element.rs

    1use crate::{
    2    ActiveDiagnostic, BlockId, CURSORS_VISIBLE_FOR, ChunkRendererContext, ChunkReplacement,
    3    CodeActionSource, ColumnarMode, ConflictsOurs, ConflictsOursMarker, ConflictsOuter,
    4    ConflictsTheirs, ConflictsTheirsMarker, ContextMenuPlacement, CursorShape, CustomBlockId,
    5    DisplayDiffHunk, DisplayPoint, DisplayRow, DocumentHighlightRead, DocumentHighlightWrite,
    6    EditDisplayMode, EditPrediction, Editor, EditorMode, EditorSettings, EditorSnapshot,
    7    EditorStyle, FILE_HEADER_HEIGHT, FocusedBlock, GutterDimensions, HalfPageDown, HalfPageUp,
    8    HandleInput, HoveredCursor, InlayHintRefreshReason, JumpData, LineDown, LineHighlight, LineUp,
    9    MAX_LINE_LEN, MINIMAP_FONT_SIZE, MULTI_BUFFER_EXCERPT_HEADER_HEIGHT, OpenExcerpts, PageDown,
   10    PageUp, PhantomBreakpointIndicator, Point, RowExt, RowRangeExt, SelectPhase,
   11    SelectedTextHighlight, Selection, SelectionDragState, SoftWrap, StickyHeaderExcerpt, ToPoint,
   12    ToggleFold, ToggleFoldAll,
   13    code_context_menus::{CodeActionsMenu, MENU_ASIDE_MAX_WIDTH, MENU_ASIDE_MIN_WIDTH, MENU_GAP},
   14    display_map::{
   15        Block, BlockContext, BlockStyle, ChunkRendererId, DisplaySnapshot, EditorMargins,
   16        HighlightKey, HighlightedChunk, ToDisplayPoint,
   17    },
   18    editor_settings::{
   19        CurrentLineHighlight, DocumentColorsRenderMode, DoubleClickInMultibuffer, Minimap,
   20        MinimapThumb, MinimapThumbBorder, ScrollBeyondLastLine, ScrollbarAxes,
   21        ScrollbarDiagnostics, ShowMinimap, ShowScrollbar,
   22    },
   23    git::blame::{BlameRenderer, GitBlame, GlobalBlameRenderer},
   24    hover_popover::{
   25        self, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
   26        POPOVER_RIGHT_OFFSET, hover_at,
   27    },
   28    inlay_hint_settings,
   29    items::BufferSearchHighlights,
   30    mouse_context_menu::{self, MenuPosition},
   31    scroll::{ActiveScrollbarState, ScrollbarThumbState, scroll_amount::ScrollAmount},
   32};
   33use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
   34use collections::{BTreeMap, HashMap};
   35use file_icons::FileIcons;
   36use git::{
   37    Oid,
   38    blame::{BlameEntry, ParsedCommitMessage},
   39    status::FileStatus,
   40};
   41use gpui::{
   42    Action, Along, AnyElement, App, AppContext, AvailableSpace, Axis as ScrollbarAxis, BorderStyle,
   43    Bounds, ClickEvent, ClipboardItem, ContentMask, Context, Corner, Corners, CursorStyle,
   44    DispatchPhase, Edges, Element, ElementInputHandler, Entity, Focusable as _, FontId,
   45    GlobalElementId, Hitbox, HitboxBehavior, Hsla, InteractiveElement, IntoElement, IsZero,
   46    Keystroke, Length, ModifiersChangedEvent, MouseButton, MouseClickEvent, MouseDownEvent,
   47    MouseMoveEvent, MouseUpEvent, PaintQuad, ParentElement, Pixels, ScrollDelta, ScrollHandle,
   48    ScrollWheelEvent, ShapedLine, SharedString, Size, StatefulInteractiveElement, Style, Styled,
   49    TextRun, TextStyleRefinement, WeakEntity, Window, anchored, deferred, div, fill,
   50    linear_color_stop, linear_gradient, outline, point, px, quad, relative, size, solid_background,
   51    transparent_black,
   52};
   53use itertools::Itertools;
   54use language::language_settings::{
   55    IndentGuideBackgroundColoring, IndentGuideColoring, IndentGuideSettings, ShowWhitespaceSetting,
   56};
   57use markdown::Markdown;
   58use multi_buffer::{
   59    Anchor, ExcerptId, ExcerptInfo, ExpandExcerptDirection, ExpandInfo, MultiBufferPoint,
   60    MultiBufferRow, RowInfo,
   61};
   62
   63use project::{
   64    Entry, ProjectPath,
   65    debugger::breakpoint_store::{Breakpoint, BreakpointSessionState},
   66    project_settings::{GitGutterSetting, GitHunkStyleSetting, ProjectSettings},
   67};
   68use settings::Settings;
   69use smallvec::{SmallVec, smallvec};
   70use std::{
   71    any::TypeId,
   72    borrow::Cow,
   73    cmp::{self, Ordering},
   74    fmt::{self, Write},
   75    iter, mem,
   76    ops::{Deref, Range},
   77    rc::Rc,
   78    sync::Arc,
   79    time::{Duration, Instant},
   80};
   81use sum_tree::Bias;
   82use text::{BufferId, SelectionGoal};
   83use theme::{ActiveTheme, Appearance, BufferLineHeight, PlayerColor};
   84use ui::{
   85    ButtonLike, ContextMenu, Indicator, KeyBinding, POPOVER_Y_PADDING, Tooltip, h_flex, prelude::*,
   86    right_click_menu,
   87};
   88use unicode_segmentation::UnicodeSegmentation;
   89use util::post_inc;
   90use util::{RangeExt, ResultExt, debug_panic};
   91use workspace::{
   92    CollaboratorId, OpenInTerminal, OpenTerminal, RevealInProjectPanel, Workspace, item::Item,
   93    notifications::NotifyTaskExt,
   94};
   95
   96/// Determines what kinds of highlights should be applied to a lines background.
   97#[derive(Clone, Copy, Default)]
   98struct LineHighlightSpec {
   99    selection: bool,
  100    breakpoint: bool,
  101    _active_stack_frame: bool,
  102}
  103
  104#[derive(Debug)]
  105struct SelectionLayout {
  106    head: DisplayPoint,
  107    cursor_shape: CursorShape,
  108    is_newest: bool,
  109    is_local: bool,
  110    range: Range<DisplayPoint>,
  111    active_rows: Range<DisplayRow>,
  112    user_name: Option<SharedString>,
  113}
  114
  115struct InlineBlameLayout {
  116    element: AnyElement,
  117    bounds: Bounds<Pixels>,
  118    entry: BlameEntry,
  119}
  120
  121impl SelectionLayout {
  122    fn new<T: ToPoint + ToDisplayPoint + Clone>(
  123        selection: Selection<T>,
  124        line_mode: bool,
  125        cursor_shape: CursorShape,
  126        map: &DisplaySnapshot,
  127        is_newest: bool,
  128        is_local: bool,
  129        user_name: Option<SharedString>,
  130    ) -> Self {
  131        let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
  132        let display_selection = point_selection.map(|p| p.to_display_point(map));
  133        let mut range = display_selection.range();
  134        let mut head = display_selection.head();
  135        let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
  136            ..map.next_line_boundary(point_selection.end).1.row();
  137
  138        // vim visual line mode
  139        if line_mode {
  140            let point_range = map.expand_to_line(point_selection.range());
  141            range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
  142        }
  143
  144        // any vim visual mode (including line mode)
  145        if (cursor_shape == CursorShape::Block || cursor_shape == CursorShape::Hollow)
  146            && !range.is_empty()
  147            && !selection.reversed
  148        {
  149            if head.column() > 0 {
  150                head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
  151            } else if head.row().0 > 0 && head != map.max_point() {
  152                head = map.clip_point(
  153                    DisplayPoint::new(
  154                        head.row().previous_row(),
  155                        map.line_len(head.row().previous_row()),
  156                    ),
  157                    Bias::Left,
  158                );
  159                // updating range.end is a no-op unless you're cursor is
  160                // on the newline containing a multi-buffer divider
  161                // in which case the clip_point may have moved the head up
  162                // an additional row.
  163                range.end = DisplayPoint::new(head.row().next_row(), 0);
  164                active_rows.end = head.row();
  165            }
  166        }
  167
  168        Self {
  169            head,
  170            cursor_shape,
  171            is_newest,
  172            is_local,
  173            range,
  174            active_rows,
  175            user_name,
  176        }
  177    }
  178}
  179
  180pub struct EditorElement {
  181    editor: Entity<Editor>,
  182    style: EditorStyle,
  183}
  184
  185type DisplayRowDelta = u32;
  186
  187impl EditorElement {
  188    pub(crate) const SCROLLBAR_WIDTH: Pixels = px(15.);
  189
  190    pub fn new(editor: &Entity<Editor>, style: EditorStyle) -> Self {
  191        Self {
  192            editor: editor.clone(),
  193            style,
  194        }
  195    }
  196
  197    fn register_actions(&self, window: &mut Window, cx: &mut App) {
  198        let editor = &self.editor;
  199        editor.update(cx, |editor, cx| {
  200            for action in editor.editor_actions.borrow().values() {
  201                (action)(editor, window, cx)
  202            }
  203        });
  204
  205        crate::rust_analyzer_ext::apply_related_actions(editor, window, cx);
  206        crate::clangd_ext::apply_related_actions(editor, window, cx);
  207
  208        register_action(editor, window, Editor::open_context_menu);
  209        register_action(editor, window, Editor::move_left);
  210        register_action(editor, window, Editor::move_right);
  211        register_action(editor, window, Editor::move_down);
  212        register_action(editor, window, Editor::move_down_by_lines);
  213        register_action(editor, window, Editor::select_down_by_lines);
  214        register_action(editor, window, Editor::move_up);
  215        register_action(editor, window, Editor::move_up_by_lines);
  216        register_action(editor, window, Editor::select_up_by_lines);
  217        register_action(editor, window, Editor::select_page_down);
  218        register_action(editor, window, Editor::select_page_up);
  219        register_action(editor, window, Editor::cancel);
  220        register_action(editor, window, Editor::newline);
  221        register_action(editor, window, Editor::newline_above);
  222        register_action(editor, window, Editor::newline_below);
  223        register_action(editor, window, Editor::backspace);
  224        register_action(editor, window, Editor::blame_hover);
  225        register_action(editor, window, Editor::delete);
  226        register_action(editor, window, Editor::tab);
  227        register_action(editor, window, Editor::backtab);
  228        register_action(editor, window, Editor::indent);
  229        register_action(editor, window, Editor::outdent);
  230        register_action(editor, window, Editor::autoindent);
  231        register_action(editor, window, Editor::delete_line);
  232        register_action(editor, window, Editor::join_lines);
  233        register_action(editor, window, Editor::sort_lines_by_length);
  234        register_action(editor, window, Editor::sort_lines_case_sensitive);
  235        register_action(editor, window, Editor::sort_lines_case_insensitive);
  236        register_action(editor, window, Editor::reverse_lines);
  237        register_action(editor, window, Editor::shuffle_lines);
  238        register_action(editor, window, Editor::convert_indentation_to_spaces);
  239        register_action(editor, window, Editor::convert_indentation_to_tabs);
  240        register_action(editor, window, Editor::convert_to_upper_case);
  241        register_action(editor, window, Editor::convert_to_lower_case);
  242        register_action(editor, window, Editor::convert_to_title_case);
  243        register_action(editor, window, Editor::convert_to_snake_case);
  244        register_action(editor, window, Editor::convert_to_kebab_case);
  245        register_action(editor, window, Editor::convert_to_upper_camel_case);
  246        register_action(editor, window, Editor::convert_to_lower_camel_case);
  247        register_action(editor, window, Editor::convert_to_opposite_case);
  248        register_action(editor, window, Editor::convert_to_sentence_case);
  249        register_action(editor, window, Editor::toggle_case);
  250        register_action(editor, window, Editor::convert_to_rot13);
  251        register_action(editor, window, Editor::convert_to_rot47);
  252        register_action(editor, window, Editor::delete_to_previous_word_start);
  253        register_action(editor, window, Editor::delete_to_previous_subword_start);
  254        register_action(editor, window, Editor::delete_to_next_word_end);
  255        register_action(editor, window, Editor::delete_to_next_subword_end);
  256        register_action(editor, window, Editor::delete_to_beginning_of_line);
  257        register_action(editor, window, Editor::delete_to_end_of_line);
  258        register_action(editor, window, Editor::cut_to_end_of_line);
  259        register_action(editor, window, Editor::duplicate_line_up);
  260        register_action(editor, window, Editor::duplicate_line_down);
  261        register_action(editor, window, Editor::duplicate_selection);
  262        register_action(editor, window, Editor::move_line_up);
  263        register_action(editor, window, Editor::move_line_down);
  264        register_action(editor, window, Editor::transpose);
  265        register_action(editor, window, Editor::rewrap);
  266        register_action(editor, window, Editor::cut);
  267        register_action(editor, window, Editor::kill_ring_cut);
  268        register_action(editor, window, Editor::kill_ring_yank);
  269        register_action(editor, window, Editor::copy);
  270        register_action(editor, window, Editor::copy_and_trim);
  271        register_action(editor, window, Editor::diff_clipboard_with_selection);
  272        register_action(editor, window, Editor::paste);
  273        register_action(editor, window, Editor::undo);
  274        register_action(editor, window, Editor::redo);
  275        register_action(editor, window, Editor::move_page_up);
  276        register_action(editor, window, Editor::move_page_down);
  277        register_action(editor, window, Editor::next_screen);
  278        register_action(editor, window, Editor::scroll_cursor_top);
  279        register_action(editor, window, Editor::scroll_cursor_center);
  280        register_action(editor, window, Editor::scroll_cursor_bottom);
  281        register_action(editor, window, Editor::scroll_cursor_center_top_bottom);
  282        register_action(editor, window, |editor, _: &LineDown, window, cx| {
  283            editor.scroll_screen(&ScrollAmount::Line(1.), window, cx)
  284        });
  285        register_action(editor, window, |editor, _: &LineUp, window, cx| {
  286            editor.scroll_screen(&ScrollAmount::Line(-1.), window, cx)
  287        });
  288        register_action(editor, window, |editor, _: &HalfPageDown, window, cx| {
  289            editor.scroll_screen(&ScrollAmount::Page(0.5), window, cx)
  290        });
  291        register_action(
  292            editor,
  293            window,
  294            |editor, HandleInput(text): &HandleInput, window, cx| {
  295                if text.is_empty() {
  296                    return;
  297                }
  298                editor.handle_input(text, window, cx);
  299            },
  300        );
  301        register_action(editor, window, |editor, _: &HalfPageUp, window, cx| {
  302            editor.scroll_screen(&ScrollAmount::Page(-0.5), window, cx)
  303        });
  304        register_action(editor, window, |editor, _: &PageDown, window, cx| {
  305            editor.scroll_screen(&ScrollAmount::Page(1.), window, cx)
  306        });
  307        register_action(editor, window, |editor, _: &PageUp, window, cx| {
  308            editor.scroll_screen(&ScrollAmount::Page(-1.), window, cx)
  309        });
  310        register_action(editor, window, Editor::move_to_previous_word_start);
  311        register_action(editor, window, Editor::move_to_previous_subword_start);
  312        register_action(editor, window, Editor::move_to_next_word_end);
  313        register_action(editor, window, Editor::move_to_next_subword_end);
  314        register_action(editor, window, Editor::move_to_beginning_of_line);
  315        register_action(editor, window, Editor::move_to_end_of_line);
  316        register_action(editor, window, Editor::move_to_start_of_paragraph);
  317        register_action(editor, window, Editor::move_to_end_of_paragraph);
  318        register_action(editor, window, Editor::move_to_beginning);
  319        register_action(editor, window, Editor::move_to_end);
  320        register_action(editor, window, Editor::move_to_start_of_excerpt);
  321        register_action(editor, window, Editor::move_to_start_of_next_excerpt);
  322        register_action(editor, window, Editor::move_to_end_of_excerpt);
  323        register_action(editor, window, Editor::move_to_end_of_previous_excerpt);
  324        register_action(editor, window, Editor::select_up);
  325        register_action(editor, window, Editor::select_down);
  326        register_action(editor, window, Editor::select_left);
  327        register_action(editor, window, Editor::select_right);
  328        register_action(editor, window, Editor::select_to_previous_word_start);
  329        register_action(editor, window, Editor::select_to_previous_subword_start);
  330        register_action(editor, window, Editor::select_to_next_word_end);
  331        register_action(editor, window, Editor::select_to_next_subword_end);
  332        register_action(editor, window, Editor::select_to_beginning_of_line);
  333        register_action(editor, window, Editor::select_to_end_of_line);
  334        register_action(editor, window, Editor::select_to_start_of_paragraph);
  335        register_action(editor, window, Editor::select_to_end_of_paragraph);
  336        register_action(editor, window, Editor::select_to_start_of_excerpt);
  337        register_action(editor, window, Editor::select_to_start_of_next_excerpt);
  338        register_action(editor, window, Editor::select_to_end_of_excerpt);
  339        register_action(editor, window, Editor::select_to_end_of_previous_excerpt);
  340        register_action(editor, window, Editor::select_to_beginning);
  341        register_action(editor, window, Editor::select_to_end);
  342        register_action(editor, window, Editor::select_all);
  343        register_action(editor, window, |editor, action, window, cx| {
  344            editor.select_all_matches(action, window, cx).log_err();
  345        });
  346        register_action(editor, window, Editor::select_line);
  347        register_action(editor, window, Editor::split_selection_into_lines);
  348        register_action(editor, window, Editor::add_selection_above);
  349        register_action(editor, window, Editor::add_selection_below);
  350        register_action(editor, window, |editor, action, window, cx| {
  351            editor.select_next(action, window, cx).log_err();
  352        });
  353        register_action(editor, window, |editor, action, window, cx| {
  354            editor.select_previous(action, window, cx).log_err();
  355        });
  356        register_action(editor, window, |editor, action, window, cx| {
  357            editor.find_next_match(action, window, cx).log_err();
  358        });
  359        register_action(editor, window, |editor, action, window, cx| {
  360            editor.find_previous_match(action, window, cx).log_err();
  361        });
  362        register_action(editor, window, Editor::toggle_comments);
  363        register_action(editor, window, Editor::select_larger_syntax_node);
  364        register_action(editor, window, Editor::select_smaller_syntax_node);
  365        register_action(editor, window, Editor::unwrap_syntax_node);
  366        register_action(editor, window, Editor::select_enclosing_symbol);
  367        register_action(editor, window, Editor::move_to_enclosing_bracket);
  368        register_action(editor, window, Editor::undo_selection);
  369        register_action(editor, window, Editor::redo_selection);
  370        if !editor.read(cx).is_singleton(cx) {
  371            register_action(editor, window, Editor::expand_excerpts);
  372            register_action(editor, window, Editor::expand_excerpts_up);
  373            register_action(editor, window, Editor::expand_excerpts_down);
  374        }
  375        register_action(editor, window, Editor::go_to_diagnostic);
  376        register_action(editor, window, Editor::go_to_prev_diagnostic);
  377        register_action(editor, window, Editor::go_to_next_hunk);
  378        register_action(editor, window, Editor::go_to_prev_hunk);
  379        register_action(editor, window, |editor, action, window, cx| {
  380            editor
  381                .go_to_definition(action, window, cx)
  382                .detach_and_log_err(cx);
  383        });
  384        register_action(editor, window, |editor, action, window, cx| {
  385            editor
  386                .go_to_definition_split(action, window, cx)
  387                .detach_and_log_err(cx);
  388        });
  389        register_action(editor, window, |editor, action, window, cx| {
  390            editor
  391                .go_to_declaration(action, window, cx)
  392                .detach_and_log_err(cx);
  393        });
  394        register_action(editor, window, |editor, action, window, cx| {
  395            editor
  396                .go_to_declaration_split(action, window, cx)
  397                .detach_and_log_err(cx);
  398        });
  399        register_action(editor, window, |editor, action, window, cx| {
  400            editor
  401                .go_to_implementation(action, window, cx)
  402                .detach_and_log_err(cx);
  403        });
  404        register_action(editor, window, |editor, action, window, cx| {
  405            editor
  406                .go_to_implementation_split(action, window, cx)
  407                .detach_and_log_err(cx);
  408        });
  409        register_action(editor, window, |editor, action, window, cx| {
  410            editor
  411                .go_to_type_definition(action, window, cx)
  412                .detach_and_log_err(cx);
  413        });
  414        register_action(editor, window, |editor, action, window, cx| {
  415            editor
  416                .go_to_type_definition_split(action, window, cx)
  417                .detach_and_log_err(cx);
  418        });
  419        register_action(editor, window, Editor::open_url);
  420        register_action(editor, window, Editor::open_selected_filename);
  421        register_action(editor, window, Editor::fold);
  422        register_action(editor, window, Editor::fold_at_level);
  423        register_action(editor, window, Editor::fold_all);
  424        register_action(editor, window, Editor::fold_function_bodies);
  425        register_action(editor, window, Editor::fold_recursive);
  426        register_action(editor, window, Editor::toggle_fold);
  427        register_action(editor, window, Editor::toggle_fold_recursive);
  428        register_action(editor, window, Editor::toggle_fold_all);
  429        register_action(editor, window, Editor::unfold_lines);
  430        register_action(editor, window, Editor::unfold_recursive);
  431        register_action(editor, window, Editor::unfold_all);
  432        register_action(editor, window, Editor::fold_selected_ranges);
  433        register_action(editor, window, Editor::set_mark);
  434        register_action(editor, window, Editor::swap_selection_ends);
  435        register_action(editor, window, Editor::show_completions);
  436        register_action(editor, window, Editor::show_word_completions);
  437        register_action(editor, window, Editor::toggle_code_actions);
  438        register_action(editor, window, Editor::open_excerpts);
  439        register_action(editor, window, Editor::open_excerpts_in_split);
  440        register_action(editor, window, Editor::open_proposed_changes_editor);
  441        register_action(editor, window, Editor::toggle_soft_wrap);
  442        register_action(editor, window, Editor::toggle_tab_bar);
  443        register_action(editor, window, Editor::toggle_line_numbers);
  444        register_action(editor, window, Editor::toggle_relative_line_numbers);
  445        register_action(editor, window, Editor::toggle_indent_guides);
  446        register_action(editor, window, Editor::toggle_inlay_hints);
  447        register_action(editor, window, Editor::toggle_edit_predictions);
  448        if editor.read(cx).diagnostics_enabled() {
  449            register_action(editor, window, Editor::toggle_diagnostics);
  450        }
  451        if editor.read(cx).inline_diagnostics_enabled() {
  452            register_action(editor, window, Editor::toggle_inline_diagnostics);
  453        }
  454        if editor.read(cx).supports_minimap(cx) {
  455            register_action(editor, window, Editor::toggle_minimap);
  456        }
  457        register_action(editor, window, hover_popover::hover);
  458        register_action(editor, window, Editor::reveal_in_finder);
  459        register_action(editor, window, Editor::copy_path);
  460        register_action(editor, window, Editor::copy_relative_path);
  461        register_action(editor, window, Editor::copy_file_name);
  462        register_action(editor, window, Editor::copy_file_name_without_extension);
  463        register_action(editor, window, Editor::copy_highlight_json);
  464        register_action(editor, window, Editor::copy_permalink_to_line);
  465        register_action(editor, window, Editor::open_permalink_to_line);
  466        register_action(editor, window, Editor::copy_file_location);
  467        register_action(editor, window, Editor::toggle_git_blame);
  468        register_action(editor, window, Editor::toggle_git_blame_inline);
  469        register_action(editor, window, Editor::open_git_blame_commit);
  470        register_action(editor, window, Editor::toggle_selected_diff_hunks);
  471        register_action(editor, window, Editor::toggle_staged_selected_diff_hunks);
  472        register_action(editor, window, Editor::stage_and_next);
  473        register_action(editor, window, Editor::unstage_and_next);
  474        register_action(editor, window, Editor::expand_all_diff_hunks);
  475        register_action(editor, window, Editor::go_to_previous_change);
  476        register_action(editor, window, Editor::go_to_next_change);
  477
  478        register_action(editor, window, |editor, action, window, cx| {
  479            if let Some(task) = editor.format(action, window, cx) {
  480                task.detach_and_notify_err(window, cx);
  481            } else {
  482                cx.propagate();
  483            }
  484        });
  485        register_action(editor, window, |editor, action, window, cx| {
  486            if let Some(task) = editor.format_selections(action, window, cx) {
  487                task.detach_and_notify_err(window, cx);
  488            } else {
  489                cx.propagate();
  490            }
  491        });
  492        register_action(editor, window, |editor, action, window, cx| {
  493            if let Some(task) = editor.organize_imports(action, window, cx) {
  494                task.detach_and_notify_err(window, cx);
  495            } else {
  496                cx.propagate();
  497            }
  498        });
  499        register_action(editor, window, Editor::restart_language_server);
  500        register_action(editor, window, Editor::stop_language_server);
  501        register_action(editor, window, Editor::show_character_palette);
  502        register_action(editor, window, |editor, action, window, cx| {
  503            if let Some(task) = editor.confirm_completion(action, window, cx) {
  504                task.detach_and_notify_err(window, cx);
  505            } else {
  506                cx.propagate();
  507            }
  508        });
  509        register_action(editor, window, |editor, action, window, cx| {
  510            if let Some(task) = editor.confirm_completion_replace(action, window, cx) {
  511                task.detach_and_notify_err(window, cx);
  512            } else {
  513                cx.propagate();
  514            }
  515        });
  516        register_action(editor, window, |editor, action, window, cx| {
  517            if let Some(task) = editor.confirm_completion_insert(action, window, cx) {
  518                task.detach_and_notify_err(window, cx);
  519            } else {
  520                cx.propagate();
  521            }
  522        });
  523        register_action(editor, window, |editor, action, window, cx| {
  524            if let Some(task) = editor.compose_completion(action, window, cx) {
  525                task.detach_and_notify_err(window, cx);
  526            } else {
  527                cx.propagate();
  528            }
  529        });
  530        register_action(editor, window, |editor, action, window, cx| {
  531            if let Some(task) = editor.confirm_code_action(action, window, cx) {
  532                task.detach_and_notify_err(window, cx);
  533            } else {
  534                cx.propagate();
  535            }
  536        });
  537        register_action(editor, window, |editor, action, window, cx| {
  538            if let Some(task) = editor.rename(action, window, cx) {
  539                task.detach_and_notify_err(window, cx);
  540            } else {
  541                cx.propagate();
  542            }
  543        });
  544        register_action(editor, window, |editor, action, window, cx| {
  545            if let Some(task) = editor.confirm_rename(action, window, cx) {
  546                task.detach_and_notify_err(window, cx);
  547            } else {
  548                cx.propagate();
  549            }
  550        });
  551        register_action(editor, window, |editor, action, window, cx| {
  552            if let Some(task) = editor.find_all_references(action, window, cx) {
  553                task.detach_and_log_err(cx);
  554            } else {
  555                cx.propagate();
  556            }
  557        });
  558        register_action(editor, window, Editor::show_signature_help);
  559        register_action(editor, window, Editor::signature_help_prev);
  560        register_action(editor, window, Editor::signature_help_next);
  561        register_action(editor, window, Editor::next_edit_prediction);
  562        register_action(editor, window, Editor::previous_edit_prediction);
  563        register_action(editor, window, Editor::show_edit_prediction);
  564        register_action(editor, window, Editor::context_menu_first);
  565        register_action(editor, window, Editor::context_menu_prev);
  566        register_action(editor, window, Editor::context_menu_next);
  567        register_action(editor, window, Editor::context_menu_last);
  568        register_action(editor, window, Editor::display_cursor_names);
  569        register_action(editor, window, Editor::unique_lines_case_insensitive);
  570        register_action(editor, window, Editor::unique_lines_case_sensitive);
  571        register_action(editor, window, Editor::accept_partial_edit_prediction);
  572        register_action(editor, window, Editor::accept_edit_prediction);
  573        register_action(editor, window, Editor::restore_file);
  574        register_action(editor, window, Editor::git_restore);
  575        register_action(editor, window, Editor::apply_all_diff_hunks);
  576        register_action(editor, window, Editor::apply_selected_diff_hunks);
  577        register_action(editor, window, Editor::open_active_item_in_terminal);
  578        register_action(editor, window, Editor::reload_file);
  579        register_action(editor, window, Editor::spawn_nearest_task);
  580        register_action(editor, window, Editor::insert_uuid_v4);
  581        register_action(editor, window, Editor::insert_uuid_v7);
  582        register_action(editor, window, Editor::open_selections_in_multibuffer);
  583        register_action(editor, window, Editor::toggle_breakpoint);
  584        register_action(editor, window, Editor::edit_log_breakpoint);
  585        register_action(editor, window, Editor::enable_breakpoint);
  586        register_action(editor, window, Editor::disable_breakpoint);
  587    }
  588
  589    fn register_key_listeners(&self, window: &mut Window, _: &mut App, layout: &EditorLayout) {
  590        let position_map = layout.position_map.clone();
  591        window.on_key_event({
  592            let editor = self.editor.clone();
  593            move |event: &ModifiersChangedEvent, phase, window, cx| {
  594                if phase != DispatchPhase::Bubble {
  595                    return;
  596                }
  597                editor.update(cx, |editor, cx| {
  598                    let inlay_hint_settings = inlay_hint_settings(
  599                        editor.selections.newest_anchor().head(),
  600                        &editor.buffer.read(cx).snapshot(cx),
  601                        cx,
  602                    );
  603
  604                    if let Some(inlay_modifiers) = inlay_hint_settings
  605                        .toggle_on_modifiers_press
  606                        .as_ref()
  607                        .filter(|modifiers| modifiers.modified())
  608                    {
  609                        editor.refresh_inlay_hints(
  610                            InlayHintRefreshReason::ModifiersChanged(
  611                                inlay_modifiers == &event.modifiers,
  612                            ),
  613                            cx,
  614                        );
  615                    }
  616
  617                    if editor.hover_state.focused(window, cx) {
  618                        return;
  619                    }
  620
  621                    editor.handle_modifiers_changed(event.modifiers, &position_map, window, cx);
  622                })
  623            }
  624        });
  625    }
  626
  627    fn mouse_left_down(
  628        editor: &mut Editor,
  629        event: &MouseDownEvent,
  630        hovered_hunk: Option<Range<Anchor>>,
  631        position_map: &PositionMap,
  632        line_numbers: &HashMap<MultiBufferRow, LineNumberLayout>,
  633        window: &mut Window,
  634        cx: &mut Context<Editor>,
  635    ) {
  636        if window.default_prevented() {
  637            return;
  638        }
  639
  640        let text_hitbox = &position_map.text_hitbox;
  641        let gutter_hitbox = &position_map.gutter_hitbox;
  642        let point_for_position = position_map.point_for_position(event.position);
  643        let mut click_count = event.click_count;
  644        let mut modifiers = event.modifiers;
  645
  646        if let Some(hovered_hunk) = hovered_hunk {
  647            editor.toggle_single_diff_hunk(hovered_hunk, cx);
  648            cx.notify();
  649            return;
  650        } else if gutter_hitbox.is_hovered(window) {
  651            click_count = 3; // Simulate triple-click when clicking the gutter to select lines
  652        } else if !text_hitbox.is_hovered(window) {
  653            return;
  654        }
  655
  656        if EditorSettings::get_global(cx)
  657            .drag_and_drop_selection
  658            .enabled
  659            && click_count == 1
  660        {
  661            let newest_anchor = editor.selections.newest_anchor();
  662            let snapshot = editor.snapshot(window, cx);
  663            let selection = newest_anchor.map(|anchor| anchor.to_display_point(&snapshot));
  664            if point_for_position.intersects_selection(&selection) {
  665                editor.selection_drag_state = SelectionDragState::ReadyToDrag {
  666                    selection: newest_anchor.clone(),
  667                    click_position: event.position,
  668                    mouse_down_time: Instant::now(),
  669                };
  670                cx.stop_propagation();
  671                return;
  672            }
  673        }
  674
  675        let is_singleton = editor.buffer().read(cx).is_singleton();
  676
  677        if click_count == 2 && !is_singleton {
  678            match EditorSettings::get_global(cx).double_click_in_multibuffer {
  679                DoubleClickInMultibuffer::Select => {
  680                    // do nothing special on double click, all selection logic is below
  681                }
  682                DoubleClickInMultibuffer::Open => {
  683                    if modifiers.alt {
  684                        // if double click is made with alt, pretend it's a regular double click without opening and alt,
  685                        // and run the selection logic.
  686                        modifiers.alt = false;
  687                    } else {
  688                        let scroll_position_row =
  689                            position_map.scroll_pixel_position.y / position_map.line_height;
  690                        let display_row = (((event.position - gutter_hitbox.bounds.origin).y
  691                            + position_map.scroll_pixel_position.y)
  692                            / position_map.line_height)
  693                            as u32;
  694                        let multi_buffer_row = position_map
  695                            .snapshot
  696                            .display_point_to_point(
  697                                DisplayPoint::new(DisplayRow(display_row), 0),
  698                                Bias::Right,
  699                            )
  700                            .row;
  701                        let line_offset_from_top = display_row - scroll_position_row as u32;
  702                        // if double click is made without alt, open the corresponding excerp
  703                        editor.open_excerpts_common(
  704                            Some(JumpData::MultiBufferRow {
  705                                row: MultiBufferRow(multi_buffer_row),
  706                                line_offset_from_top,
  707                            }),
  708                            false,
  709                            window,
  710                            cx,
  711                        );
  712                        return;
  713                    }
  714                }
  715            }
  716        }
  717
  718        let position = point_for_position.previous_valid;
  719        if let Some(mode) = Editor::columnar_selection_mode(&modifiers, cx) {
  720            editor.select(
  721                SelectPhase::BeginColumnar {
  722                    position,
  723                    reset: match mode {
  724                        ColumnarMode::FromMouse => true,
  725                        ColumnarMode::FromSelection => false,
  726                    },
  727                    mode: mode,
  728                    goal_column: point_for_position.exact_unclipped.column(),
  729                },
  730                window,
  731                cx,
  732            );
  733        } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
  734        {
  735            editor.select(
  736                SelectPhase::Extend {
  737                    position,
  738                    click_count,
  739                },
  740                window,
  741                cx,
  742            );
  743        } else {
  744            editor.select(
  745                SelectPhase::Begin {
  746                    position,
  747                    add: Editor::multi_cursor_modifier(true, &modifiers, cx),
  748                    click_count,
  749                },
  750                window,
  751                cx,
  752            );
  753        }
  754        cx.stop_propagation();
  755
  756        if !is_singleton {
  757            let display_row = (((event.position - gutter_hitbox.bounds.origin).y
  758                + position_map.scroll_pixel_position.y)
  759                / position_map.line_height) as u32;
  760            let multi_buffer_row = position_map
  761                .snapshot
  762                .display_point_to_point(DisplayPoint::new(DisplayRow(display_row), 0), Bias::Right)
  763                .row;
  764            if line_numbers
  765                .get(&MultiBufferRow(multi_buffer_row))
  766                .and_then(|line_number| line_number.hitbox.as_ref())
  767                .is_some_and(|hitbox| hitbox.contains(&event.position))
  768            {
  769                let scroll_position_row =
  770                    position_map.scroll_pixel_position.y / position_map.line_height;
  771                let line_offset_from_top = display_row - scroll_position_row as u32;
  772
  773                editor.open_excerpts_common(
  774                    Some(JumpData::MultiBufferRow {
  775                        row: MultiBufferRow(multi_buffer_row),
  776                        line_offset_from_top,
  777                    }),
  778                    modifiers.alt,
  779                    window,
  780                    cx,
  781                );
  782                cx.stop_propagation();
  783            }
  784        }
  785    }
  786
  787    fn mouse_right_down(
  788        editor: &mut Editor,
  789        event: &MouseDownEvent,
  790        position_map: &PositionMap,
  791        window: &mut Window,
  792        cx: &mut Context<Editor>,
  793    ) {
  794        if position_map.gutter_hitbox.is_hovered(window) {
  795            let gutter_right_padding = editor.gutter_dimensions.right_padding;
  796            let hitbox = &position_map.gutter_hitbox;
  797
  798            if event.position.x <= hitbox.bounds.right() - gutter_right_padding {
  799                let point_for_position = position_map.point_for_position(event.position);
  800                editor.set_breakpoint_context_menu(
  801                    point_for_position.previous_valid.row(),
  802                    None,
  803                    event.position,
  804                    window,
  805                    cx,
  806                );
  807            }
  808            return;
  809        }
  810
  811        if !position_map.text_hitbox.is_hovered(window) {
  812            return;
  813        }
  814
  815        let point_for_position = position_map.point_for_position(event.position);
  816        mouse_context_menu::deploy_context_menu(
  817            editor,
  818            Some(event.position),
  819            point_for_position.previous_valid,
  820            window,
  821            cx,
  822        );
  823        cx.stop_propagation();
  824    }
  825
  826    fn mouse_middle_down(
  827        editor: &mut Editor,
  828        event: &MouseDownEvent,
  829        position_map: &PositionMap,
  830        window: &mut Window,
  831        cx: &mut Context<Editor>,
  832    ) {
  833        if !position_map.text_hitbox.is_hovered(window) || window.default_prevented() {
  834            return;
  835        }
  836
  837        let point_for_position = position_map.point_for_position(event.position);
  838        let position = point_for_position.previous_valid;
  839
  840        editor.select(
  841            SelectPhase::BeginColumnar {
  842                position,
  843                reset: true,
  844                mode: ColumnarMode::FromMouse,
  845                goal_column: point_for_position.exact_unclipped.column(),
  846            },
  847            window,
  848            cx,
  849        );
  850    }
  851
  852    fn mouse_up(
  853        editor: &mut Editor,
  854        event: &MouseUpEvent,
  855        position_map: &PositionMap,
  856        window: &mut Window,
  857        cx: &mut Context<Editor>,
  858    ) {
  859        let text_hitbox = &position_map.text_hitbox;
  860        let end_selection = editor.has_pending_selection();
  861        let pending_nonempty_selections = editor.has_pending_nonempty_selection();
  862        let point_for_position = position_map.point_for_position(event.position);
  863
  864        match editor.selection_drag_state {
  865            SelectionDragState::ReadyToDrag {
  866                selection: _,
  867                ref click_position,
  868                mouse_down_time: _,
  869            } => {
  870                if event.position == *click_position {
  871                    editor.select(
  872                        SelectPhase::Begin {
  873                            position: point_for_position.previous_valid,
  874                            add: false,
  875                            click_count: 1, // ready to drag state only occurs on click count 1
  876                        },
  877                        window,
  878                        cx,
  879                    );
  880                    editor.selection_drag_state = SelectionDragState::None;
  881                    cx.stop_propagation();
  882                    return;
  883                } else {
  884                    debug_panic!("drag state can never be in ready state after drag")
  885                }
  886            }
  887            SelectionDragState::Dragging { ref selection, .. } => {
  888                let snapshot = editor.snapshot(window, cx);
  889                let selection_display = selection.map(|anchor| anchor.to_display_point(&snapshot));
  890                if !point_for_position.intersects_selection(&selection_display)
  891                    && text_hitbox.is_hovered(window)
  892                {
  893                    let is_cut = !(cfg!(target_os = "macos") && event.modifiers.alt
  894                        || cfg!(not(target_os = "macos")) && event.modifiers.control);
  895                    editor.move_selection_on_drop(
  896                        &selection.clone(),
  897                        point_for_position.previous_valid,
  898                        is_cut,
  899                        window,
  900                        cx,
  901                    );
  902                }
  903                editor.selection_drag_state = SelectionDragState::None;
  904                cx.stop_propagation();
  905                cx.notify();
  906                return;
  907            }
  908            _ => {}
  909        }
  910
  911        if end_selection {
  912            editor.select(SelectPhase::End, window, cx);
  913        }
  914
  915        if end_selection && pending_nonempty_selections {
  916            cx.stop_propagation();
  917        } else if cfg!(any(target_os = "linux", target_os = "freebsd"))
  918            && event.button == MouseButton::Middle
  919        {
  920            #[allow(
  921                clippy::collapsible_if,
  922                clippy::needless_return,
  923                reason = "The cfg-block below makes this a false positive"
  924            )]
  925            if !text_hitbox.is_hovered(window) || editor.read_only(cx) {
  926                return;
  927            }
  928
  929            #[cfg(any(target_os = "linux", target_os = "freebsd"))]
  930            if EditorSettings::get_global(cx).middle_click_paste {
  931                if let Some(text) = cx.read_from_primary().and_then(|item| item.text()) {
  932                    let point_for_position = position_map.point_for_position(event.position);
  933                    let position = point_for_position.previous_valid;
  934
  935                    editor.select(
  936                        SelectPhase::Begin {
  937                            position,
  938                            add: false,
  939                            click_count: 1,
  940                        },
  941                        window,
  942                        cx,
  943                    );
  944                    editor.insert(&text, window, cx);
  945                }
  946                cx.stop_propagation()
  947            }
  948        }
  949    }
  950
  951    fn click(
  952        editor: &mut Editor,
  953        event: &ClickEvent,
  954        position_map: &PositionMap,
  955        window: &mut Window,
  956        cx: &mut Context<Editor>,
  957    ) {
  958        let text_hitbox = &position_map.text_hitbox;
  959        let pending_nonempty_selections = editor.has_pending_nonempty_selection();
  960
  961        let hovered_link_modifier = Editor::multi_cursor_modifier(false, &event.modifiers(), cx);
  962
  963        if let Some(mouse_position) = event.mouse_position()
  964            && !pending_nonempty_selections
  965            && hovered_link_modifier
  966            && text_hitbox.is_hovered(window)
  967        {
  968            let point = position_map.point_for_position(mouse_position);
  969            editor.handle_click_hovered_link(point, event.modifiers(), window, cx);
  970            editor.selection_drag_state = SelectionDragState::None;
  971
  972            cx.stop_propagation();
  973        }
  974    }
  975
  976    fn mouse_dragged(
  977        editor: &mut Editor,
  978        event: &MouseMoveEvent,
  979        position_map: &PositionMap,
  980        window: &mut Window,
  981        cx: &mut Context<Editor>,
  982    ) {
  983        if !editor.has_pending_selection()
  984            && matches!(editor.selection_drag_state, SelectionDragState::None)
  985        {
  986            return;
  987        }
  988
  989        let point_for_position = position_map.point_for_position(event.position);
  990        let text_hitbox = &position_map.text_hitbox;
  991
  992        let scroll_delta = {
  993            let text_bounds = text_hitbox.bounds;
  994            let mut scroll_delta = gpui::Point::<f32>::default();
  995            let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
  996            let top = text_bounds.origin.y + vertical_margin;
  997            let bottom = text_bounds.bottom_left().y - vertical_margin;
  998            if event.position.y < top {
  999                scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
 1000            }
 1001            if event.position.y > bottom {
 1002                scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
 1003            }
 1004
 1005            // We need horizontal width of text
 1006            let style = editor.style.clone().unwrap_or_default();
 1007            let font_id = window.text_system().resolve_font(&style.text.font());
 1008            let font_size = style.text.font_size.to_pixels(window.rem_size());
 1009            let em_width = window.text_system().em_width(font_id, font_size).unwrap();
 1010
 1011            let scroll_margin_x = EditorSettings::get_global(cx).horizontal_scroll_margin;
 1012
 1013            let scroll_space: Pixels = scroll_margin_x * em_width;
 1014
 1015            let left = text_bounds.origin.x + scroll_space;
 1016            let right = text_bounds.top_right().x - scroll_space;
 1017
 1018            if event.position.x < left {
 1019                scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
 1020            }
 1021            if event.position.x > right {
 1022                scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
 1023            }
 1024            scroll_delta
 1025        };
 1026
 1027        if !editor.has_pending_selection() {
 1028            let drop_anchor = position_map
 1029                .snapshot
 1030                .display_point_to_anchor(point_for_position.previous_valid, Bias::Left);
 1031            match editor.selection_drag_state {
 1032                SelectionDragState::Dragging {
 1033                    ref mut drop_cursor,
 1034                    ref mut hide_drop_cursor,
 1035                    ..
 1036                } => {
 1037                    drop_cursor.start = drop_anchor;
 1038                    drop_cursor.end = drop_anchor;
 1039                    *hide_drop_cursor = !text_hitbox.is_hovered(window);
 1040                    editor.apply_scroll_delta(scroll_delta, window, cx);
 1041                    cx.notify();
 1042                }
 1043                SelectionDragState::ReadyToDrag {
 1044                    ref selection,
 1045                    ref click_position,
 1046                    ref mouse_down_time,
 1047                } => {
 1048                    let drag_and_drop_delay = Duration::from_millis(
 1049                        EditorSettings::get_global(cx).drag_and_drop_selection.delay,
 1050                    );
 1051                    if mouse_down_time.elapsed() >= drag_and_drop_delay {
 1052                        let drop_cursor = Selection {
 1053                            id: post_inc(&mut editor.selections.next_selection_id),
 1054                            start: drop_anchor,
 1055                            end: drop_anchor,
 1056                            reversed: false,
 1057                            goal: SelectionGoal::None,
 1058                        };
 1059                        editor.selection_drag_state = SelectionDragState::Dragging {
 1060                            selection: selection.clone(),
 1061                            drop_cursor,
 1062                            hide_drop_cursor: false,
 1063                        };
 1064                        editor.apply_scroll_delta(scroll_delta, window, cx);
 1065                        cx.notify();
 1066                    } else {
 1067                        let click_point = position_map.point_for_position(*click_position);
 1068                        editor.selection_drag_state = SelectionDragState::None;
 1069                        editor.select(
 1070                            SelectPhase::Begin {
 1071                                position: click_point.previous_valid,
 1072                                add: false,
 1073                                click_count: 1,
 1074                            },
 1075                            window,
 1076                            cx,
 1077                        );
 1078                        editor.select(
 1079                            SelectPhase::Update {
 1080                                position: point_for_position.previous_valid,
 1081                                goal_column: point_for_position.exact_unclipped.column(),
 1082                                scroll_delta,
 1083                            },
 1084                            window,
 1085                            cx,
 1086                        );
 1087                    }
 1088                }
 1089                _ => {}
 1090            }
 1091        } else {
 1092            editor.select(
 1093                SelectPhase::Update {
 1094                    position: point_for_position.previous_valid,
 1095                    goal_column: point_for_position.exact_unclipped.column(),
 1096                    scroll_delta,
 1097                },
 1098                window,
 1099                cx,
 1100            );
 1101        }
 1102    }
 1103
 1104    fn mouse_moved(
 1105        editor: &mut Editor,
 1106        event: &MouseMoveEvent,
 1107        position_map: &PositionMap,
 1108        window: &mut Window,
 1109        cx: &mut Context<Editor>,
 1110    ) {
 1111        let text_hitbox = &position_map.text_hitbox;
 1112        let gutter_hitbox = &position_map.gutter_hitbox;
 1113        let modifiers = event.modifiers;
 1114        let text_hovered = text_hitbox.is_hovered(window);
 1115        let gutter_hovered = gutter_hitbox.is_hovered(window);
 1116        editor.set_gutter_hovered(gutter_hovered, cx);
 1117        editor.show_mouse_cursor(cx);
 1118
 1119        let point_for_position = position_map.point_for_position(event.position);
 1120        let valid_point = point_for_position.previous_valid;
 1121
 1122        let hovered_diff_control = position_map
 1123            .diff_hunk_control_bounds
 1124            .iter()
 1125            .find(|(_, bounds)| bounds.contains(&event.position))
 1126            .map(|(row, _)| *row);
 1127
 1128        let hovered_diff_hunk_row = if let Some(control_row) = hovered_diff_control {
 1129            Some(control_row)
 1130        } else if text_hovered {
 1131            let current_row = valid_point.row();
 1132            position_map.display_hunks.iter().find_map(|(hunk, _)| {
 1133                if let DisplayDiffHunk::Unfolded {
 1134                    display_row_range, ..
 1135                } = hunk
 1136                {
 1137                    if display_row_range.contains(&current_row) {
 1138                        Some(display_row_range.start)
 1139                    } else {
 1140                        None
 1141                    }
 1142                } else {
 1143                    None
 1144                }
 1145            })
 1146        } else {
 1147            None
 1148        };
 1149
 1150        if hovered_diff_hunk_row != editor.hovered_diff_hunk_row {
 1151            editor.hovered_diff_hunk_row = hovered_diff_hunk_row;
 1152            cx.notify();
 1153        }
 1154
 1155        if let Some((bounds, blame_entry)) = &position_map.inline_blame_bounds {
 1156            let mouse_over_inline_blame = bounds.contains(&event.position);
 1157            let mouse_over_popover = editor
 1158                .inline_blame_popover
 1159                .as_ref()
 1160                .and_then(|state| state.popover_bounds)
 1161                .is_some_and(|bounds| bounds.contains(&event.position));
 1162            let keyboard_grace = editor
 1163                .inline_blame_popover
 1164                .as_ref()
 1165                .is_some_and(|state| state.keyboard_grace);
 1166
 1167            if mouse_over_inline_blame || mouse_over_popover {
 1168                editor.show_blame_popover(blame_entry, event.position, false, cx);
 1169            } else if !keyboard_grace {
 1170                editor.hide_blame_popover(cx);
 1171            }
 1172        } else {
 1173            editor.hide_blame_popover(cx);
 1174        }
 1175
 1176        let breakpoint_indicator = if gutter_hovered {
 1177            let buffer_anchor = position_map
 1178                .snapshot
 1179                .display_point_to_anchor(valid_point, Bias::Left);
 1180
 1181            if let Some((buffer_snapshot, file)) = position_map
 1182                .snapshot
 1183                .buffer_snapshot
 1184                .buffer_for_excerpt(buffer_anchor.excerpt_id)
 1185                .and_then(|buffer| buffer.file().map(|file| (buffer, file)))
 1186            {
 1187                let as_point = text::ToPoint::to_point(&buffer_anchor.text_anchor, buffer_snapshot);
 1188
 1189                let is_visible = editor
 1190                    .gutter_breakpoint_indicator
 1191                    .0
 1192                    .is_some_and(|indicator| indicator.is_active);
 1193
 1194                let has_existing_breakpoint =
 1195                    editor.breakpoint_store.as_ref().is_some_and(|store| {
 1196                        let Some(project) = &editor.project else {
 1197                            return false;
 1198                        };
 1199                        let Some(abs_path) = project.read(cx).absolute_path(
 1200                            &ProjectPath {
 1201                                path: file.path().clone(),
 1202                                worktree_id: file.worktree_id(cx),
 1203                            },
 1204                            cx,
 1205                        ) else {
 1206                            return false;
 1207                        };
 1208                        store
 1209                            .read(cx)
 1210                            .breakpoint_at_row(&abs_path, as_point.row, cx)
 1211                            .is_some()
 1212                    });
 1213
 1214                if !is_visible {
 1215                    editor.gutter_breakpoint_indicator.1.get_or_insert_with(|| {
 1216                        cx.spawn(async move |this, cx| {
 1217                            cx.background_executor()
 1218                                .timer(Duration::from_millis(200))
 1219                                .await;
 1220
 1221                            this.update(cx, |this, cx| {
 1222                                if let Some(indicator) = this.gutter_breakpoint_indicator.0.as_mut()
 1223                                {
 1224                                    indicator.is_active = true;
 1225                                    cx.notify();
 1226                                }
 1227                            })
 1228                            .ok();
 1229                        })
 1230                    });
 1231                }
 1232
 1233                Some(PhantomBreakpointIndicator {
 1234                    display_row: valid_point.row(),
 1235                    is_active: is_visible,
 1236                    collides_with_existing_breakpoint: has_existing_breakpoint,
 1237                })
 1238            } else {
 1239                editor.gutter_breakpoint_indicator.1 = None;
 1240                None
 1241            }
 1242        } else {
 1243            editor.gutter_breakpoint_indicator.1 = None;
 1244            None
 1245        };
 1246
 1247        if &breakpoint_indicator != &editor.gutter_breakpoint_indicator.0 {
 1248            editor.gutter_breakpoint_indicator.0 = breakpoint_indicator;
 1249            cx.notify();
 1250        }
 1251
 1252        // Don't trigger hover popover if mouse is hovering over context menu
 1253        if text_hovered {
 1254            editor.update_hovered_link(
 1255                point_for_position,
 1256                &position_map.snapshot,
 1257                modifiers,
 1258                window,
 1259                cx,
 1260            );
 1261
 1262            if let Some(point) = point_for_position.as_valid() {
 1263                let anchor = position_map
 1264                    .snapshot
 1265                    .buffer_snapshot
 1266                    .anchor_before(point.to_offset(&position_map.snapshot, Bias::Left));
 1267                hover_at(editor, Some(anchor), window, cx);
 1268                Self::update_visible_cursor(editor, point, position_map, window, cx);
 1269            } else {
 1270                hover_at(editor, None, window, cx);
 1271            }
 1272        } else {
 1273            editor.hide_hovered_link(cx);
 1274            hover_at(editor, None, window, cx);
 1275        }
 1276    }
 1277
 1278    fn update_visible_cursor(
 1279        editor: &mut Editor,
 1280        point: DisplayPoint,
 1281        position_map: &PositionMap,
 1282        window: &mut Window,
 1283        cx: &mut Context<Editor>,
 1284    ) {
 1285        let snapshot = &position_map.snapshot;
 1286        let Some(hub) = editor.collaboration_hub() else {
 1287            return;
 1288        };
 1289        let start = snapshot.display_snapshot.clip_point(
 1290            DisplayPoint::new(point.row(), point.column().saturating_sub(1)),
 1291            Bias::Left,
 1292        );
 1293        let end = snapshot.display_snapshot.clip_point(
 1294            DisplayPoint::new(
 1295                point.row(),
 1296                (point.column() + 1).min(snapshot.line_len(point.row())),
 1297            ),
 1298            Bias::Right,
 1299        );
 1300
 1301        let range = snapshot
 1302            .buffer_snapshot
 1303            .anchor_at(start.to_point(&snapshot.display_snapshot), Bias::Left)
 1304            ..snapshot
 1305                .buffer_snapshot
 1306                .anchor_at(end.to_point(&snapshot.display_snapshot), Bias::Right);
 1307
 1308        let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
 1309            return;
 1310        };
 1311        let key = crate::HoveredCursor {
 1312            replica_id: selection.replica_id,
 1313            selection_id: selection.selection.id,
 1314        };
 1315        editor.hovered_cursors.insert(
 1316            key.clone(),
 1317            cx.spawn_in(window, async move |editor, cx| {
 1318                cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 1319                editor
 1320                    .update(cx, |editor, cx| {
 1321                        editor.hovered_cursors.remove(&key);
 1322                        cx.notify();
 1323                    })
 1324                    .ok();
 1325            }),
 1326        );
 1327        cx.notify()
 1328    }
 1329
 1330    fn layout_selections(
 1331        &self,
 1332        start_anchor: Anchor,
 1333        end_anchor: Anchor,
 1334        local_selections: &[Selection<Point>],
 1335        snapshot: &EditorSnapshot,
 1336        start_row: DisplayRow,
 1337        end_row: DisplayRow,
 1338        window: &mut Window,
 1339        cx: &mut App,
 1340    ) -> (
 1341        Vec<(PlayerColor, Vec<SelectionLayout>)>,
 1342        BTreeMap<DisplayRow, LineHighlightSpec>,
 1343        Option<DisplayPoint>,
 1344    ) {
 1345        let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
 1346        let mut active_rows = BTreeMap::new();
 1347        let mut newest_selection_head = None;
 1348
 1349        let Some(editor_with_selections) = self.editor_with_selections(cx) else {
 1350            return (selections, active_rows, newest_selection_head);
 1351        };
 1352
 1353        editor_with_selections.update(cx, |editor, cx| {
 1354            if editor.show_local_selections {
 1355                let mut layouts = Vec::new();
 1356                let newest = editor.selections.newest(cx);
 1357                for selection in local_selections.iter().cloned() {
 1358                    let is_empty = selection.start == selection.end;
 1359                    let is_newest = selection == newest;
 1360
 1361                    let layout = SelectionLayout::new(
 1362                        selection,
 1363                        editor.selections.line_mode,
 1364                        editor.cursor_shape,
 1365                        &snapshot.display_snapshot,
 1366                        is_newest,
 1367                        editor.leader_id.is_none(),
 1368                        None,
 1369                    );
 1370                    if is_newest {
 1371                        newest_selection_head = Some(layout.head);
 1372                    }
 1373
 1374                    for row in cmp::max(layout.active_rows.start.0, start_row.0)
 1375                        ..=cmp::min(layout.active_rows.end.0, end_row.0)
 1376                    {
 1377                        let contains_non_empty_selection = active_rows
 1378                            .entry(DisplayRow(row))
 1379                            .or_insert_with(LineHighlightSpec::default);
 1380                        contains_non_empty_selection.selection |= !is_empty;
 1381                    }
 1382                    layouts.push(layout);
 1383                }
 1384
 1385                let player = editor.current_user_player_color(cx);
 1386                selections.push((player, layouts));
 1387
 1388                if let SelectionDragState::Dragging {
 1389                    ref selection,
 1390                    ref drop_cursor,
 1391                    ref hide_drop_cursor,
 1392                } = editor.selection_drag_state
 1393                    && !hide_drop_cursor
 1394                    && (drop_cursor
 1395                        .start
 1396                        .cmp(&selection.start, &snapshot.buffer_snapshot)
 1397                        .eq(&Ordering::Less)
 1398                        || drop_cursor
 1399                            .end
 1400                            .cmp(&selection.end, &snapshot.buffer_snapshot)
 1401                            .eq(&Ordering::Greater))
 1402                {
 1403                    let drag_cursor_layout = SelectionLayout::new(
 1404                        drop_cursor.clone(),
 1405                        false,
 1406                        CursorShape::Bar,
 1407                        &snapshot.display_snapshot,
 1408                        false,
 1409                        false,
 1410                        None,
 1411                    );
 1412                    let absent_color = cx.theme().players().absent();
 1413                    selections.push((absent_color, vec![drag_cursor_layout]));
 1414                }
 1415            }
 1416
 1417            if let Some(collaboration_hub) = &editor.collaboration_hub {
 1418                // When following someone, render the local selections in their color.
 1419                if let Some(leader_id) = editor.leader_id {
 1420                    match leader_id {
 1421                        CollaboratorId::PeerId(peer_id) => {
 1422                            if let Some(collaborator) =
 1423                                collaboration_hub.collaborators(cx).get(&peer_id)
 1424                                && let Some(participant_index) = collaboration_hub
 1425                                    .user_participant_indices(cx)
 1426                                    .get(&collaborator.user_id)
 1427                                && let Some((local_selection_style, _)) = selections.first_mut()
 1428                            {
 1429                                *local_selection_style = cx
 1430                                    .theme()
 1431                                    .players()
 1432                                    .color_for_participant(participant_index.0);
 1433                            }
 1434                        }
 1435                        CollaboratorId::Agent => {
 1436                            if let Some((local_selection_style, _)) = selections.first_mut() {
 1437                                *local_selection_style = cx.theme().players().agent();
 1438                            }
 1439                        }
 1440                    }
 1441                }
 1442
 1443                let mut remote_selections = HashMap::default();
 1444                for selection in snapshot.remote_selections_in_range(
 1445                    &(start_anchor..end_anchor),
 1446                    collaboration_hub.as_ref(),
 1447                    cx,
 1448                ) {
 1449                    // Don't re-render the leader's selections, since the local selections
 1450                    // match theirs.
 1451                    if Some(selection.collaborator_id) == editor.leader_id {
 1452                        continue;
 1453                    }
 1454                    let key = HoveredCursor {
 1455                        replica_id: selection.replica_id,
 1456                        selection_id: selection.selection.id,
 1457                    };
 1458
 1459                    let is_shown =
 1460                        editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
 1461
 1462                    remote_selections
 1463                        .entry(selection.replica_id)
 1464                        .or_insert((selection.color, Vec::new()))
 1465                        .1
 1466                        .push(SelectionLayout::new(
 1467                            selection.selection,
 1468                            selection.line_mode,
 1469                            selection.cursor_shape,
 1470                            &snapshot.display_snapshot,
 1471                            false,
 1472                            false,
 1473                            if is_shown { selection.user_name } else { None },
 1474                        ));
 1475                }
 1476
 1477                selections.extend(remote_selections.into_values());
 1478            } else if !editor.is_focused(window) && editor.show_cursor_when_unfocused {
 1479                let layouts = snapshot
 1480                    .buffer_snapshot
 1481                    .selections_in_range(&(start_anchor..end_anchor), true)
 1482                    .map(move |(_, line_mode, cursor_shape, selection)| {
 1483                        SelectionLayout::new(
 1484                            selection,
 1485                            line_mode,
 1486                            cursor_shape,
 1487                            &snapshot.display_snapshot,
 1488                            false,
 1489                            false,
 1490                            None,
 1491                        )
 1492                    })
 1493                    .collect::<Vec<_>>();
 1494                let player = editor.current_user_player_color(cx);
 1495                selections.push((player, layouts));
 1496            }
 1497        });
 1498        (selections, active_rows, newest_selection_head)
 1499    }
 1500
 1501    fn collect_cursors(
 1502        &self,
 1503        snapshot: &EditorSnapshot,
 1504        cx: &mut App,
 1505    ) -> Vec<(DisplayPoint, Hsla)> {
 1506        let editor = self.editor.read(cx);
 1507        let mut cursors = Vec::new();
 1508        let mut skip_local = false;
 1509        let mut add_cursor = |anchor: Anchor, color| {
 1510            cursors.push((anchor.to_display_point(&snapshot.display_snapshot), color));
 1511        };
 1512        // Remote cursors
 1513        if let Some(collaboration_hub) = &editor.collaboration_hub {
 1514            for remote_selection in snapshot.remote_selections_in_range(
 1515                &(Anchor::min()..Anchor::max()),
 1516                collaboration_hub.deref(),
 1517                cx,
 1518            ) {
 1519                add_cursor(
 1520                    remote_selection.selection.head(),
 1521                    remote_selection.color.cursor,
 1522                );
 1523                if Some(remote_selection.collaborator_id) == editor.leader_id {
 1524                    skip_local = true;
 1525                }
 1526            }
 1527        }
 1528        // Local cursors
 1529        if !skip_local {
 1530            let color = cx.theme().players().local().cursor;
 1531            editor.selections.disjoint.iter().for_each(|selection| {
 1532                add_cursor(selection.head(), color);
 1533            });
 1534            if let Some(ref selection) = editor.selections.pending_anchor() {
 1535                add_cursor(selection.head(), color);
 1536            }
 1537        }
 1538        cursors
 1539    }
 1540
 1541    fn layout_visible_cursors(
 1542        &self,
 1543        snapshot: &EditorSnapshot,
 1544        selections: &[(PlayerColor, Vec<SelectionLayout>)],
 1545        row_block_types: &HashMap<DisplayRow, bool>,
 1546        visible_display_row_range: Range<DisplayRow>,
 1547        line_layouts: &[LineWithInvisibles],
 1548        text_hitbox: &Hitbox,
 1549        content_origin: gpui::Point<Pixels>,
 1550        scroll_position: gpui::Point<f32>,
 1551        scroll_pixel_position: gpui::Point<Pixels>,
 1552        line_height: Pixels,
 1553        em_width: Pixels,
 1554        em_advance: Pixels,
 1555        autoscroll_containing_element: bool,
 1556        window: &mut Window,
 1557        cx: &mut App,
 1558    ) -> Vec<CursorLayout> {
 1559        let mut autoscroll_bounds = None;
 1560        let cursor_layouts = self.editor.update(cx, |editor, cx| {
 1561            let mut cursors = Vec::new();
 1562
 1563            let show_local_cursors = editor.show_local_cursors(window, cx);
 1564
 1565            for (player_color, selections) in selections {
 1566                for selection in selections {
 1567                    let cursor_position = selection.head;
 1568
 1569                    let in_range = visible_display_row_range.contains(&cursor_position.row());
 1570                    if (selection.is_local && !show_local_cursors)
 1571                        || !in_range
 1572                        || row_block_types.get(&cursor_position.row()) == Some(&true)
 1573                    {
 1574                        continue;
 1575                    }
 1576
 1577                    let cursor_row_layout = &line_layouts
 1578                        [cursor_position.row().minus(visible_display_row_range.start) as usize];
 1579                    let cursor_column = cursor_position.column() as usize;
 1580
 1581                    let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 1582                    let mut block_width =
 1583                        cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
 1584                    if block_width == Pixels::ZERO {
 1585                        block_width = em_advance;
 1586                    }
 1587                    let block_text = if let CursorShape::Block = selection.cursor_shape {
 1588                        snapshot
 1589                            .grapheme_at(cursor_position)
 1590                            .or_else(|| {
 1591                                if snapshot.is_empty() {
 1592                                    snapshot.placeholder_text().and_then(|s| {
 1593                                        s.graphemes(true).next().map(|s| s.to_string().into())
 1594                                    })
 1595                                } else {
 1596                                    None
 1597                                }
 1598                            })
 1599                            .map(|text| {
 1600                                let len = text.len();
 1601
 1602                                let font = cursor_row_layout
 1603                                    .font_id_for_index(cursor_column)
 1604                                    .and_then(|cursor_font_id| {
 1605                                        window.text_system().get_font_for_id(cursor_font_id)
 1606                                    })
 1607                                    .unwrap_or(self.style.text.font());
 1608
 1609                                // Invert the text color for the block cursor. Ensure that the text
 1610                                // color is opaque enough to be visible against the background color.
 1611                                //
 1612                                // 0.75 is an arbitrary threshold to determine if the background color is
 1613                                // opaque enough to use as a text color.
 1614                                //
 1615                                // TODO: In the future we should ensure themes have a `text_inverse` color.
 1616                                let color = if cx.theme().colors().editor_background.a < 0.75 {
 1617                                    match cx.theme().appearance {
 1618                                        Appearance::Dark => Hsla::black(),
 1619                                        Appearance::Light => Hsla::white(),
 1620                                    }
 1621                                } else {
 1622                                    cx.theme().colors().editor_background
 1623                                };
 1624
 1625                                window.text_system().shape_line(
 1626                                    text,
 1627                                    cursor_row_layout.font_size,
 1628                                    &[TextRun {
 1629                                        len,
 1630                                        font,
 1631                                        color,
 1632                                        background_color: None,
 1633                                        strikethrough: None,
 1634                                        underline: None,
 1635                                    }],
 1636                                    None,
 1637                                )
 1638                            })
 1639                    } else {
 1640                        None
 1641                    };
 1642
 1643                    let x = cursor_character_x - scroll_pixel_position.x;
 1644                    let y = (cursor_position.row().as_f32()
 1645                        - scroll_pixel_position.y / line_height)
 1646                        * line_height;
 1647                    if selection.is_newest {
 1648                        editor.pixel_position_of_newest_cursor = Some(point(
 1649                            text_hitbox.origin.x + x + block_width / 2.,
 1650                            text_hitbox.origin.y + y + line_height / 2.,
 1651                        ));
 1652
 1653                        if autoscroll_containing_element {
 1654                            let top = text_hitbox.origin.y
 1655                                + (cursor_position.row().as_f32() - scroll_position.y - 3.).max(0.)
 1656                                    * line_height;
 1657                            let left = text_hitbox.origin.x
 1658                                + (cursor_position.column() as f32 - scroll_position.x - 3.)
 1659                                    .max(0.)
 1660                                    * em_width;
 1661
 1662                            let bottom = text_hitbox.origin.y
 1663                                + (cursor_position.row().as_f32() - scroll_position.y + 4.)
 1664                                    * line_height;
 1665                            let right = text_hitbox.origin.x
 1666                                + (cursor_position.column() as f32 - scroll_position.x + 4.)
 1667                                    * em_width;
 1668
 1669                            autoscroll_bounds =
 1670                                Some(Bounds::from_corners(point(left, top), point(right, bottom)))
 1671                        }
 1672                    }
 1673
 1674                    let mut cursor = CursorLayout {
 1675                        color: player_color.cursor,
 1676                        block_width,
 1677                        origin: point(x, y),
 1678                        line_height,
 1679                        shape: selection.cursor_shape,
 1680                        block_text,
 1681                        cursor_name: None,
 1682                    };
 1683                    let cursor_name = selection.user_name.clone().map(|name| CursorName {
 1684                        string: name,
 1685                        color: self.style.background,
 1686                        is_top_row: cursor_position.row().0 == 0,
 1687                    });
 1688                    cursor.layout(content_origin, cursor_name, window, cx);
 1689                    cursors.push(cursor);
 1690                }
 1691            }
 1692
 1693            cursors
 1694        });
 1695
 1696        if let Some(bounds) = autoscroll_bounds {
 1697            window.request_autoscroll(bounds);
 1698        }
 1699
 1700        cursor_layouts
 1701    }
 1702
 1703    fn layout_scrollbars(
 1704        &self,
 1705        snapshot: &EditorSnapshot,
 1706        scrollbar_layout_information: &ScrollbarLayoutInformation,
 1707        content_offset: gpui::Point<Pixels>,
 1708        scroll_position: gpui::Point<f32>,
 1709        non_visible_cursors: bool,
 1710        right_margin: Pixels,
 1711        editor_width: Pixels,
 1712        window: &mut Window,
 1713        cx: &mut App,
 1714    ) -> Option<EditorScrollbars> {
 1715        let show_scrollbars = self.editor.read(cx).show_scrollbars;
 1716        if (!show_scrollbars.horizontal && !show_scrollbars.vertical)
 1717            || self.style.scrollbar_width.is_zero()
 1718        {
 1719            return None;
 1720        }
 1721
 1722        // If a drag took place after we started dragging the scrollbar,
 1723        // cancel the scrollbar drag.
 1724        if cx.has_active_drag() {
 1725            self.editor.update(cx, |editor, cx| {
 1726                editor.scroll_manager.reset_scrollbar_state(cx)
 1727            });
 1728        }
 1729
 1730        let editor_settings = EditorSettings::get_global(cx);
 1731        let scrollbar_settings = editor_settings.scrollbar;
 1732        let show_scrollbars = match scrollbar_settings.show {
 1733            ShowScrollbar::Auto => {
 1734                let editor = self.editor.read(cx);
 1735                let is_singleton = editor.is_singleton(cx);
 1736                // Git
 1737                (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_diff_hunks())
 1738                ||
 1739                // Buffer Search Results
 1740                (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights::<BufferSearchHighlights>())
 1741                ||
 1742                // Selected Text Occurrences
 1743                (is_singleton && scrollbar_settings.selected_text && editor.has_background_highlights::<SelectedTextHighlight>())
 1744                ||
 1745                // Selected Symbol Occurrences
 1746                (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
 1747                ||
 1748                // Diagnostics
 1749                (is_singleton && scrollbar_settings.diagnostics != ScrollbarDiagnostics::None && snapshot.buffer_snapshot.has_diagnostics())
 1750                ||
 1751                // Cursors out of sight
 1752                non_visible_cursors
 1753                ||
 1754                // Scrollmanager
 1755                editor.scroll_manager.scrollbars_visible()
 1756            }
 1757            ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
 1758            ShowScrollbar::Always => true,
 1759            ShowScrollbar::Never => return None,
 1760        };
 1761
 1762        // The horizontal scrollbar is usually slightly offset to align nicely with
 1763        // indent guides. However, this offset is not needed if indent guides are
 1764        // disabled for the current editor.
 1765        let content_offset = self
 1766            .editor
 1767            .read(cx)
 1768            .show_indent_guides
 1769            .is_none_or(|should_show| should_show)
 1770            .then_some(content_offset)
 1771            .unwrap_or_default();
 1772
 1773        Some(EditorScrollbars::from_scrollbar_axes(
 1774            ScrollbarAxes {
 1775                horizontal: scrollbar_settings.axes.horizontal
 1776                    && self.editor.read(cx).show_scrollbars.horizontal,
 1777                vertical: scrollbar_settings.axes.vertical
 1778                    && self.editor.read(cx).show_scrollbars.vertical,
 1779            },
 1780            scrollbar_layout_information,
 1781            content_offset,
 1782            scroll_position,
 1783            self.style.scrollbar_width,
 1784            right_margin,
 1785            editor_width,
 1786            show_scrollbars,
 1787            self.editor.read(cx).scroll_manager.active_scrollbar_state(),
 1788            window,
 1789        ))
 1790    }
 1791
 1792    fn layout_minimap(
 1793        &self,
 1794        snapshot: &EditorSnapshot,
 1795        minimap_width: Pixels,
 1796        scroll_position: gpui::Point<f32>,
 1797        scrollbar_layout_information: &ScrollbarLayoutInformation,
 1798        scrollbar_layout: Option<&EditorScrollbars>,
 1799        window: &mut Window,
 1800        cx: &mut App,
 1801    ) -> Option<MinimapLayout> {
 1802        let minimap_editor = self.editor.read(cx).minimap().cloned()?;
 1803
 1804        let minimap_settings = EditorSettings::get_global(cx).minimap;
 1805
 1806        if minimap_settings.on_active_editor() {
 1807            let active_editor = self.editor.read(cx).workspace().and_then(|ws| {
 1808                ws.read(cx)
 1809                    .active_pane()
 1810                    .read(cx)
 1811                    .active_item()
 1812                    .and_then(|i| i.act_as::<Editor>(cx))
 1813            });
 1814            if active_editor.is_some_and(|e| e != self.editor) {
 1815                return None;
 1816            }
 1817        }
 1818
 1819        if !snapshot.mode.is_full()
 1820            || minimap_width.is_zero()
 1821            || matches!(
 1822                minimap_settings.show,
 1823                ShowMinimap::Auto if scrollbar_layout.is_none_or(|layout| !layout.visible)
 1824            )
 1825        {
 1826            return None;
 1827        }
 1828
 1829        const MINIMAP_AXIS: ScrollbarAxis = ScrollbarAxis::Vertical;
 1830
 1831        let ScrollbarLayoutInformation {
 1832            editor_bounds,
 1833            scroll_range,
 1834            glyph_grid_cell,
 1835        } = scrollbar_layout_information;
 1836
 1837        let line_height = glyph_grid_cell.height;
 1838        let scroll_position = scroll_position.along(MINIMAP_AXIS);
 1839
 1840        let top_right_anchor = scrollbar_layout
 1841            .and_then(|layout| layout.vertical.as_ref())
 1842            .map(|vertical_scrollbar| vertical_scrollbar.hitbox.origin)
 1843            .unwrap_or_else(|| editor_bounds.top_right());
 1844
 1845        let thumb_state = self
 1846            .editor
 1847            .read_with(cx, |editor, _| editor.scroll_manager.minimap_thumb_state());
 1848
 1849        let show_thumb = match minimap_settings.thumb {
 1850            MinimapThumb::Always => true,
 1851            MinimapThumb::Hover => thumb_state.is_some(),
 1852        };
 1853
 1854        let minimap_bounds = Bounds::from_corner_and_size(
 1855            Corner::TopRight,
 1856            top_right_anchor,
 1857            size(minimap_width, editor_bounds.size.height),
 1858        );
 1859        let minimap_line_height = self.get_minimap_line_height(
 1860            minimap_editor
 1861                .read(cx)
 1862                .text_style_refinement
 1863                .as_ref()
 1864                .and_then(|refinement| refinement.font_size)
 1865                .unwrap_or(MINIMAP_FONT_SIZE),
 1866            window,
 1867            cx,
 1868        );
 1869        let minimap_height = minimap_bounds.size.height;
 1870
 1871        let visible_editor_lines = editor_bounds.size.height / line_height;
 1872        let total_editor_lines = scroll_range.height / line_height;
 1873        let minimap_lines = minimap_height / minimap_line_height;
 1874
 1875        let minimap_scroll_top = MinimapLayout::calculate_minimap_top_offset(
 1876            total_editor_lines,
 1877            visible_editor_lines,
 1878            minimap_lines,
 1879            scroll_position,
 1880        );
 1881
 1882        let layout = ScrollbarLayout::for_minimap(
 1883            window.insert_hitbox(minimap_bounds, HitboxBehavior::Normal),
 1884            visible_editor_lines,
 1885            total_editor_lines,
 1886            minimap_line_height,
 1887            scroll_position,
 1888            minimap_scroll_top,
 1889            show_thumb,
 1890        )
 1891        .with_thumb_state(thumb_state);
 1892
 1893        minimap_editor.update(cx, |editor, cx| {
 1894            editor.set_scroll_position(point(0., minimap_scroll_top), window, cx)
 1895        });
 1896
 1897        // Required for the drop shadow to be visible
 1898        const PADDING_OFFSET: Pixels = px(4.);
 1899
 1900        let mut minimap = div()
 1901            .size_full()
 1902            .shadow_xs()
 1903            .px(PADDING_OFFSET)
 1904            .child(minimap_editor)
 1905            .into_any_element();
 1906
 1907        let extended_bounds = minimap_bounds.extend(Edges {
 1908            right: PADDING_OFFSET,
 1909            left: PADDING_OFFSET,
 1910            ..Default::default()
 1911        });
 1912        minimap.layout_as_root(extended_bounds.size.into(), window, cx);
 1913        window.with_absolute_element_offset(extended_bounds.origin, |window| {
 1914            minimap.prepaint(window, cx)
 1915        });
 1916
 1917        Some(MinimapLayout {
 1918            minimap,
 1919            thumb_layout: layout,
 1920            thumb_border_style: minimap_settings.thumb_border,
 1921            minimap_line_height,
 1922            minimap_scroll_top,
 1923            max_scroll_top: total_editor_lines,
 1924        })
 1925    }
 1926
 1927    fn get_minimap_line_height(
 1928        &self,
 1929        font_size: AbsoluteLength,
 1930        window: &mut Window,
 1931        cx: &mut App,
 1932    ) -> Pixels {
 1933        let rem_size = self.rem_size(cx).unwrap_or(window.rem_size());
 1934        let mut text_style = self.style.text.clone();
 1935        text_style.font_size = font_size;
 1936        text_style.line_height_in_pixels(rem_size)
 1937    }
 1938
 1939    fn get_minimap_width(
 1940        &self,
 1941        minimap_settings: &Minimap,
 1942        scrollbars_shown: bool,
 1943        text_width: Pixels,
 1944        em_width: Pixels,
 1945        font_size: Pixels,
 1946        rem_size: Pixels,
 1947        cx: &App,
 1948    ) -> Option<Pixels> {
 1949        if minimap_settings.show == ShowMinimap::Auto && !scrollbars_shown {
 1950            return None;
 1951        }
 1952
 1953        let minimap_font_size = self.editor.read_with(cx, |editor, cx| {
 1954            editor.minimap().map(|minimap_editor| {
 1955                minimap_editor
 1956                    .read(cx)
 1957                    .text_style_refinement
 1958                    .as_ref()
 1959                    .and_then(|refinement| refinement.font_size)
 1960                    .unwrap_or(MINIMAP_FONT_SIZE)
 1961            })
 1962        })?;
 1963
 1964        let minimap_em_width = em_width * (minimap_font_size.to_pixels(rem_size) / font_size);
 1965
 1966        let minimap_width = (text_width * MinimapLayout::MINIMAP_WIDTH_PCT)
 1967            .min(minimap_em_width * minimap_settings.max_width_columns.get() as f32);
 1968
 1969        (minimap_width >= minimap_em_width * MinimapLayout::MINIMAP_MIN_WIDTH_COLUMNS)
 1970            .then_some(minimap_width)
 1971    }
 1972
 1973    fn prepaint_crease_toggles(
 1974        &self,
 1975        crease_toggles: &mut [Option<AnyElement>],
 1976        line_height: Pixels,
 1977        gutter_dimensions: &GutterDimensions,
 1978        gutter_settings: crate::editor_settings::Gutter,
 1979        scroll_pixel_position: gpui::Point<Pixels>,
 1980        gutter_hitbox: &Hitbox,
 1981        window: &mut Window,
 1982        cx: &mut App,
 1983    ) {
 1984        for (ix, crease_toggle) in crease_toggles.iter_mut().enumerate() {
 1985            if let Some(crease_toggle) = crease_toggle {
 1986                debug_assert!(gutter_settings.folds);
 1987                let available_space = size(
 1988                    AvailableSpace::MinContent,
 1989                    AvailableSpace::Definite(line_height * 0.55),
 1990                );
 1991                let crease_toggle_size = crease_toggle.layout_as_root(available_space, window, cx);
 1992
 1993                let position = point(
 1994                    gutter_dimensions.width - gutter_dimensions.right_padding,
 1995                    ix as f32 * line_height - (scroll_pixel_position.y % line_height),
 1996                );
 1997                let centering_offset = point(
 1998                    (gutter_dimensions.fold_area_width() - crease_toggle_size.width) / 2.,
 1999                    (line_height - crease_toggle_size.height) / 2.,
 2000                );
 2001                let origin = gutter_hitbox.origin + position + centering_offset;
 2002                crease_toggle.prepaint_as_root(origin, available_space, window, cx);
 2003            }
 2004        }
 2005    }
 2006
 2007    fn prepaint_expand_toggles(
 2008        &self,
 2009        expand_toggles: &mut [Option<(AnyElement, gpui::Point<Pixels>)>],
 2010        window: &mut Window,
 2011        cx: &mut App,
 2012    ) {
 2013        for (expand_toggle, origin) in expand_toggles.iter_mut().flatten() {
 2014            let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
 2015            expand_toggle.layout_as_root(available_space, window, cx);
 2016            expand_toggle.prepaint_as_root(*origin, available_space, window, cx);
 2017        }
 2018    }
 2019
 2020    fn prepaint_crease_trailers(
 2021        &self,
 2022        trailers: Vec<Option<AnyElement>>,
 2023        lines: &[LineWithInvisibles],
 2024        line_height: Pixels,
 2025        content_origin: gpui::Point<Pixels>,
 2026        scroll_pixel_position: gpui::Point<Pixels>,
 2027        em_width: Pixels,
 2028        window: &mut Window,
 2029        cx: &mut App,
 2030    ) -> Vec<Option<CreaseTrailerLayout>> {
 2031        trailers
 2032            .into_iter()
 2033            .enumerate()
 2034            .map(|(ix, element)| {
 2035                let mut element = element?;
 2036                let available_space = size(
 2037                    AvailableSpace::MinContent,
 2038                    AvailableSpace::Definite(line_height),
 2039                );
 2040                let size = element.layout_as_root(available_space, window, cx);
 2041
 2042                let line = &lines[ix];
 2043                let padding = if line.width == Pixels::ZERO {
 2044                    Pixels::ZERO
 2045                } else {
 2046                    4. * em_width
 2047                };
 2048                let position = point(
 2049                    scroll_pixel_position.x + line.width + padding,
 2050                    ix as f32 * line_height - (scroll_pixel_position.y % line_height),
 2051                );
 2052                let centering_offset = point(px(0.), (line_height - size.height) / 2.);
 2053                let origin = content_origin + position + centering_offset;
 2054                element.prepaint_as_root(origin, available_space, window, cx);
 2055                Some(CreaseTrailerLayout {
 2056                    element,
 2057                    bounds: Bounds::new(origin, size),
 2058                })
 2059            })
 2060            .collect()
 2061    }
 2062
 2063    // Folds contained in a hunk are ignored apart from shrinking visual size
 2064    // If a fold contains any hunks then that fold line is marked as modified
 2065    fn layout_gutter_diff_hunks(
 2066        &self,
 2067        line_height: Pixels,
 2068        gutter_hitbox: &Hitbox,
 2069        display_rows: Range<DisplayRow>,
 2070        snapshot: &EditorSnapshot,
 2071        window: &mut Window,
 2072        cx: &mut App,
 2073    ) -> Vec<(DisplayDiffHunk, Option<Hitbox>)> {
 2074        let folded_buffers = self.editor.read(cx).folded_buffers(cx);
 2075        let mut display_hunks = snapshot
 2076            .display_diff_hunks_for_rows(display_rows, folded_buffers)
 2077            .map(|hunk| (hunk, None))
 2078            .collect::<Vec<_>>();
 2079        let git_gutter_setting = ProjectSettings::get_global(cx)
 2080            .git
 2081            .git_gutter
 2082            .unwrap_or_default();
 2083        if let GitGutterSetting::TrackedFiles = git_gutter_setting {
 2084            for (hunk, hitbox) in &mut display_hunks {
 2085                if matches!(hunk, DisplayDiffHunk::Unfolded { .. }) {
 2086                    let hunk_bounds =
 2087                        Self::diff_hunk_bounds(snapshot, line_height, gutter_hitbox.bounds, hunk);
 2088                    *hitbox = Some(window.insert_hitbox(hunk_bounds, HitboxBehavior::BlockMouse));
 2089                }
 2090            }
 2091        }
 2092
 2093        display_hunks
 2094    }
 2095
 2096    fn layout_inline_diagnostics(
 2097        &self,
 2098        line_layouts: &[LineWithInvisibles],
 2099        crease_trailers: &[Option<CreaseTrailerLayout>],
 2100        row_block_types: &HashMap<DisplayRow, bool>,
 2101        content_origin: gpui::Point<Pixels>,
 2102        scroll_pixel_position: gpui::Point<Pixels>,
 2103        edit_prediction_popover_origin: Option<gpui::Point<Pixels>>,
 2104        start_row: DisplayRow,
 2105        end_row: DisplayRow,
 2106        line_height: Pixels,
 2107        em_width: Pixels,
 2108        style: &EditorStyle,
 2109        window: &mut Window,
 2110        cx: &mut App,
 2111    ) -> HashMap<DisplayRow, AnyElement> {
 2112        let max_severity = match self
 2113            .editor
 2114            .read(cx)
 2115            .inline_diagnostics_enabled()
 2116            .then(|| {
 2117                ProjectSettings::get_global(cx)
 2118                    .diagnostics
 2119                    .inline
 2120                    .max_severity
 2121                    .unwrap_or_else(|| self.editor.read(cx).diagnostics_max_severity)
 2122                    .into_lsp()
 2123            })
 2124            .flatten()
 2125        {
 2126            Some(max_severity) => max_severity,
 2127            None => return HashMap::default(),
 2128        };
 2129
 2130        let active_diagnostics_group =
 2131            if let ActiveDiagnostic::Group(group) = &self.editor.read(cx).active_diagnostics {
 2132                Some(group.group_id)
 2133            } else {
 2134                None
 2135            };
 2136
 2137        let diagnostics_by_rows = self.editor.update(cx, |editor, cx| {
 2138            let snapshot = editor.snapshot(window, cx);
 2139            editor
 2140                .inline_diagnostics
 2141                .iter()
 2142                .filter(|(_, diagnostic)| diagnostic.severity <= max_severity)
 2143                .filter(|(_, diagnostic)| match active_diagnostics_group {
 2144                    Some(active_diagnostics_group) => {
 2145                        // Active diagnostics are all shown in the editor already, no need to display them inline
 2146                        diagnostic.group_id != active_diagnostics_group
 2147                    }
 2148                    None => true,
 2149                })
 2150                .map(|(point, diag)| (point.to_display_point(&snapshot), diag.clone()))
 2151                .skip_while(|(point, _)| point.row() < start_row)
 2152                .take_while(|(point, _)| point.row() < end_row)
 2153                .filter(|(point, _)| !row_block_types.contains_key(&point.row()))
 2154                .fold(HashMap::default(), |mut acc, (point, diagnostic)| {
 2155                    acc.entry(point.row())
 2156                        .or_insert_with(Vec::new)
 2157                        .push(diagnostic);
 2158                    acc
 2159                })
 2160        });
 2161
 2162        if diagnostics_by_rows.is_empty() {
 2163            return HashMap::default();
 2164        }
 2165
 2166        let severity_to_color = |sev: &lsp::DiagnosticSeverity| match sev {
 2167            &lsp::DiagnosticSeverity::ERROR => Color::Error,
 2168            &lsp::DiagnosticSeverity::WARNING => Color::Warning,
 2169            &lsp::DiagnosticSeverity::INFORMATION => Color::Info,
 2170            &lsp::DiagnosticSeverity::HINT => Color::Hint,
 2171            _ => Color::Error,
 2172        };
 2173
 2174        let padding = ProjectSettings::get_global(cx).diagnostics.inline.padding as f32 * em_width;
 2175        let min_x = self.column_pixels(
 2176            ProjectSettings::get_global(cx)
 2177                .diagnostics
 2178                .inline
 2179                .min_column as usize,
 2180            window,
 2181        );
 2182
 2183        let mut elements = HashMap::default();
 2184        for (row, mut diagnostics) in diagnostics_by_rows {
 2185            diagnostics.sort_by_key(|diagnostic| {
 2186                (
 2187                    diagnostic.severity,
 2188                    std::cmp::Reverse(diagnostic.is_primary),
 2189                    diagnostic.start.row,
 2190                    diagnostic.start.column,
 2191                )
 2192            });
 2193
 2194            let Some(diagnostic_to_render) = diagnostics
 2195                .iter()
 2196                .find(|diagnostic| diagnostic.is_primary)
 2197                .or_else(|| diagnostics.first())
 2198            else {
 2199                continue;
 2200            };
 2201
 2202            let pos_y = content_origin.y
 2203                + line_height * (row.0 as f32 - scroll_pixel_position.y / line_height);
 2204
 2205            let window_ix = row.0.saturating_sub(start_row.0) as usize;
 2206            let pos_x = {
 2207                let crease_trailer_layout = &crease_trailers[window_ix];
 2208                let line_layout = &line_layouts[window_ix];
 2209
 2210                let line_end = if let Some(crease_trailer) = crease_trailer_layout {
 2211                    crease_trailer.bounds.right()
 2212                } else {
 2213                    content_origin.x - scroll_pixel_position.x + line_layout.width
 2214                };
 2215
 2216                let padded_line = line_end + padding;
 2217                let min_start = content_origin.x - scroll_pixel_position.x + min_x;
 2218
 2219                cmp::max(padded_line, min_start)
 2220            };
 2221
 2222            let behind_edit_prediction_popover = edit_prediction_popover_origin
 2223                .as_ref()
 2224                .is_some_and(|edit_prediction_popover_origin| {
 2225                    (pos_y..pos_y + line_height).contains(&edit_prediction_popover_origin.y)
 2226                });
 2227            let opacity = if behind_edit_prediction_popover {
 2228                0.5
 2229            } else {
 2230                1.0
 2231            };
 2232
 2233            let mut element = h_flex()
 2234                .id(("diagnostic", row.0))
 2235                .h(line_height)
 2236                .w_full()
 2237                .px_1()
 2238                .rounded_xs()
 2239                .opacity(opacity)
 2240                .bg(severity_to_color(&diagnostic_to_render.severity)
 2241                    .color(cx)
 2242                    .opacity(0.05))
 2243                .text_color(severity_to_color(&diagnostic_to_render.severity).color(cx))
 2244                .text_sm()
 2245                .font_family(style.text.font().family)
 2246                .child(diagnostic_to_render.message.clone())
 2247                .into_any();
 2248
 2249            element.prepaint_as_root(point(pos_x, pos_y), AvailableSpace::min_size(), window, cx);
 2250
 2251            elements.insert(row, element);
 2252        }
 2253
 2254        elements
 2255    }
 2256
 2257    fn layout_inline_code_actions(
 2258        &self,
 2259        display_point: DisplayPoint,
 2260        content_origin: gpui::Point<Pixels>,
 2261        scroll_pixel_position: gpui::Point<Pixels>,
 2262        line_height: Pixels,
 2263        snapshot: &EditorSnapshot,
 2264        window: &mut Window,
 2265        cx: &mut App,
 2266    ) -> Option<AnyElement> {
 2267        if !snapshot
 2268            .show_code_actions
 2269            .unwrap_or(EditorSettings::get_global(cx).inline_code_actions)
 2270        {
 2271            return None;
 2272        }
 2273
 2274        let icon_size = ui::IconSize::XSmall;
 2275        let mut button = self.editor.update(cx, |editor, cx| {
 2276            editor.available_code_actions.as_ref()?;
 2277            let active = editor
 2278                .context_menu
 2279                .borrow()
 2280                .as_ref()
 2281                .and_then(|menu| {
 2282                    if let crate::CodeContextMenu::CodeActions(CodeActionsMenu {
 2283                        deployed_from,
 2284                        ..
 2285                    }) = menu
 2286                    {
 2287                        deployed_from.as_ref()
 2288                    } else {
 2289                        None
 2290                    }
 2291                })
 2292                .is_some_and(|source| matches!(source, CodeActionSource::Indicator(..)));
 2293            Some(editor.render_inline_code_actions(icon_size, display_point.row(), active, cx))
 2294        })?;
 2295
 2296        let buffer_point = display_point.to_point(&snapshot.display_snapshot);
 2297
 2298        // do not show code action for folded line
 2299        if snapshot.is_line_folded(MultiBufferRow(buffer_point.row)) {
 2300            return None;
 2301        }
 2302
 2303        // do not show code action for blank line with cursor
 2304        let line_indent = snapshot
 2305            .display_snapshot
 2306            .buffer_snapshot
 2307            .line_indent_for_row(MultiBufferRow(buffer_point.row));
 2308        if line_indent.is_line_blank() {
 2309            return None;
 2310        }
 2311
 2312        const INLINE_SLOT_CHAR_LIMIT: u32 = 4;
 2313        const MAX_ALTERNATE_DISTANCE: u32 = 8;
 2314
 2315        let excerpt_id = snapshot
 2316            .display_snapshot
 2317            .buffer_snapshot
 2318            .excerpt_containing(buffer_point..buffer_point)
 2319            .map(|excerpt| excerpt.id());
 2320
 2321        let is_valid_row = |row_candidate: u32| -> bool {
 2322            // move to other row if folded row
 2323            if snapshot.is_line_folded(MultiBufferRow(row_candidate)) {
 2324                return false;
 2325            }
 2326            if buffer_point.row == row_candidate {
 2327                // move to other row if cursor is in slot
 2328                if buffer_point.column < INLINE_SLOT_CHAR_LIMIT {
 2329                    return false;
 2330                }
 2331            } else {
 2332                let candidate_point = MultiBufferPoint {
 2333                    row: row_candidate,
 2334                    column: 0,
 2335                };
 2336                let candidate_excerpt_id = snapshot
 2337                    .display_snapshot
 2338                    .buffer_snapshot
 2339                    .excerpt_containing(candidate_point..candidate_point)
 2340                    .map(|excerpt| excerpt.id());
 2341                // move to other row if different excerpt
 2342                if excerpt_id != candidate_excerpt_id {
 2343                    return false;
 2344                }
 2345            }
 2346            let line_indent = snapshot
 2347                .display_snapshot
 2348                .buffer_snapshot
 2349                .line_indent_for_row(MultiBufferRow(row_candidate));
 2350            // use this row if it's blank
 2351            if line_indent.is_line_blank() {
 2352                true
 2353            } else {
 2354                // use this row if code starts after slot
 2355                let indent_size = snapshot
 2356                    .display_snapshot
 2357                    .buffer_snapshot
 2358                    .indent_size_for_line(MultiBufferRow(row_candidate));
 2359                indent_size.len >= INLINE_SLOT_CHAR_LIMIT
 2360            }
 2361        };
 2362
 2363        let new_buffer_row = if is_valid_row(buffer_point.row) {
 2364            Some(buffer_point.row)
 2365        } else {
 2366            let max_row = snapshot.display_snapshot.buffer_snapshot.max_point().row;
 2367            (1..=MAX_ALTERNATE_DISTANCE).find_map(|offset| {
 2368                let row_above = buffer_point.row.saturating_sub(offset);
 2369                let row_below = buffer_point.row + offset;
 2370                if row_above != buffer_point.row && is_valid_row(row_above) {
 2371                    Some(row_above)
 2372                } else if row_below <= max_row && is_valid_row(row_below) {
 2373                    Some(row_below)
 2374                } else {
 2375                    None
 2376                }
 2377            })
 2378        }?;
 2379
 2380        let new_display_row = snapshot
 2381            .display_snapshot
 2382            .point_to_display_point(
 2383                Point {
 2384                    row: new_buffer_row,
 2385                    column: buffer_point.column,
 2386                },
 2387                text::Bias::Left,
 2388            )
 2389            .row();
 2390
 2391        let start_y = content_origin.y
 2392            + ((new_display_row.as_f32() - (scroll_pixel_position.y / line_height)) * line_height)
 2393            + (line_height / 2.0)
 2394            - (icon_size.square(window, cx) / 2.);
 2395        let start_x = content_origin.x - scroll_pixel_position.x + (window.rem_size() * 0.1);
 2396
 2397        let absolute_offset = gpui::point(start_x, start_y);
 2398        button.layout_as_root(gpui::AvailableSpace::min_size(), window, cx);
 2399        button.prepaint_as_root(
 2400            absolute_offset,
 2401            gpui::AvailableSpace::min_size(),
 2402            window,
 2403            cx,
 2404        );
 2405        Some(button)
 2406    }
 2407
 2408    fn layout_inline_blame(
 2409        &self,
 2410        display_row: DisplayRow,
 2411        row_info: &RowInfo,
 2412        line_layout: &LineWithInvisibles,
 2413        crease_trailer: Option<&CreaseTrailerLayout>,
 2414        em_width: Pixels,
 2415        content_origin: gpui::Point<Pixels>,
 2416        scroll_pixel_position: gpui::Point<Pixels>,
 2417        line_height: Pixels,
 2418        text_hitbox: &Hitbox,
 2419        window: &mut Window,
 2420        cx: &mut App,
 2421    ) -> Option<InlineBlameLayout> {
 2422        if !self
 2423            .editor
 2424            .update(cx, |editor, cx| editor.render_git_blame_inline(window, cx))
 2425        {
 2426            return None;
 2427        }
 2428
 2429        let editor = self.editor.read(cx);
 2430        let blame = editor.blame.clone()?;
 2431        let padding = {
 2432            const INLINE_ACCEPT_SUGGESTION_EM_WIDTHS: f32 = 14.;
 2433
 2434            let mut padding = ProjectSettings::get_global(cx)
 2435                .git
 2436                .inline_blame
 2437                .unwrap_or_default()
 2438                .padding as f32;
 2439
 2440            if let Some(edit_prediction) = editor.active_edit_prediction.as_ref() {
 2441                match &edit_prediction.completion {
 2442                    EditPrediction::Edit {
 2443                        display_mode: EditDisplayMode::TabAccept,
 2444                        ..
 2445                    } => padding += INLINE_ACCEPT_SUGGESTION_EM_WIDTHS,
 2446                    _ => {}
 2447                }
 2448            }
 2449
 2450            padding * em_width
 2451        };
 2452
 2453        let entry = blame
 2454            .update(cx, |blame, cx| {
 2455                blame.blame_for_rows(&[*row_info], cx).next()
 2456            })
 2457            .flatten()?;
 2458
 2459        let mut element = render_inline_blame_entry(entry.clone(), &self.style, cx)?;
 2460
 2461        let start_y = content_origin.y
 2462            + line_height * (display_row.as_f32() - scroll_pixel_position.y / line_height);
 2463
 2464        let start_x = {
 2465            let line_end = if let Some(crease_trailer) = crease_trailer {
 2466                crease_trailer.bounds.right()
 2467            } else {
 2468                content_origin.x - scroll_pixel_position.x + line_layout.width
 2469            };
 2470
 2471            let padded_line_end = line_end + padding;
 2472
 2473            let min_column_in_pixels = ProjectSettings::get_global(cx)
 2474                .git
 2475                .inline_blame
 2476                .map(|settings| settings.min_column)
 2477                .map(|col| self.column_pixels(col as usize, window))
 2478                .unwrap_or(px(0.));
 2479            let min_start = content_origin.x - scroll_pixel_position.x + min_column_in_pixels;
 2480
 2481            cmp::max(padded_line_end, min_start)
 2482        };
 2483
 2484        let absolute_offset = point(start_x, start_y);
 2485        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 2486        let bounds = Bounds::new(absolute_offset, size);
 2487
 2488        self.layout_blame_entry_popover(entry.clone(), blame, line_height, text_hitbox, window, cx);
 2489
 2490        element.prepaint_as_root(absolute_offset, AvailableSpace::min_size(), window, cx);
 2491
 2492        Some(InlineBlameLayout {
 2493            element,
 2494            bounds,
 2495            entry,
 2496        })
 2497    }
 2498
 2499    fn layout_blame_entry_popover(
 2500        &self,
 2501        blame_entry: BlameEntry,
 2502        blame: Entity<GitBlame>,
 2503        line_height: Pixels,
 2504        text_hitbox: &Hitbox,
 2505        window: &mut Window,
 2506        cx: &mut App,
 2507    ) {
 2508        let Some((popover_state, target_point)) = self.editor.read_with(cx, |editor, _| {
 2509            editor
 2510                .inline_blame_popover
 2511                .as_ref()
 2512                .map(|state| (state.popover_state.clone(), state.position))
 2513        }) else {
 2514            return;
 2515        };
 2516
 2517        let workspace = self
 2518            .editor
 2519            .read_with(cx, |editor, _| editor.workspace().map(|w| w.downgrade()));
 2520
 2521        let maybe_element = workspace.and_then(|workspace| {
 2522            render_blame_entry_popover(
 2523                blame_entry,
 2524                popover_state.scroll_handle,
 2525                popover_state.commit_message,
 2526                popover_state.markdown,
 2527                workspace,
 2528                &blame,
 2529                window,
 2530                cx,
 2531            )
 2532        });
 2533
 2534        if let Some(mut element) = maybe_element {
 2535            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 2536            let overall_height = size.height + HOVER_POPOVER_GAP;
 2537            let popover_origin = if target_point.y > overall_height {
 2538                point(target_point.x, target_point.y - size.height)
 2539            } else {
 2540                point(
 2541                    target_point.x,
 2542                    target_point.y + line_height + HOVER_POPOVER_GAP,
 2543                )
 2544            };
 2545
 2546            let horizontal_offset = (text_hitbox.top_right().x
 2547                - POPOVER_RIGHT_OFFSET
 2548                - (popover_origin.x + size.width))
 2549                .min(Pixels::ZERO);
 2550
 2551            let origin = point(popover_origin.x + horizontal_offset, popover_origin.y);
 2552            let popover_bounds = Bounds::new(origin, size);
 2553
 2554            self.editor.update(cx, |editor, _| {
 2555                if let Some(state) = &mut editor.inline_blame_popover {
 2556                    state.popover_bounds = Some(popover_bounds);
 2557                }
 2558            });
 2559
 2560            window.defer_draw(element, origin, 2);
 2561        }
 2562    }
 2563
 2564    fn layout_blame_entries(
 2565        &self,
 2566        buffer_rows: &[RowInfo],
 2567        em_width: Pixels,
 2568        scroll_position: gpui::Point<f32>,
 2569        line_height: Pixels,
 2570        gutter_hitbox: &Hitbox,
 2571        max_width: Option<Pixels>,
 2572        window: &mut Window,
 2573        cx: &mut App,
 2574    ) -> Option<Vec<AnyElement>> {
 2575        if !self
 2576            .editor
 2577            .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
 2578        {
 2579            return None;
 2580        }
 2581
 2582        let blame = self.editor.read(cx).blame.clone()?;
 2583        let workspace = self.editor.read(cx).workspace()?;
 2584        let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
 2585            blame.blame_for_rows(buffer_rows, cx).collect()
 2586        });
 2587
 2588        let width = if let Some(max_width) = max_width {
 2589            AvailableSpace::Definite(max_width)
 2590        } else {
 2591            AvailableSpace::MaxContent
 2592        };
 2593        let scroll_top = scroll_position.y * line_height;
 2594        let start_x = em_width;
 2595
 2596        let mut last_used_color: Option<(PlayerColor, Oid)> = None;
 2597        let blame_renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 2598
 2599        let shaped_lines = blamed_rows
 2600            .into_iter()
 2601            .enumerate()
 2602            .flat_map(|(ix, blame_entry)| {
 2603                let mut element = render_blame_entry(
 2604                    ix,
 2605                    &blame,
 2606                    blame_entry?,
 2607                    &self.style,
 2608                    &mut last_used_color,
 2609                    self.editor.clone(),
 2610                    workspace.clone(),
 2611                    blame_renderer.clone(),
 2612                    cx,
 2613                )?;
 2614
 2615                let start_y = ix as f32 * line_height - (scroll_top % line_height);
 2616                let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
 2617
 2618                element.prepaint_as_root(
 2619                    absolute_offset,
 2620                    size(width, AvailableSpace::MinContent),
 2621                    window,
 2622                    cx,
 2623                );
 2624
 2625                Some(element)
 2626            })
 2627            .collect();
 2628
 2629        Some(shaped_lines)
 2630    }
 2631
 2632    fn layout_indent_guides(
 2633        &self,
 2634        content_origin: gpui::Point<Pixels>,
 2635        text_origin: gpui::Point<Pixels>,
 2636        visible_buffer_range: Range<MultiBufferRow>,
 2637        scroll_pixel_position: gpui::Point<Pixels>,
 2638        line_height: Pixels,
 2639        snapshot: &DisplaySnapshot,
 2640        window: &mut Window,
 2641        cx: &mut App,
 2642    ) -> Option<Vec<IndentGuideLayout>> {
 2643        let indent_guides = self.editor.update(cx, |editor, cx| {
 2644            editor.indent_guides(visible_buffer_range, snapshot, cx)
 2645        })?;
 2646
 2647        let active_indent_guide_indices = self.editor.update(cx, |editor, cx| {
 2648            editor
 2649                .find_active_indent_guide_indices(&indent_guides, snapshot, window, cx)
 2650                .unwrap_or_default()
 2651        });
 2652
 2653        Some(
 2654            indent_guides
 2655                .into_iter()
 2656                .enumerate()
 2657                .filter_map(|(i, indent_guide)| {
 2658                    let single_indent_width =
 2659                        self.column_pixels(indent_guide.tab_size as usize, window);
 2660                    let total_width = single_indent_width * indent_guide.depth as f32;
 2661                    let start_x = content_origin.x + total_width - scroll_pixel_position.x;
 2662                    if start_x >= text_origin.x {
 2663                        let (offset_y, length) = Self::calculate_indent_guide_bounds(
 2664                            indent_guide.start_row..indent_guide.end_row,
 2665                            line_height,
 2666                            snapshot,
 2667                        );
 2668
 2669                        let start_y = content_origin.y + offset_y - scroll_pixel_position.y;
 2670
 2671                        Some(IndentGuideLayout {
 2672                            origin: point(start_x, start_y),
 2673                            length,
 2674                            single_indent_width,
 2675                            depth: indent_guide.depth,
 2676                            active: active_indent_guide_indices.contains(&i),
 2677                            settings: indent_guide.settings,
 2678                        })
 2679                    } else {
 2680                        None
 2681                    }
 2682                })
 2683                .collect(),
 2684        )
 2685    }
 2686
 2687    fn layout_wrap_guides(
 2688        &self,
 2689        em_advance: Pixels,
 2690        scroll_position: gpui::Point<f32>,
 2691        content_origin: gpui::Point<Pixels>,
 2692        scrollbar_layout: Option<&EditorScrollbars>,
 2693        vertical_scrollbar_width: Pixels,
 2694        hitbox: &Hitbox,
 2695        window: &Window,
 2696        cx: &App,
 2697    ) -> SmallVec<[(Pixels, bool); 2]> {
 2698        let scroll_left = scroll_position.x * em_advance;
 2699        let content_origin = content_origin.x;
 2700        let horizontal_offset = content_origin - scroll_left;
 2701        let vertical_scrollbar_width = scrollbar_layout
 2702            .and_then(|layout| layout.visible.then_some(vertical_scrollbar_width))
 2703            .unwrap_or_default();
 2704
 2705        self.editor
 2706            .read(cx)
 2707            .wrap_guides(cx)
 2708            .into_iter()
 2709            .flat_map(|(guide, active)| {
 2710                let wrap_position = self.column_pixels(guide, window);
 2711                let wrap_guide_x = wrap_position + horizontal_offset;
 2712                let display_wrap_guide = wrap_guide_x >= content_origin
 2713                    && wrap_guide_x <= hitbox.bounds.right() - vertical_scrollbar_width;
 2714
 2715                display_wrap_guide.then_some((wrap_guide_x, active))
 2716            })
 2717            .collect()
 2718    }
 2719
 2720    fn calculate_indent_guide_bounds(
 2721        row_range: Range<MultiBufferRow>,
 2722        line_height: Pixels,
 2723        snapshot: &DisplaySnapshot,
 2724    ) -> (gpui::Pixels, gpui::Pixels) {
 2725        let start_point = Point::new(row_range.start.0, 0);
 2726        let end_point = Point::new(row_range.end.0, 0);
 2727
 2728        let row_range = start_point.to_display_point(snapshot).row()
 2729            ..end_point.to_display_point(snapshot).row();
 2730
 2731        let mut prev_line = start_point;
 2732        prev_line.row = prev_line.row.saturating_sub(1);
 2733        let prev_line = prev_line.to_display_point(snapshot).row();
 2734
 2735        let mut cons_line = end_point;
 2736        cons_line.row += 1;
 2737        let cons_line = cons_line.to_display_point(snapshot).row();
 2738
 2739        let mut offset_y = row_range.start.0 as f32 * line_height;
 2740        let mut length = (cons_line.0.saturating_sub(row_range.start.0)) as f32 * line_height;
 2741
 2742        // If we are at the end of the buffer, ensure that the indent guide extends to the end of the line.
 2743        if row_range.end == cons_line {
 2744            length += line_height;
 2745        }
 2746
 2747        // If there is a block (e.g. diagnostic) in between the start of the indent guide and the line above,
 2748        // we want to extend the indent guide to the start of the block.
 2749        let mut block_height = 0;
 2750        let mut block_offset = 0;
 2751        let mut found_excerpt_header = false;
 2752        for (_, block) in snapshot.blocks_in_range(prev_line..row_range.start) {
 2753            if matches!(block, Block::ExcerptBoundary { .. }) {
 2754                found_excerpt_header = true;
 2755                break;
 2756            }
 2757            block_offset += block.height();
 2758            block_height += block.height();
 2759        }
 2760        if !found_excerpt_header {
 2761            offset_y -= block_offset as f32 * line_height;
 2762            length += block_height as f32 * line_height;
 2763        }
 2764
 2765        // If there is a block (e.g. diagnostic) at the end of an multibuffer excerpt,
 2766        // we want to ensure that the indent guide stops before the excerpt header.
 2767        let mut block_height = 0;
 2768        let mut found_excerpt_header = false;
 2769        for (_, block) in snapshot.blocks_in_range(row_range.end..cons_line) {
 2770            if matches!(block, Block::ExcerptBoundary { .. }) {
 2771                found_excerpt_header = true;
 2772            }
 2773            block_height += block.height();
 2774        }
 2775        if found_excerpt_header {
 2776            length -= block_height as f32 * line_height;
 2777        }
 2778
 2779        (offset_y, length)
 2780    }
 2781
 2782    fn layout_breakpoints(
 2783        &self,
 2784        line_height: Pixels,
 2785        range: Range<DisplayRow>,
 2786        scroll_pixel_position: gpui::Point<Pixels>,
 2787        gutter_dimensions: &GutterDimensions,
 2788        gutter_hitbox: &Hitbox,
 2789        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 2790        snapshot: &EditorSnapshot,
 2791        breakpoints: HashMap<DisplayRow, (Anchor, Breakpoint, Option<BreakpointSessionState>)>,
 2792        row_infos: &[RowInfo],
 2793        window: &mut Window,
 2794        cx: &mut App,
 2795    ) -> Vec<AnyElement> {
 2796        self.editor.update(cx, |editor, cx| {
 2797            breakpoints
 2798                .into_iter()
 2799                .filter_map(|(display_row, (text_anchor, bp, state))| {
 2800                    if row_infos
 2801                        .get((display_row.0.saturating_sub(range.start.0)) as usize)
 2802                        .is_some_and(|row_info| {
 2803                            row_info.expand_info.is_some()
 2804                                || row_info
 2805                                    .diff_status
 2806                                    .is_some_and(|status| status.is_deleted())
 2807                        })
 2808                    {
 2809                        return None;
 2810                    }
 2811
 2812                    if range.start > display_row || range.end < display_row {
 2813                        return None;
 2814                    }
 2815
 2816                    let row =
 2817                        MultiBufferRow(DisplayPoint::new(display_row, 0).to_point(snapshot).row);
 2818                    if snapshot.is_line_folded(row) {
 2819                        return None;
 2820                    }
 2821
 2822                    let button = editor.render_breakpoint(text_anchor, display_row, &bp, state, cx);
 2823
 2824                    let button = prepaint_gutter_button(
 2825                        button,
 2826                        display_row,
 2827                        line_height,
 2828                        gutter_dimensions,
 2829                        scroll_pixel_position,
 2830                        gutter_hitbox,
 2831                        display_hunks,
 2832                        window,
 2833                        cx,
 2834                    );
 2835                    Some(button)
 2836                })
 2837                .collect_vec()
 2838        })
 2839    }
 2840
 2841    #[allow(clippy::too_many_arguments)]
 2842    fn layout_run_indicators(
 2843        &self,
 2844        line_height: Pixels,
 2845        range: Range<DisplayRow>,
 2846        row_infos: &[RowInfo],
 2847        scroll_pixel_position: gpui::Point<Pixels>,
 2848        gutter_dimensions: &GutterDimensions,
 2849        gutter_hitbox: &Hitbox,
 2850        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 2851        snapshot: &EditorSnapshot,
 2852        breakpoints: &mut HashMap<DisplayRow, (Anchor, Breakpoint, Option<BreakpointSessionState>)>,
 2853        window: &mut Window,
 2854        cx: &mut App,
 2855    ) -> Vec<AnyElement> {
 2856        self.editor.update(cx, |editor, cx| {
 2857            let active_task_indicator_row =
 2858                // TODO: add edit button on the right side of each row in the context menu
 2859                if let Some(crate::CodeContextMenu::CodeActions(CodeActionsMenu {
 2860                    deployed_from,
 2861                    actions,
 2862                    ..
 2863                })) = editor.context_menu.borrow().as_ref()
 2864                {
 2865                    actions
 2866                        .tasks()
 2867                        .map(|tasks| tasks.position.to_display_point(snapshot).row())
 2868                        .or_else(|| match deployed_from {
 2869                            Some(CodeActionSource::Indicator(row)) => Some(*row),
 2870                            _ => None,
 2871                        })
 2872                } else {
 2873                    None
 2874                };
 2875
 2876            let offset_range_start =
 2877                snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left);
 2878
 2879            let offset_range_end =
 2880                snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 2881
 2882            editor
 2883                .tasks
 2884                .iter()
 2885                .filter_map(|(_, tasks)| {
 2886                    let multibuffer_point = tasks.offset.to_point(&snapshot.buffer_snapshot);
 2887                    if multibuffer_point < offset_range_start
 2888                        || multibuffer_point > offset_range_end
 2889                    {
 2890                        return None;
 2891                    }
 2892                    let multibuffer_row = MultiBufferRow(multibuffer_point.row);
 2893                    let buffer_folded = snapshot
 2894                        .buffer_snapshot
 2895                        .buffer_line_for_row(multibuffer_row)
 2896                        .map(|(buffer_snapshot, _)| buffer_snapshot.remote_id())
 2897                        .map(|buffer_id| editor.is_buffer_folded(buffer_id, cx))
 2898                        .unwrap_or(false);
 2899                    if buffer_folded {
 2900                        return None;
 2901                    }
 2902
 2903                    if snapshot.is_line_folded(multibuffer_row) {
 2904                        // Skip folded indicators, unless it's the starting line of a fold.
 2905                        if multibuffer_row
 2906                            .0
 2907                            .checked_sub(1)
 2908                            .is_some_and(|previous_row| {
 2909                                snapshot.is_line_folded(MultiBufferRow(previous_row))
 2910                            })
 2911                        {
 2912                            return None;
 2913                        }
 2914                    }
 2915
 2916                    let display_row = multibuffer_point.to_display_point(snapshot).row();
 2917                    if !range.contains(&display_row) {
 2918                        return None;
 2919                    }
 2920                    if row_infos
 2921                        .get((display_row - range.start).0 as usize)
 2922                        .is_some_and(|row_info| row_info.expand_info.is_some())
 2923                    {
 2924                        return None;
 2925                    }
 2926
 2927                    let button = editor.render_run_indicator(
 2928                        &self.style,
 2929                        Some(display_row) == active_task_indicator_row,
 2930                        display_row,
 2931                        breakpoints.remove(&display_row),
 2932                        cx,
 2933                    );
 2934
 2935                    let button = prepaint_gutter_button(
 2936                        button,
 2937                        display_row,
 2938                        line_height,
 2939                        gutter_dimensions,
 2940                        scroll_pixel_position,
 2941                        gutter_hitbox,
 2942                        display_hunks,
 2943                        window,
 2944                        cx,
 2945                    );
 2946                    Some(button)
 2947                })
 2948                .collect_vec()
 2949        })
 2950    }
 2951
 2952    fn layout_expand_toggles(
 2953        &self,
 2954        gutter_hitbox: &Hitbox,
 2955        gutter_dimensions: GutterDimensions,
 2956        em_width: Pixels,
 2957        line_height: Pixels,
 2958        scroll_position: gpui::Point<f32>,
 2959        buffer_rows: &[RowInfo],
 2960        window: &mut Window,
 2961        cx: &mut App,
 2962    ) -> Vec<Option<(AnyElement, gpui::Point<Pixels>)>> {
 2963        if self.editor.read(cx).disable_expand_excerpt_buttons {
 2964            return vec![];
 2965        }
 2966
 2967        let editor_font_size = self.style.text.font_size.to_pixels(window.rem_size()) * 1.2;
 2968
 2969        let scroll_top = scroll_position.y * line_height;
 2970
 2971        let max_line_number_length = self
 2972            .editor
 2973            .read(cx)
 2974            .buffer()
 2975            .read(cx)
 2976            .snapshot(cx)
 2977            .widest_line_number()
 2978            .ilog10()
 2979            + 1;
 2980
 2981        let elements = buffer_rows
 2982            .into_iter()
 2983            .enumerate()
 2984            .map(|(ix, row_info)| {
 2985                let ExpandInfo {
 2986                    excerpt_id,
 2987                    direction,
 2988                } = row_info.expand_info?;
 2989
 2990                let icon_name = match direction {
 2991                    ExpandExcerptDirection::Up => IconName::ExpandUp,
 2992                    ExpandExcerptDirection::Down => IconName::ExpandDown,
 2993                    ExpandExcerptDirection::UpAndDown => IconName::ExpandVertical,
 2994                };
 2995
 2996                let git_gutter_width = Self::gutter_strip_width(line_height);
 2997                let available_width = gutter_dimensions.left_padding - git_gutter_width;
 2998
 2999                let editor = self.editor.clone();
 3000                let is_wide = max_line_number_length
 3001                    >= EditorSettings::get_global(cx).gutter.min_line_number_digits as u32
 3002                    && row_info
 3003                        .buffer_row
 3004                        .is_some_and(|row| (row + 1).ilog10() + 1 == max_line_number_length)
 3005                    || gutter_dimensions.right_padding == px(0.);
 3006
 3007                let width = if is_wide {
 3008                    available_width - px(2.)
 3009                } else {
 3010                    available_width + em_width - px(2.)
 3011                };
 3012
 3013                let toggle = IconButton::new(("expand", ix), icon_name)
 3014                    .icon_color(Color::Custom(cx.theme().colors().editor_line_number))
 3015                    .selected_icon_color(Color::Custom(cx.theme().colors().editor_foreground))
 3016                    .icon_size(IconSize::Custom(rems(editor_font_size / window.rem_size())))
 3017                    .width(width)
 3018                    .on_click(move |_, window, cx| {
 3019                        editor.update(cx, |editor, cx| {
 3020                            editor.expand_excerpt(excerpt_id, direction, window, cx);
 3021                        });
 3022                    })
 3023                    .tooltip(Tooltip::for_action_title(
 3024                        "Expand Excerpt",
 3025                        &crate::actions::ExpandExcerpts::default(),
 3026                    ))
 3027                    .into_any_element();
 3028
 3029                let position = point(
 3030                    git_gutter_width + px(1.),
 3031                    ix as f32 * line_height - (scroll_top % line_height) + px(1.),
 3032                );
 3033                let origin = gutter_hitbox.origin + position;
 3034
 3035                Some((toggle, origin))
 3036            })
 3037            .collect();
 3038
 3039        elements
 3040    }
 3041
 3042    fn calculate_relative_line_numbers(
 3043        &self,
 3044        snapshot: &EditorSnapshot,
 3045        rows: &Range<DisplayRow>,
 3046        relative_to: Option<DisplayRow>,
 3047    ) -> HashMap<DisplayRow, DisplayRowDelta> {
 3048        let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
 3049        let Some(relative_to) = relative_to else {
 3050            return relative_rows;
 3051        };
 3052
 3053        let start = rows.start.min(relative_to);
 3054        let end = rows.end.max(relative_to);
 3055
 3056        let buffer_rows = snapshot
 3057            .row_infos(start)
 3058            .take(1 + end.minus(start) as usize)
 3059            .collect::<Vec<_>>();
 3060
 3061        let head_idx = relative_to.minus(start);
 3062        let mut delta = 1;
 3063        let mut i = head_idx + 1;
 3064        while i < buffer_rows.len() as u32 {
 3065            if buffer_rows[i as usize].buffer_row.is_some() {
 3066                if rows.contains(&DisplayRow(i + start.0)) {
 3067                    relative_rows.insert(DisplayRow(i + start.0), delta);
 3068                }
 3069                delta += 1;
 3070            }
 3071            i += 1;
 3072        }
 3073        delta = 1;
 3074        i = head_idx.min(buffer_rows.len() as u32 - 1);
 3075        while i > 0 && buffer_rows[i as usize].buffer_row.is_none() {
 3076            i -= 1;
 3077        }
 3078
 3079        while i > 0 {
 3080            i -= 1;
 3081            if buffer_rows[i as usize].buffer_row.is_some() {
 3082                if rows.contains(&DisplayRow(i + start.0)) {
 3083                    relative_rows.insert(DisplayRow(i + start.0), delta);
 3084                }
 3085                delta += 1;
 3086            }
 3087        }
 3088
 3089        relative_rows
 3090    }
 3091
 3092    fn layout_line_numbers(
 3093        &self,
 3094        gutter_hitbox: Option<&Hitbox>,
 3095        gutter_dimensions: GutterDimensions,
 3096        line_height: Pixels,
 3097        scroll_position: gpui::Point<f32>,
 3098        rows: Range<DisplayRow>,
 3099        buffer_rows: &[RowInfo],
 3100        active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
 3101        newest_selection_head: Option<DisplayPoint>,
 3102        snapshot: &EditorSnapshot,
 3103        window: &mut Window,
 3104        cx: &mut App,
 3105    ) -> Arc<HashMap<MultiBufferRow, LineNumberLayout>> {
 3106        let include_line_numbers = snapshot
 3107            .show_line_numbers
 3108            .unwrap_or_else(|| EditorSettings::get_global(cx).gutter.line_numbers);
 3109        if !include_line_numbers {
 3110            return Arc::default();
 3111        }
 3112
 3113        let (newest_selection_head, is_relative) = self.editor.update(cx, |editor, cx| {
 3114            let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
 3115                let newest = editor.selections.newest::<Point>(cx);
 3116                SelectionLayout::new(
 3117                    newest,
 3118                    editor.selections.line_mode,
 3119                    editor.cursor_shape,
 3120                    &snapshot.display_snapshot,
 3121                    true,
 3122                    true,
 3123                    None,
 3124                )
 3125                .head
 3126            });
 3127            let is_relative = editor.should_use_relative_line_numbers(cx);
 3128            (newest_selection_head, is_relative)
 3129        });
 3130
 3131        let relative_to = if is_relative {
 3132            Some(newest_selection_head.row())
 3133        } else {
 3134            None
 3135        };
 3136        let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
 3137        let mut line_number = String::new();
 3138        let line_numbers = buffer_rows
 3139            .into_iter()
 3140            .enumerate()
 3141            .flat_map(|(ix, row_info)| {
 3142                let display_row = DisplayRow(rows.start.0 + ix as u32);
 3143                line_number.clear();
 3144                let non_relative_number = row_info.buffer_row? + 1;
 3145                let number = relative_rows
 3146                    .get(&display_row)
 3147                    .unwrap_or(&non_relative_number);
 3148                write!(&mut line_number, "{number}").unwrap();
 3149                if row_info
 3150                    .diff_status
 3151                    .is_some_and(|status| status.is_deleted())
 3152                {
 3153                    return None;
 3154                }
 3155
 3156                let color = active_rows
 3157                    .get(&display_row)
 3158                    .map(|spec| {
 3159                        if spec.breakpoint {
 3160                            cx.theme().colors().debugger_accent
 3161                        } else {
 3162                            cx.theme().colors().editor_active_line_number
 3163                        }
 3164                    })
 3165                    .unwrap_or_else(|| cx.theme().colors().editor_line_number);
 3166                let shaped_line =
 3167                    self.shape_line_number(SharedString::from(&line_number), color, window);
 3168                let scroll_top = scroll_position.y * line_height;
 3169                let line_origin = gutter_hitbox.map(|hitbox| {
 3170                    hitbox.origin
 3171                        + point(
 3172                            hitbox.size.width - shaped_line.width - gutter_dimensions.right_padding,
 3173                            ix as f32 * line_height - (scroll_top % line_height),
 3174                        )
 3175                });
 3176
 3177                #[cfg(not(test))]
 3178                let hitbox = line_origin.map(|line_origin| {
 3179                    window.insert_hitbox(
 3180                        Bounds::new(line_origin, size(shaped_line.width, line_height)),
 3181                        HitboxBehavior::Normal,
 3182                    )
 3183                });
 3184                #[cfg(test)]
 3185                let hitbox = {
 3186                    let _ = line_origin;
 3187                    None
 3188                };
 3189
 3190                let multi_buffer_row = DisplayPoint::new(display_row, 0).to_point(snapshot).row;
 3191                let multi_buffer_row = MultiBufferRow(multi_buffer_row);
 3192                let line_number = LineNumberLayout {
 3193                    shaped_line,
 3194                    hitbox,
 3195                };
 3196                Some((multi_buffer_row, line_number))
 3197            })
 3198            .collect();
 3199        Arc::new(line_numbers)
 3200    }
 3201
 3202    fn layout_crease_toggles(
 3203        &self,
 3204        rows: Range<DisplayRow>,
 3205        row_infos: &[RowInfo],
 3206        active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
 3207        snapshot: &EditorSnapshot,
 3208        window: &mut Window,
 3209        cx: &mut App,
 3210    ) -> Vec<Option<AnyElement>> {
 3211        let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
 3212            && snapshot.mode.is_full()
 3213            && self.editor.read(cx).is_singleton(cx);
 3214        if include_fold_statuses {
 3215            row_infos
 3216                .into_iter()
 3217                .enumerate()
 3218                .map(|(ix, info)| {
 3219                    if info.expand_info.is_some() {
 3220                        return None;
 3221                    }
 3222                    let row = info.multibuffer_row?;
 3223                    let display_row = DisplayRow(rows.start.0 + ix as u32);
 3224                    let active = active_rows.contains_key(&display_row);
 3225
 3226                    snapshot.render_crease_toggle(row, active, self.editor.clone(), window, cx)
 3227                })
 3228                .collect()
 3229        } else {
 3230            Vec::new()
 3231        }
 3232    }
 3233
 3234    fn layout_crease_trailers(
 3235        &self,
 3236        buffer_rows: impl IntoIterator<Item = RowInfo>,
 3237        snapshot: &EditorSnapshot,
 3238        window: &mut Window,
 3239        cx: &mut App,
 3240    ) -> Vec<Option<AnyElement>> {
 3241        buffer_rows
 3242            .into_iter()
 3243            .map(|row_info| {
 3244                if row_info.expand_info.is_some() {
 3245                    return None;
 3246                }
 3247                if let Some(row) = row_info.multibuffer_row {
 3248                    snapshot.render_crease_trailer(row, window, cx)
 3249                } else {
 3250                    None
 3251                }
 3252            })
 3253            .collect()
 3254    }
 3255
 3256    fn layout_lines(
 3257        rows: Range<DisplayRow>,
 3258        snapshot: &EditorSnapshot,
 3259        style: &EditorStyle,
 3260        editor_width: Pixels,
 3261        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 3262        window: &mut Window,
 3263        cx: &mut App,
 3264    ) -> Vec<LineWithInvisibles> {
 3265        if rows.start >= rows.end {
 3266            return Vec::new();
 3267        }
 3268
 3269        // Show the placeholder when the editor is empty
 3270        if snapshot.is_empty() {
 3271            let font_size = style.text.font_size.to_pixels(window.rem_size());
 3272            let placeholder_color = cx.theme().colors().text_placeholder;
 3273            let placeholder_text = snapshot.placeholder_text();
 3274
 3275            let placeholder_lines = placeholder_text
 3276                .as_ref()
 3277                .map_or("", AsRef::as_ref)
 3278                .split('\n')
 3279                .skip(rows.start.0 as usize)
 3280                .chain(iter::repeat(""))
 3281                .take(rows.len());
 3282            placeholder_lines
 3283                .map(move |line| {
 3284                    let run = TextRun {
 3285                        len: line.len(),
 3286                        font: style.text.font(),
 3287                        color: placeholder_color,
 3288                        background_color: None,
 3289                        underline: None,
 3290                        strikethrough: None,
 3291                    };
 3292                    let line = window.text_system().shape_line(
 3293                        line.to_string().into(),
 3294                        font_size,
 3295                        &[run],
 3296                        None,
 3297                    );
 3298                    LineWithInvisibles {
 3299                        width: line.width,
 3300                        len: line.len,
 3301                        fragments: smallvec![LineFragment::Text(line)],
 3302                        invisibles: Vec::new(),
 3303                        font_size,
 3304                    }
 3305                })
 3306                .collect()
 3307        } else {
 3308            let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
 3309            LineWithInvisibles::from_chunks(
 3310                chunks,
 3311                style,
 3312                MAX_LINE_LEN,
 3313                rows.len(),
 3314                &snapshot.mode,
 3315                editor_width,
 3316                is_row_soft_wrapped,
 3317                window,
 3318                cx,
 3319            )
 3320        }
 3321    }
 3322
 3323    fn prepaint_lines(
 3324        &self,
 3325        start_row: DisplayRow,
 3326        line_layouts: &mut [LineWithInvisibles],
 3327        line_height: Pixels,
 3328        scroll_pixel_position: gpui::Point<Pixels>,
 3329        content_origin: gpui::Point<Pixels>,
 3330        window: &mut Window,
 3331        cx: &mut App,
 3332    ) -> SmallVec<[AnyElement; 1]> {
 3333        let mut line_elements = SmallVec::new();
 3334        for (ix, line) in line_layouts.iter_mut().enumerate() {
 3335            let row = start_row + DisplayRow(ix as u32);
 3336            line.prepaint(
 3337                line_height,
 3338                scroll_pixel_position,
 3339                row,
 3340                content_origin,
 3341                &mut line_elements,
 3342                window,
 3343                cx,
 3344            );
 3345        }
 3346        line_elements
 3347    }
 3348
 3349    fn render_block(
 3350        &self,
 3351        block: &Block,
 3352        available_width: AvailableSpace,
 3353        block_id: BlockId,
 3354        block_row_start: DisplayRow,
 3355        snapshot: &EditorSnapshot,
 3356        text_x: Pixels,
 3357        rows: &Range<DisplayRow>,
 3358        line_layouts: &[LineWithInvisibles],
 3359        editor_margins: &EditorMargins,
 3360        line_height: Pixels,
 3361        em_width: Pixels,
 3362        text_hitbox: &Hitbox,
 3363        editor_width: Pixels,
 3364        scroll_width: &mut Pixels,
 3365        resized_blocks: &mut HashMap<CustomBlockId, u32>,
 3366        row_block_types: &mut HashMap<DisplayRow, bool>,
 3367        selections: &[Selection<Point>],
 3368        selected_buffer_ids: &Vec<BufferId>,
 3369        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 3370        sticky_header_excerpt_id: Option<ExcerptId>,
 3371        window: &mut Window,
 3372        cx: &mut App,
 3373    ) -> Option<(AnyElement, Size<Pixels>, DisplayRow, Pixels)> {
 3374        let mut x_position = None;
 3375        let mut element = match block {
 3376            Block::Custom(custom) => {
 3377                let block_start = custom.start().to_point(&snapshot.buffer_snapshot);
 3378                let block_end = custom.end().to_point(&snapshot.buffer_snapshot);
 3379                if block.place_near() && snapshot.is_line_folded(MultiBufferRow(block_start.row)) {
 3380                    return None;
 3381                }
 3382                let align_to = block_start.to_display_point(snapshot);
 3383                let x_and_width = |layout: &LineWithInvisibles| {
 3384                    Some((
 3385                        text_x + layout.x_for_index(align_to.column() as usize),
 3386                        text_x + layout.width,
 3387                    ))
 3388                };
 3389                let line_ix = align_to.row().0.checked_sub(rows.start.0);
 3390                x_position =
 3391                    if let Some(layout) = line_ix.and_then(|ix| line_layouts.get(ix as usize)) {
 3392                        x_and_width(layout)
 3393                    } else {
 3394                        x_and_width(&layout_line(
 3395                            align_to.row(),
 3396                            snapshot,
 3397                            &self.style,
 3398                            editor_width,
 3399                            is_row_soft_wrapped,
 3400                            window,
 3401                            cx,
 3402                        ))
 3403                    };
 3404
 3405                let anchor_x = x_position.unwrap().0;
 3406
 3407                let selected = selections
 3408                    .binary_search_by(|selection| {
 3409                        if selection.end <= block_start {
 3410                            Ordering::Less
 3411                        } else if selection.start >= block_end {
 3412                            Ordering::Greater
 3413                        } else {
 3414                            Ordering::Equal
 3415                        }
 3416                    })
 3417                    .is_ok();
 3418
 3419                div()
 3420                    .size_full()
 3421                    .child(custom.render(&mut BlockContext {
 3422                        window,
 3423                        app: cx,
 3424                        anchor_x,
 3425                        margins: editor_margins,
 3426                        line_height,
 3427                        em_width,
 3428                        block_id,
 3429                        selected,
 3430                        max_width: text_hitbox.size.width.max(*scroll_width),
 3431                        editor_style: &self.style,
 3432                    }))
 3433                    .into_any()
 3434            }
 3435
 3436            Block::FoldedBuffer {
 3437                first_excerpt,
 3438                height,
 3439                ..
 3440            } => {
 3441                let selected = selected_buffer_ids.contains(&first_excerpt.buffer_id);
 3442                let result = v_flex().id(block_id).w_full().pr(editor_margins.right);
 3443
 3444                let jump_data = header_jump_data(snapshot, block_row_start, *height, first_excerpt);
 3445                result
 3446                    .child(self.render_buffer_header(
 3447                        first_excerpt,
 3448                        true,
 3449                        selected,
 3450                        false,
 3451                        jump_data,
 3452                        window,
 3453                        cx,
 3454                    ))
 3455                    .into_any_element()
 3456            }
 3457
 3458            Block::ExcerptBoundary {
 3459                excerpt,
 3460                height,
 3461                starts_new_buffer,
 3462                ..
 3463            } => {
 3464                let color = cx.theme().colors().clone();
 3465                let mut result = v_flex().id(block_id).w_full();
 3466
 3467                let jump_data = header_jump_data(snapshot, block_row_start, *height, excerpt);
 3468
 3469                if *starts_new_buffer {
 3470                    if sticky_header_excerpt_id != Some(excerpt.id) {
 3471                        let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
 3472
 3473                        result = result.child(div().pr(editor_margins.right).child(
 3474                            self.render_buffer_header(
 3475                                excerpt, false, selected, false, jump_data, window, cx,
 3476                            ),
 3477                        ));
 3478                    } else {
 3479                        result =
 3480                            result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
 3481                    }
 3482                } else {
 3483                    result = result.child(
 3484                        h_flex().relative().child(
 3485                            div()
 3486                                .top(line_height / 2.)
 3487                                .absolute()
 3488                                .w_full()
 3489                                .h_px()
 3490                                .bg(color.border_variant),
 3491                        ),
 3492                    );
 3493                };
 3494
 3495                result.into_any()
 3496            }
 3497        };
 3498
 3499        // Discover the element's content height, then round up to the nearest multiple of line height.
 3500        let preliminary_size = element.layout_as_root(
 3501            size(available_width, AvailableSpace::MinContent),
 3502            window,
 3503            cx,
 3504        );
 3505        let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
 3506        let final_size = if preliminary_size.height == quantized_height {
 3507            preliminary_size
 3508        } else {
 3509            element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
 3510        };
 3511        let mut element_height_in_lines = ((final_size.height / line_height).ceil() as u32).max(1);
 3512
 3513        let mut row = block_row_start;
 3514        let mut x_offset = px(0.);
 3515        let mut is_block = true;
 3516
 3517        if let BlockId::Custom(custom_block_id) = block_id
 3518            && block.has_height()
 3519        {
 3520            if block.place_near()
 3521                && let Some((x_target, line_width)) = x_position
 3522            {
 3523                let margin = em_width * 2;
 3524                if line_width + final_size.width + margin
 3525                    < editor_width + editor_margins.gutter.full_width()
 3526                    && !row_block_types.contains_key(&(row - 1))
 3527                    && element_height_in_lines == 1
 3528                {
 3529                    x_offset = line_width + margin;
 3530                    row = row - 1;
 3531                    is_block = false;
 3532                    element_height_in_lines = 0;
 3533                    row_block_types.insert(row, is_block);
 3534                } else {
 3535                    let max_offset =
 3536                        editor_width + editor_margins.gutter.full_width() - final_size.width;
 3537                    let min_offset = (x_target + em_width - final_size.width)
 3538                        .max(editor_margins.gutter.full_width());
 3539                    x_offset = x_target.min(max_offset).max(min_offset);
 3540                }
 3541            };
 3542            if element_height_in_lines != block.height() {
 3543                resized_blocks.insert(custom_block_id, element_height_in_lines);
 3544            }
 3545        }
 3546        for i in 0..element_height_in_lines {
 3547            row_block_types.insert(row + i, is_block);
 3548        }
 3549
 3550        Some((element, final_size, row, x_offset))
 3551    }
 3552
 3553    fn render_buffer_header(
 3554        &self,
 3555        for_excerpt: &ExcerptInfo,
 3556        is_folded: bool,
 3557        is_selected: bool,
 3558        is_sticky: bool,
 3559        jump_data: JumpData,
 3560        window: &mut Window,
 3561        cx: &mut App,
 3562    ) -> impl IntoElement {
 3563        let editor = self.editor.read(cx);
 3564        let multi_buffer = editor.buffer.read(cx);
 3565        let file_status = multi_buffer
 3566            .all_diff_hunks_expanded()
 3567            .then(|| {
 3568                editor
 3569                    .project
 3570                    .as_ref()?
 3571                    .read(cx)
 3572                    .status_for_buffer_id(for_excerpt.buffer_id, cx)
 3573            })
 3574            .flatten();
 3575        let indicator = multi_buffer
 3576            .buffer(for_excerpt.buffer_id)
 3577            .and_then(|buffer| {
 3578                let buffer = buffer.read(cx);
 3579                let indicator_color = match (buffer.has_conflict(), buffer.is_dirty()) {
 3580                    (true, _) => Some(Color::Warning),
 3581                    (_, true) => Some(Color::Accent),
 3582                    (false, false) => None,
 3583                };
 3584                indicator_color.map(|indicator_color| Indicator::dot().color(indicator_color))
 3585            });
 3586
 3587        let include_root = editor
 3588            .project
 3589            .as_ref()
 3590            .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 3591            .unwrap_or_default();
 3592        let can_open_excerpts = Editor::can_open_excerpts_in_file(for_excerpt.buffer.file());
 3593        let relative_path = for_excerpt.buffer.resolve_file_path(cx, include_root);
 3594        let filename = relative_path
 3595            .as_ref()
 3596            .and_then(|path| Some(path.file_name()?.to_string_lossy().to_string()));
 3597        let parent_path = relative_path.as_ref().and_then(|path| {
 3598            Some(path.parent()?.to_string_lossy().to_string() + std::path::MAIN_SEPARATOR_STR)
 3599        });
 3600        let focus_handle = editor.focus_handle(cx);
 3601        let colors = cx.theme().colors();
 3602
 3603        let header =
 3604            div()
 3605                .p_1()
 3606                .w_full()
 3607                .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
 3608                .child(
 3609                    h_flex()
 3610                        .size_full()
 3611                        .gap_2()
 3612                        .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
 3613                        .pl_0p5()
 3614                        .pr_5()
 3615                        .rounded_sm()
 3616                        .when(is_sticky, |el| el.shadow_md())
 3617                        .border_1()
 3618                        .map(|div| {
 3619                            let border_color = if is_selected
 3620                                && is_folded
 3621                                && focus_handle.contains_focused(window, cx)
 3622                            {
 3623                                colors.border_focused
 3624                            } else {
 3625                                colors.border
 3626                            };
 3627                            div.border_color(border_color)
 3628                        })
 3629                        .bg(colors.editor_subheader_background)
 3630                        .hover(|style| style.bg(colors.element_hover))
 3631                        .map(|header| {
 3632                            let editor = self.editor.clone();
 3633                            let buffer_id = for_excerpt.buffer_id;
 3634                            let toggle_chevron_icon =
 3635                                FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
 3636                            header.child(
 3637                                div()
 3638                                    .hover(|style| style.bg(colors.element_selected))
 3639                                    .rounded_xs()
 3640                                    .child(
 3641                                        ButtonLike::new("toggle-buffer-fold")
 3642                                            .style(ui::ButtonStyle::Transparent)
 3643                                            .height(px(28.).into())
 3644                                            .width(px(28.))
 3645                                            .children(toggle_chevron_icon)
 3646                                            .tooltip({
 3647                                                let focus_handle = focus_handle.clone();
 3648                                                move |window, cx| {
 3649                                                    Tooltip::with_meta_in(
 3650                                                        "Toggle Excerpt Fold",
 3651                                                        Some(&ToggleFold),
 3652                                                        "Alt+click to toggle all",
 3653                                                        &focus_handle,
 3654                                                        window,
 3655                                                        cx,
 3656                                                    )
 3657                                                }
 3658                                            })
 3659                                            .on_click(move |event, window, cx| {
 3660                                                if event.modifiers().alt {
 3661                                                    // Alt+click toggles all buffers
 3662                                                    editor.update(cx, |editor, cx| {
 3663                                                        editor.toggle_fold_all(
 3664                                                            &ToggleFoldAll,
 3665                                                            window,
 3666                                                            cx,
 3667                                                        );
 3668                                                    });
 3669                                                } else {
 3670                                                    // Regular click toggles single buffer
 3671                                                    if is_folded {
 3672                                                        editor.update(cx, |editor, cx| {
 3673                                                            editor.unfold_buffer(buffer_id, cx);
 3674                                                        });
 3675                                                    } else {
 3676                                                        editor.update(cx, |editor, cx| {
 3677                                                            editor.fold_buffer(buffer_id, cx);
 3678                                                        });
 3679                                                    }
 3680                                                }
 3681                                            }),
 3682                                    ),
 3683                            )
 3684                        })
 3685                        .children(
 3686                            editor
 3687                                .addons
 3688                                .values()
 3689                                .filter_map(|addon| {
 3690                                    addon.render_buffer_header_controls(for_excerpt, window, cx)
 3691                                })
 3692                                .take(1),
 3693                        )
 3694                        .children(indicator)
 3695                        .child(
 3696                            h_flex()
 3697                                .cursor_pointer()
 3698                                .id("path header block")
 3699                                .size_full()
 3700                                .justify_between()
 3701                                .overflow_hidden()
 3702                                .child(
 3703                                    h_flex()
 3704                                        .gap_2()
 3705                                        .child(
 3706                                            Label::new(
 3707                                                filename
 3708                                                    .map(SharedString::from)
 3709                                                    .unwrap_or_else(|| "untitled".into()),
 3710                                            )
 3711                                            .single_line()
 3712                                            .when_some(file_status, |el, status| {
 3713                                                el.color(if status.is_conflicted() {
 3714                                                    Color::Conflict
 3715                                                } else if status.is_modified() {
 3716                                                    Color::Modified
 3717                                                } else if status.is_deleted() {
 3718                                                    Color::Disabled
 3719                                                } else {
 3720                                                    Color::Created
 3721                                                })
 3722                                                .when(status.is_deleted(), |el| el.strikethrough())
 3723                                            }),
 3724                                        )
 3725                                        .when_some(parent_path, |then, path| {
 3726                                            then.child(div().child(path).text_color(
 3727                                                if file_status.is_some_and(FileStatus::is_deleted) {
 3728                                                    colors.text_disabled
 3729                                                } else {
 3730                                                    colors.text_muted
 3731                                                },
 3732                                            ))
 3733                                        }),
 3734                                )
 3735                                .when(
 3736                                    can_open_excerpts && is_selected && relative_path.is_some(),
 3737                                    |el| {
 3738                                        el.child(
 3739                                            h_flex()
 3740                                                .id("jump-to-file-button")
 3741                                                .gap_2p5()
 3742                                                .child(Label::new("Jump To File"))
 3743                                                .children(
 3744                                                    KeyBinding::for_action_in(
 3745                                                        &OpenExcerpts,
 3746                                                        &focus_handle,
 3747                                                        window,
 3748                                                        cx,
 3749                                                    )
 3750                                                    .map(|binding| binding.into_any_element()),
 3751                                                ),
 3752                                        )
 3753                                    },
 3754                                )
 3755                                .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 3756                                .on_click(window.listener_for(&self.editor, {
 3757                                    move |editor, e: &ClickEvent, window, cx| {
 3758                                        editor.open_excerpts_common(
 3759                                            Some(jump_data.clone()),
 3760                                            e.modifiers().secondary(),
 3761                                            window,
 3762                                            cx,
 3763                                        );
 3764                                    }
 3765                                })),
 3766                        ),
 3767                );
 3768
 3769        let file = for_excerpt.buffer.file().cloned();
 3770        let editor = self.editor.clone();
 3771        right_click_menu("buffer-header-context-menu")
 3772            .trigger(move |_, _, _| header)
 3773            .menu(move |window, cx| {
 3774                let menu_context = focus_handle.clone();
 3775                let editor = editor.clone();
 3776                let file = file.clone();
 3777                ContextMenu::build(window, cx, move |mut menu, window, cx| {
 3778                    if let Some(file) = file
 3779                        && let Some(project) = editor.read(cx).project()
 3780                        && let Some(worktree) =
 3781                            project.read(cx).worktree_for_id(file.worktree_id(cx), cx)
 3782                    {
 3783                        let relative_path = file.path();
 3784                        let entry_for_path = worktree.read(cx).entry_for_path(relative_path);
 3785                        let abs_path = entry_for_path.and_then(|e| e.canonical_path.as_deref());
 3786                        let has_relative_path =
 3787                            worktree.read(cx).root_entry().is_some_and(Entry::is_dir);
 3788
 3789                        let parent_abs_path =
 3790                            abs_path.and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
 3791                        let relative_path = has_relative_path
 3792                            .then_some(relative_path)
 3793                            .map(ToOwned::to_owned);
 3794
 3795                        let visible_in_project_panel =
 3796                            relative_path.is_some() && worktree.read(cx).is_visible();
 3797                        let reveal_in_project_panel = entry_for_path
 3798                            .filter(|_| visible_in_project_panel)
 3799                            .map(|entry| entry.id);
 3800                        menu = menu
 3801                            .when_some(abs_path.map(ToOwned::to_owned), |menu, abs_path| {
 3802                                menu.entry(
 3803                                    "Copy Path",
 3804                                    Some(Box::new(zed_actions::workspace::CopyPath)),
 3805                                    window.handler_for(&editor, move |_, _, cx| {
 3806                                        cx.write_to_clipboard(ClipboardItem::new_string(
 3807                                            abs_path.to_string_lossy().to_string(),
 3808                                        ));
 3809                                    }),
 3810                                )
 3811                            })
 3812                            .when_some(relative_path, |menu, relative_path| {
 3813                                menu.entry(
 3814                                    "Copy Relative Path",
 3815                                    Some(Box::new(zed_actions::workspace::CopyRelativePath)),
 3816                                    window.handler_for(&editor, move |_, _, cx| {
 3817                                        cx.write_to_clipboard(ClipboardItem::new_string(
 3818                                            relative_path.to_string_lossy().to_string(),
 3819                                        ));
 3820                                    }),
 3821                                )
 3822                            })
 3823                            .when(
 3824                                reveal_in_project_panel.is_some() || parent_abs_path.is_some(),
 3825                                |menu| menu.separator(),
 3826                            )
 3827                            .when_some(reveal_in_project_panel, |menu, entry_id| {
 3828                                menu.entry(
 3829                                    "Reveal In Project Panel",
 3830                                    Some(Box::new(RevealInProjectPanel::default())),
 3831                                    window.handler_for(&editor, move |editor, _, cx| {
 3832                                        if let Some(project) = &mut editor.project {
 3833                                            project.update(cx, |_, cx| {
 3834                                                cx.emit(project::Event::RevealInProjectPanel(
 3835                                                    entry_id,
 3836                                                ))
 3837                                            });
 3838                                        }
 3839                                    }),
 3840                                )
 3841                            })
 3842                            .when_some(parent_abs_path, |menu, parent_abs_path| {
 3843                                menu.entry(
 3844                                    "Open in Terminal",
 3845                                    Some(Box::new(OpenInTerminal)),
 3846                                    window.handler_for(&editor, move |_, window, cx| {
 3847                                        window.dispatch_action(
 3848                                            OpenTerminal {
 3849                                                working_directory: parent_abs_path.clone(),
 3850                                            }
 3851                                            .boxed_clone(),
 3852                                            cx,
 3853                                        );
 3854                                    }),
 3855                                )
 3856                            });
 3857                    }
 3858
 3859                    menu.context(menu_context)
 3860                })
 3861            })
 3862    }
 3863
 3864    fn render_blocks(
 3865        &self,
 3866        rows: Range<DisplayRow>,
 3867        snapshot: &EditorSnapshot,
 3868        hitbox: &Hitbox,
 3869        text_hitbox: &Hitbox,
 3870        editor_width: Pixels,
 3871        scroll_width: &mut Pixels,
 3872        editor_margins: &EditorMargins,
 3873        em_width: Pixels,
 3874        text_x: Pixels,
 3875        line_height: Pixels,
 3876        line_layouts: &mut [LineWithInvisibles],
 3877        selections: &[Selection<Point>],
 3878        selected_buffer_ids: &Vec<BufferId>,
 3879        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 3880        sticky_header_excerpt_id: Option<ExcerptId>,
 3881        window: &mut Window,
 3882        cx: &mut App,
 3883    ) -> Result<(Vec<BlockLayout>, HashMap<DisplayRow, bool>), HashMap<CustomBlockId, u32>> {
 3884        let (fixed_blocks, non_fixed_blocks) = snapshot
 3885            .blocks_in_range(rows.clone())
 3886            .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
 3887
 3888        let mut focused_block = self
 3889            .editor
 3890            .update(cx, |editor, _| editor.take_focused_block());
 3891        let mut fixed_block_max_width = Pixels::ZERO;
 3892        let mut blocks = Vec::new();
 3893        let mut resized_blocks = HashMap::default();
 3894        let mut row_block_types = HashMap::default();
 3895
 3896        for (row, block) in fixed_blocks {
 3897            let block_id = block.id();
 3898
 3899            if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
 3900                focused_block = None;
 3901            }
 3902
 3903            if let Some((element, element_size, row, x_offset)) = self.render_block(
 3904                block,
 3905                AvailableSpace::MinContent,
 3906                block_id,
 3907                row,
 3908                snapshot,
 3909                text_x,
 3910                &rows,
 3911                line_layouts,
 3912                editor_margins,
 3913                line_height,
 3914                em_width,
 3915                text_hitbox,
 3916                editor_width,
 3917                scroll_width,
 3918                &mut resized_blocks,
 3919                &mut row_block_types,
 3920                selections,
 3921                selected_buffer_ids,
 3922                is_row_soft_wrapped,
 3923                sticky_header_excerpt_id,
 3924                window,
 3925                cx,
 3926            ) {
 3927                fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
 3928                blocks.push(BlockLayout {
 3929                    id: block_id,
 3930                    x_offset,
 3931                    row: Some(row),
 3932                    element,
 3933                    available_space: size(AvailableSpace::MinContent, element_size.height.into()),
 3934                    style: BlockStyle::Fixed,
 3935                    overlaps_gutter: true,
 3936                    is_buffer_header: block.is_buffer_header(),
 3937                });
 3938            }
 3939        }
 3940
 3941        for (row, block) in non_fixed_blocks {
 3942            let style = block.style();
 3943            let width = match (style, block.place_near()) {
 3944                (_, true) => AvailableSpace::MinContent,
 3945                (BlockStyle::Sticky, _) => hitbox.size.width.into(),
 3946                (BlockStyle::Flex, _) => hitbox
 3947                    .size
 3948                    .width
 3949                    .max(fixed_block_max_width)
 3950                    .max(editor_margins.gutter.width + *scroll_width)
 3951                    .into(),
 3952                (BlockStyle::Fixed, _) => unreachable!(),
 3953            };
 3954            let block_id = block.id();
 3955
 3956            if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
 3957                focused_block = None;
 3958            }
 3959
 3960            if let Some((element, element_size, row, x_offset)) = self.render_block(
 3961                block,
 3962                width,
 3963                block_id,
 3964                row,
 3965                snapshot,
 3966                text_x,
 3967                &rows,
 3968                line_layouts,
 3969                editor_margins,
 3970                line_height,
 3971                em_width,
 3972                text_hitbox,
 3973                editor_width,
 3974                scroll_width,
 3975                &mut resized_blocks,
 3976                &mut row_block_types,
 3977                selections,
 3978                selected_buffer_ids,
 3979                is_row_soft_wrapped,
 3980                sticky_header_excerpt_id,
 3981                window,
 3982                cx,
 3983            ) {
 3984                blocks.push(BlockLayout {
 3985                    id: block_id,
 3986                    x_offset,
 3987                    row: Some(row),
 3988                    element,
 3989                    available_space: size(width, element_size.height.into()),
 3990                    style,
 3991                    overlaps_gutter: !block.place_near(),
 3992                    is_buffer_header: block.is_buffer_header(),
 3993                });
 3994            }
 3995        }
 3996
 3997        if let Some(focused_block) = focused_block
 3998            && let Some(focus_handle) = focused_block.focus_handle.upgrade()
 3999            && focus_handle.is_focused(window)
 4000            && let Some(block) = snapshot.block_for_id(focused_block.id)
 4001        {
 4002            let style = block.style();
 4003            let width = match style {
 4004                BlockStyle::Fixed => AvailableSpace::MinContent,
 4005                BlockStyle::Flex => AvailableSpace::Definite(
 4006                    hitbox
 4007                        .size
 4008                        .width
 4009                        .max(fixed_block_max_width)
 4010                        .max(editor_margins.gutter.width + *scroll_width),
 4011                ),
 4012                BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
 4013            };
 4014
 4015            if let Some((element, element_size, _, x_offset)) = self.render_block(
 4016                &block,
 4017                width,
 4018                focused_block.id,
 4019                rows.end,
 4020                snapshot,
 4021                text_x,
 4022                &rows,
 4023                line_layouts,
 4024                editor_margins,
 4025                line_height,
 4026                em_width,
 4027                text_hitbox,
 4028                editor_width,
 4029                scroll_width,
 4030                &mut resized_blocks,
 4031                &mut row_block_types,
 4032                selections,
 4033                selected_buffer_ids,
 4034                is_row_soft_wrapped,
 4035                sticky_header_excerpt_id,
 4036                window,
 4037                cx,
 4038            ) {
 4039                blocks.push(BlockLayout {
 4040                    id: block.id(),
 4041                    x_offset,
 4042                    row: None,
 4043                    element,
 4044                    available_space: size(width, element_size.height.into()),
 4045                    style,
 4046                    overlaps_gutter: true,
 4047                    is_buffer_header: block.is_buffer_header(),
 4048                });
 4049            }
 4050        }
 4051
 4052        if resized_blocks.is_empty() {
 4053            *scroll_width =
 4054                (*scroll_width).max(fixed_block_max_width - editor_margins.gutter.width);
 4055            Ok((blocks, row_block_types))
 4056        } else {
 4057            Err(resized_blocks)
 4058        }
 4059    }
 4060
 4061    fn layout_blocks(
 4062        &self,
 4063        blocks: &mut Vec<BlockLayout>,
 4064        hitbox: &Hitbox,
 4065        line_height: Pixels,
 4066        scroll_pixel_position: gpui::Point<Pixels>,
 4067        window: &mut Window,
 4068        cx: &mut App,
 4069    ) {
 4070        for block in blocks {
 4071            let mut origin = if let Some(row) = block.row {
 4072                hitbox.origin
 4073                    + point(
 4074                        block.x_offset,
 4075                        row.as_f32() * line_height - scroll_pixel_position.y,
 4076                    )
 4077            } else {
 4078                // Position the block outside the visible area
 4079                hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
 4080            };
 4081
 4082            if !matches!(block.style, BlockStyle::Sticky) {
 4083                origin += point(-scroll_pixel_position.x, Pixels::ZERO);
 4084            }
 4085
 4086            let focus_handle =
 4087                block
 4088                    .element
 4089                    .prepaint_as_root(origin, block.available_space, window, cx);
 4090
 4091            if let Some(focus_handle) = focus_handle {
 4092                self.editor.update(cx, |editor, _cx| {
 4093                    editor.set_focused_block(FocusedBlock {
 4094                        id: block.id,
 4095                        focus_handle: focus_handle.downgrade(),
 4096                    });
 4097                });
 4098            }
 4099        }
 4100    }
 4101
 4102    fn layout_sticky_buffer_header(
 4103        &self,
 4104        StickyHeaderExcerpt { excerpt }: StickyHeaderExcerpt<'_>,
 4105        scroll_position: f32,
 4106        line_height: Pixels,
 4107        right_margin: Pixels,
 4108        snapshot: &EditorSnapshot,
 4109        hitbox: &Hitbox,
 4110        selected_buffer_ids: &Vec<BufferId>,
 4111        blocks: &[BlockLayout],
 4112        window: &mut Window,
 4113        cx: &mut App,
 4114    ) -> AnyElement {
 4115        let jump_data = header_jump_data(
 4116            snapshot,
 4117            DisplayRow(scroll_position as u32),
 4118            FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 4119            excerpt,
 4120        );
 4121
 4122        let editor_bg_color = cx.theme().colors().editor_background;
 4123
 4124        let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
 4125
 4126        let available_width = hitbox.bounds.size.width - right_margin;
 4127
 4128        let mut header = v_flex()
 4129            .w_full()
 4130            .relative()
 4131            .child(
 4132                div()
 4133                    .w(available_width)
 4134                    .h(FILE_HEADER_HEIGHT as f32 * line_height)
 4135                    .bg(linear_gradient(
 4136                        0.,
 4137                        linear_color_stop(editor_bg_color.opacity(0.), 0.),
 4138                        linear_color_stop(editor_bg_color, 0.6),
 4139                    ))
 4140                    .absolute()
 4141                    .top_0(),
 4142            )
 4143            .child(
 4144                self.render_buffer_header(excerpt, false, selected, true, jump_data, window, cx)
 4145                    .into_any_element(),
 4146            )
 4147            .into_any_element();
 4148
 4149        let mut origin = hitbox.origin;
 4150        // Move floating header up to avoid colliding with the next buffer header.
 4151        for block in blocks.iter() {
 4152            if !block.is_buffer_header {
 4153                continue;
 4154            }
 4155
 4156            let Some(display_row) = block.row.filter(|row| row.0 > scroll_position as u32) else {
 4157                continue;
 4158            };
 4159
 4160            let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
 4161            let offset = scroll_position - max_row as f32;
 4162
 4163            if offset > 0.0 {
 4164                origin.y -= offset * line_height;
 4165            }
 4166            break;
 4167        }
 4168
 4169        let size = size(
 4170            AvailableSpace::Definite(available_width),
 4171            AvailableSpace::MinContent,
 4172        );
 4173
 4174        header.prepaint_as_root(origin, size, window, cx);
 4175
 4176        header
 4177    }
 4178
 4179    fn layout_cursor_popovers(
 4180        &self,
 4181        line_height: Pixels,
 4182        text_hitbox: &Hitbox,
 4183        content_origin: gpui::Point<Pixels>,
 4184        right_margin: Pixels,
 4185        start_row: DisplayRow,
 4186        scroll_pixel_position: gpui::Point<Pixels>,
 4187        line_layouts: &[LineWithInvisibles],
 4188        cursor: DisplayPoint,
 4189        cursor_point: Point,
 4190        style: &EditorStyle,
 4191        window: &mut Window,
 4192        cx: &mut App,
 4193    ) -> Option<ContextMenuLayout> {
 4194        let mut min_menu_height = Pixels::ZERO;
 4195        let mut max_menu_height = Pixels::ZERO;
 4196        let mut height_above_menu = Pixels::ZERO;
 4197        let height_below_menu = Pixels::ZERO;
 4198        let mut edit_prediction_popover_visible = false;
 4199        let mut context_menu_visible = false;
 4200        let context_menu_placement;
 4201
 4202        {
 4203            let editor = self.editor.read(cx);
 4204            if editor.edit_prediction_visible_in_cursor_popover(editor.has_active_edit_prediction())
 4205            {
 4206                height_above_menu +=
 4207                    editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
 4208                edit_prediction_popover_visible = true;
 4209            }
 4210
 4211            if editor.context_menu_visible()
 4212                && let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin()
 4213            {
 4214                let (min_height_in_lines, max_height_in_lines) = editor
 4215                    .context_menu_options
 4216                    .as_ref()
 4217                    .map_or((3, 12), |options| {
 4218                        (options.min_entries_visible, options.max_entries_visible)
 4219                    });
 4220
 4221                min_menu_height += line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
 4222                max_menu_height += line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
 4223                context_menu_visible = true;
 4224            }
 4225            context_menu_placement = editor
 4226                .context_menu_options
 4227                .as_ref()
 4228                .and_then(|options| options.placement.clone());
 4229        }
 4230
 4231        let visible = edit_prediction_popover_visible || context_menu_visible;
 4232        if !visible {
 4233            return None;
 4234        }
 4235
 4236        let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
 4237        let target_position = content_origin
 4238            + gpui::Point {
 4239                x: cmp::max(
 4240                    px(0.),
 4241                    cursor_row_layout.x_for_index(cursor.column() as usize)
 4242                        - scroll_pixel_position.x,
 4243                ),
 4244                y: cmp::max(
 4245                    px(0.),
 4246                    cursor.row().next_row().as_f32() * line_height - scroll_pixel_position.y,
 4247                ),
 4248            };
 4249
 4250        let viewport_bounds =
 4251            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 4252                right: -right_margin - MENU_GAP,
 4253                ..Default::default()
 4254            });
 4255
 4256        let min_height = height_above_menu + min_menu_height + height_below_menu;
 4257        let max_height = height_above_menu + max_menu_height + height_below_menu;
 4258        let (laid_out_popovers, y_flipped) = self.layout_popovers_above_or_below_line(
 4259            target_position,
 4260            line_height,
 4261            min_height,
 4262            max_height,
 4263            context_menu_placement,
 4264            text_hitbox,
 4265            viewport_bounds,
 4266            window,
 4267            cx,
 4268            |height, max_width_for_stable_x, y_flipped, window, cx| {
 4269                // First layout the menu to get its size - others can be at least this wide.
 4270                let context_menu = if context_menu_visible {
 4271                    let menu_height = if y_flipped {
 4272                        height - height_below_menu
 4273                    } else {
 4274                        height - height_above_menu
 4275                    };
 4276                    let mut element = self
 4277                        .render_context_menu(line_height, menu_height, window, cx)
 4278                        .expect("Visible context menu should always render.");
 4279                    let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 4280                    Some((CursorPopoverType::CodeContextMenu, element, size))
 4281                } else {
 4282                    None
 4283                };
 4284                let min_width = context_menu
 4285                    .as_ref()
 4286                    .map_or(px(0.), |(_, _, size)| size.width);
 4287                let max_width = max_width_for_stable_x.max(
 4288                    context_menu
 4289                        .as_ref()
 4290                        .map_or(px(0.), |(_, _, size)| size.width),
 4291                );
 4292
 4293                let edit_prediction = if edit_prediction_popover_visible {
 4294                    self.editor.update(cx, move |editor, cx| {
 4295                        let accept_binding =
 4296                            editor.accept_edit_prediction_keybind(false, window, cx);
 4297                        let mut element = editor.render_edit_prediction_cursor_popover(
 4298                            min_width,
 4299                            max_width,
 4300                            cursor_point,
 4301                            style,
 4302                            accept_binding.keystroke(),
 4303                            window,
 4304                            cx,
 4305                        )?;
 4306                        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 4307                        Some((CursorPopoverType::EditPrediction, element, size))
 4308                    })
 4309                } else {
 4310                    None
 4311                };
 4312                vec![edit_prediction, context_menu]
 4313                    .into_iter()
 4314                    .flatten()
 4315                    .collect::<Vec<_>>()
 4316            },
 4317        )?;
 4318
 4319        let (menu_ix, (_, menu_bounds)) = laid_out_popovers
 4320            .iter()
 4321            .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))?;
 4322        let last_ix = laid_out_popovers.len() - 1;
 4323        let menu_is_last = menu_ix == last_ix;
 4324        let first_popover_bounds = laid_out_popovers[0].1;
 4325        let last_popover_bounds = laid_out_popovers[last_ix].1;
 4326
 4327        // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
 4328        // right, and otherwise it goes below or to the right.
 4329        let mut target_bounds = Bounds::from_corners(
 4330            first_popover_bounds.origin,
 4331            last_popover_bounds.bottom_right(),
 4332        );
 4333        target_bounds.size.width = menu_bounds.size.width;
 4334
 4335        // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
 4336        // based on this is preferred for layout stability.
 4337        let mut max_target_bounds = target_bounds;
 4338        max_target_bounds.size.height = max_height;
 4339        if y_flipped {
 4340            max_target_bounds.origin.y -= max_height - target_bounds.size.height;
 4341        }
 4342
 4343        // Add spacing around `target_bounds` and `max_target_bounds`.
 4344        let mut extend_amount = Edges::all(MENU_GAP);
 4345        if y_flipped {
 4346            extend_amount.bottom = line_height;
 4347        } else {
 4348            extend_amount.top = line_height;
 4349        }
 4350        let target_bounds = target_bounds.extend(extend_amount);
 4351        let max_target_bounds = max_target_bounds.extend(extend_amount);
 4352
 4353        let must_place_above_or_below =
 4354            if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
 4355                laid_out_popovers[menu_ix + 1..]
 4356                    .iter()
 4357                    .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
 4358            } else {
 4359                false
 4360            };
 4361
 4362        let aside_bounds = self.layout_context_menu_aside(
 4363            y_flipped,
 4364            *menu_bounds,
 4365            target_bounds,
 4366            max_target_bounds,
 4367            max_menu_height,
 4368            must_place_above_or_below,
 4369            text_hitbox,
 4370            viewport_bounds,
 4371            window,
 4372            cx,
 4373        );
 4374
 4375        if let Some(menu_bounds) = laid_out_popovers.iter().find_map(|(popover_type, bounds)| {
 4376            if matches!(popover_type, CursorPopoverType::CodeContextMenu) {
 4377                Some(*bounds)
 4378            } else {
 4379                None
 4380            }
 4381        }) {
 4382            let bounds = if let Some(aside_bounds) = aside_bounds {
 4383                menu_bounds.union(&aside_bounds)
 4384            } else {
 4385                menu_bounds
 4386            };
 4387            return Some(ContextMenuLayout { y_flipped, bounds });
 4388        }
 4389
 4390        None
 4391    }
 4392
 4393    fn layout_gutter_menu(
 4394        &self,
 4395        line_height: Pixels,
 4396        text_hitbox: &Hitbox,
 4397        content_origin: gpui::Point<Pixels>,
 4398        right_margin: Pixels,
 4399        scroll_pixel_position: gpui::Point<Pixels>,
 4400        gutter_overshoot: Pixels,
 4401        window: &mut Window,
 4402        cx: &mut App,
 4403    ) {
 4404        let editor = self.editor.read(cx);
 4405        if !editor.context_menu_visible() {
 4406            return;
 4407        }
 4408        let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
 4409            editor.context_menu_origin()
 4410        else {
 4411            return;
 4412        };
 4413        // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
 4414        // indicator than just a plain first column of the text field.
 4415        let target_position = content_origin
 4416            + gpui::Point {
 4417                x: -gutter_overshoot,
 4418                y: gutter_row.next_row().as_f32() * line_height - scroll_pixel_position.y,
 4419            };
 4420
 4421        let (min_height_in_lines, max_height_in_lines) = editor
 4422            .context_menu_options
 4423            .as_ref()
 4424            .map_or((3, 12), |options| {
 4425                (options.min_entries_visible, options.max_entries_visible)
 4426            });
 4427
 4428        let min_height = line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
 4429        let max_height = line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
 4430        let viewport_bounds =
 4431            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 4432                right: -right_margin - MENU_GAP,
 4433                ..Default::default()
 4434            });
 4435        self.layout_popovers_above_or_below_line(
 4436            target_position,
 4437            line_height,
 4438            min_height,
 4439            max_height,
 4440            editor
 4441                .context_menu_options
 4442                .as_ref()
 4443                .and_then(|options| options.placement.clone()),
 4444            text_hitbox,
 4445            viewport_bounds,
 4446            window,
 4447            cx,
 4448            move |height, _max_width_for_stable_x, _, window, cx| {
 4449                let mut element = self
 4450                    .render_context_menu(line_height, height, window, cx)
 4451                    .expect("Visible context menu should always render.");
 4452                let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 4453                vec![(CursorPopoverType::CodeContextMenu, element, size)]
 4454            },
 4455        );
 4456    }
 4457
 4458    fn layout_popovers_above_or_below_line(
 4459        &self,
 4460        target_position: gpui::Point<Pixels>,
 4461        line_height: Pixels,
 4462        min_height: Pixels,
 4463        max_height: Pixels,
 4464        placement: Option<ContextMenuPlacement>,
 4465        text_hitbox: &Hitbox,
 4466        viewport_bounds: Bounds<Pixels>,
 4467        window: &mut Window,
 4468        cx: &mut App,
 4469        make_sized_popovers: impl FnOnce(
 4470            Pixels,
 4471            Pixels,
 4472            bool,
 4473            &mut Window,
 4474            &mut App,
 4475        ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
 4476    ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
 4477        let text_style = TextStyleRefinement {
 4478            line_height: Some(DefiniteLength::Fraction(
 4479                BufferLineHeight::Comfortable.value(),
 4480            )),
 4481            ..Default::default()
 4482        };
 4483        window.with_text_style(Some(text_style), |window| {
 4484            // If the max height won't fit below and there is more space above, put it above the line.
 4485            let bottom_y_when_flipped = target_position.y - line_height;
 4486            let available_above = bottom_y_when_flipped - text_hitbox.top();
 4487            let available_below = text_hitbox.bottom() - target_position.y;
 4488            let y_overflows_below = max_height > available_below;
 4489            let mut y_flipped = match placement {
 4490                Some(ContextMenuPlacement::Above) => true,
 4491                Some(ContextMenuPlacement::Below) => false,
 4492                None => y_overflows_below && available_above > available_below,
 4493            };
 4494            let mut height = cmp::min(
 4495                max_height,
 4496                if y_flipped {
 4497                    available_above
 4498                } else {
 4499                    available_below
 4500                },
 4501            );
 4502
 4503            // If the min height doesn't fit within text bounds, instead fit within the window.
 4504            if height < min_height {
 4505                let available_above = bottom_y_when_flipped;
 4506                let available_below = viewport_bounds.bottom() - target_position.y;
 4507                let (y_flipped_override, height_override) = match placement {
 4508                    Some(ContextMenuPlacement::Above) => {
 4509                        (true, cmp::min(available_above, min_height))
 4510                    }
 4511                    Some(ContextMenuPlacement::Below) => {
 4512                        (false, cmp::min(available_below, min_height))
 4513                    }
 4514                    None => {
 4515                        if available_below > min_height {
 4516                            (false, min_height)
 4517                        } else if available_above > min_height {
 4518                            (true, min_height)
 4519                        } else if available_above > available_below {
 4520                            (true, available_above)
 4521                        } else {
 4522                            (false, available_below)
 4523                        }
 4524                    }
 4525                };
 4526                y_flipped = y_flipped_override;
 4527                height = height_override;
 4528            }
 4529
 4530            let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
 4531
 4532            // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
 4533            // for very narrow windows.
 4534            let popovers =
 4535                make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
 4536            if popovers.is_empty() {
 4537                return None;
 4538            }
 4539
 4540            let max_width = popovers
 4541                .iter()
 4542                .map(|(_, _, size)| size.width)
 4543                .max()
 4544                .unwrap_or_default();
 4545
 4546            let mut current_position = gpui::Point {
 4547                // Snap the right edge of the list to the right edge of the window if its horizontal bounds
 4548                // overflow. Include space for the scrollbar.
 4549                x: target_position
 4550                    .x
 4551                    .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
 4552                y: if y_flipped {
 4553                    bottom_y_when_flipped
 4554                } else {
 4555                    target_position.y
 4556                },
 4557            };
 4558
 4559            let mut laid_out_popovers = popovers
 4560                .into_iter()
 4561                .map(|(popover_type, element, size)| {
 4562                    if y_flipped {
 4563                        current_position.y -= size.height;
 4564                    }
 4565                    let position = current_position;
 4566                    window.defer_draw(element, current_position, 1);
 4567                    if !y_flipped {
 4568                        current_position.y += size.height + MENU_GAP;
 4569                    } else {
 4570                        current_position.y -= MENU_GAP;
 4571                    }
 4572                    (popover_type, Bounds::new(position, size))
 4573                })
 4574                .collect::<Vec<_>>();
 4575
 4576            if y_flipped {
 4577                laid_out_popovers.reverse();
 4578            }
 4579
 4580            Some((laid_out_popovers, y_flipped))
 4581        })
 4582    }
 4583
 4584    fn layout_context_menu_aside(
 4585        &self,
 4586        y_flipped: bool,
 4587        menu_bounds: Bounds<Pixels>,
 4588        target_bounds: Bounds<Pixels>,
 4589        max_target_bounds: Bounds<Pixels>,
 4590        max_height: Pixels,
 4591        must_place_above_or_below: bool,
 4592        text_hitbox: &Hitbox,
 4593        viewport_bounds: Bounds<Pixels>,
 4594        window: &mut Window,
 4595        cx: &mut App,
 4596    ) -> Option<Bounds<Pixels>> {
 4597        let available_within_viewport = target_bounds.space_within(&viewport_bounds);
 4598        let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
 4599            && !must_place_above_or_below
 4600        {
 4601            let max_width = cmp::min(
 4602                available_within_viewport.right - px(1.),
 4603                MENU_ASIDE_MAX_WIDTH,
 4604            );
 4605            let mut aside = self.render_context_menu_aside(
 4606                size(max_width, max_height - POPOVER_Y_PADDING),
 4607                window,
 4608                cx,
 4609            )?;
 4610            let size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
 4611            let right_position = point(target_bounds.right(), menu_bounds.origin.y);
 4612            Some((aside, right_position, size))
 4613        } else {
 4614            let max_size = size(
 4615                // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
 4616                // won't be needed here.
 4617                cmp::min(
 4618                    cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
 4619                    viewport_bounds.right(),
 4620                ),
 4621                cmp::min(
 4622                    max_height,
 4623                    cmp::max(
 4624                        available_within_viewport.top,
 4625                        available_within_viewport.bottom,
 4626                    ),
 4627                ) - POPOVER_Y_PADDING,
 4628            );
 4629            let mut aside = self.render_context_menu_aside(max_size, window, cx)?;
 4630            let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
 4631
 4632            let top_position = point(
 4633                menu_bounds.origin.x,
 4634                target_bounds.top() - actual_size.height,
 4635            );
 4636            let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
 4637
 4638            let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
 4639                // Prefer to fit on the same side of the line as the menu, then on the other side of
 4640                // the line.
 4641                if !y_flipped && wanted.height < available.bottom {
 4642                    Some(bottom_position)
 4643                } else if !y_flipped && wanted.height < available.top {
 4644                    Some(top_position)
 4645                } else if y_flipped && wanted.height < available.top {
 4646                    Some(top_position)
 4647                } else if y_flipped && wanted.height < available.bottom {
 4648                    Some(bottom_position)
 4649                } else {
 4650                    None
 4651                }
 4652            };
 4653
 4654            // Prefer choosing a direction using max sizes rather than actual size for stability.
 4655            let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
 4656            let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
 4657            let aside_position = fit_within(available_within_text, wanted)
 4658                // Fallback: fit max size in window.
 4659                .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
 4660                // Fallback: fit actual size in window.
 4661                .or_else(|| fit_within(available_within_viewport, actual_size));
 4662
 4663            aside_position.map(|position| (aside, position, actual_size))
 4664        };
 4665
 4666        // Skip drawing if it doesn't fit anywhere.
 4667        if let Some((aside, position, size)) = positioned_aside {
 4668            let aside_bounds = Bounds::new(position, size);
 4669            window.defer_draw(aside, position, 2);
 4670            return Some(aside_bounds);
 4671        }
 4672
 4673        None
 4674    }
 4675
 4676    fn render_context_menu(
 4677        &self,
 4678        line_height: Pixels,
 4679        height: Pixels,
 4680        window: &mut Window,
 4681        cx: &mut App,
 4682    ) -> Option<AnyElement> {
 4683        let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
 4684        self.editor.update(cx, |editor, cx| {
 4685            editor.render_context_menu(&self.style, max_height_in_lines, window, cx)
 4686        })
 4687    }
 4688
 4689    fn render_context_menu_aside(
 4690        &self,
 4691        max_size: Size<Pixels>,
 4692        window: &mut Window,
 4693        cx: &mut App,
 4694    ) -> Option<AnyElement> {
 4695        if max_size.width < px(100.) || max_size.height < px(12.) {
 4696            None
 4697        } else {
 4698            self.editor.update(cx, |editor, cx| {
 4699                editor.render_context_menu_aside(max_size, window, cx)
 4700            })
 4701        }
 4702    }
 4703
 4704    fn layout_mouse_context_menu(
 4705        &self,
 4706        editor_snapshot: &EditorSnapshot,
 4707        visible_range: Range<DisplayRow>,
 4708        content_origin: gpui::Point<Pixels>,
 4709        window: &mut Window,
 4710        cx: &mut App,
 4711    ) -> Option<AnyElement> {
 4712        let position = self.editor.update(cx, |editor, _cx| {
 4713            let visible_start_point = editor.display_to_pixel_point(
 4714                DisplayPoint::new(visible_range.start, 0),
 4715                editor_snapshot,
 4716                window,
 4717            )?;
 4718            let visible_end_point = editor.display_to_pixel_point(
 4719                DisplayPoint::new(visible_range.end, 0),
 4720                editor_snapshot,
 4721                window,
 4722            )?;
 4723
 4724            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
 4725            let (source_display_point, position) = match mouse_context_menu.position {
 4726                MenuPosition::PinnedToScreen(point) => (None, point),
 4727                MenuPosition::PinnedToEditor { source, offset } => {
 4728                    let source_display_point = source.to_display_point(editor_snapshot);
 4729                    let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
 4730                    let position = content_origin + source_point + offset;
 4731                    (Some(source_display_point), position)
 4732                }
 4733            };
 4734
 4735            let source_included = source_display_point.is_none_or(|source_display_point| {
 4736                visible_range
 4737                    .to_inclusive()
 4738                    .contains(&source_display_point.row())
 4739            });
 4740            let position_included =
 4741                visible_start_point.y <= position.y && position.y <= visible_end_point.y;
 4742            if !source_included && !position_included {
 4743                None
 4744            } else {
 4745                Some(position)
 4746            }
 4747        })?;
 4748
 4749        let text_style = TextStyleRefinement {
 4750            line_height: Some(DefiniteLength::Fraction(
 4751                BufferLineHeight::Comfortable.value(),
 4752            )),
 4753            ..Default::default()
 4754        };
 4755        window.with_text_style(Some(text_style), |window| {
 4756            let mut element = self.editor.read_with(cx, |editor, _| {
 4757                let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
 4758                let context_menu = mouse_context_menu.context_menu.clone();
 4759
 4760                Some(
 4761                    deferred(
 4762                        anchored()
 4763                            .position(position)
 4764                            .child(context_menu)
 4765                            .anchor(Corner::TopLeft)
 4766                            .snap_to_window_with_margin(px(8.)),
 4767                    )
 4768                    .with_priority(1)
 4769                    .into_any(),
 4770                )
 4771            })?;
 4772
 4773            element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
 4774            Some(element)
 4775        })
 4776    }
 4777
 4778    fn layout_hover_popovers(
 4779        &self,
 4780        snapshot: &EditorSnapshot,
 4781        hitbox: &Hitbox,
 4782        visible_display_row_range: Range<DisplayRow>,
 4783        content_origin: gpui::Point<Pixels>,
 4784        scroll_pixel_position: gpui::Point<Pixels>,
 4785        line_layouts: &[LineWithInvisibles],
 4786        line_height: Pixels,
 4787        em_width: Pixels,
 4788        context_menu_layout: Option<ContextMenuLayout>,
 4789        window: &mut Window,
 4790        cx: &mut App,
 4791    ) {
 4792        struct MeasuredHoverPopover {
 4793            element: AnyElement,
 4794            size: Size<Pixels>,
 4795            horizontal_offset: Pixels,
 4796        }
 4797
 4798        let max_size = size(
 4799            (120. * em_width) // Default size
 4800                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
 4801                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
 4802            (16. * line_height) // Default size
 4803                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
 4804                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
 4805        );
 4806
 4807        let hover_popovers = self.editor.update(cx, |editor, cx| {
 4808            editor.hover_state.render(
 4809                snapshot,
 4810                visible_display_row_range.clone(),
 4811                max_size,
 4812                window,
 4813                cx,
 4814            )
 4815        });
 4816        let Some((position, hover_popovers)) = hover_popovers else {
 4817            return;
 4818        };
 4819
 4820        // This is safe because we check on layout whether the required row is available
 4821        let hovered_row_layout =
 4822            &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
 4823
 4824        // Compute Hovered Point
 4825        let x =
 4826            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
 4827        let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
 4828        let hovered_point = content_origin + point(x, y);
 4829
 4830        let mut overall_height = Pixels::ZERO;
 4831        let mut measured_hover_popovers = Vec::new();
 4832        for (position, mut hover_popover) in hover_popovers.into_iter().with_position() {
 4833            let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
 4834            let horizontal_offset =
 4835                (hitbox.top_right().x - POPOVER_RIGHT_OFFSET - (hovered_point.x + size.width))
 4836                    .min(Pixels::ZERO);
 4837            match position {
 4838                itertools::Position::Middle | itertools::Position::Last => {
 4839                    overall_height += HOVER_POPOVER_GAP
 4840                }
 4841                _ => {}
 4842            }
 4843            overall_height += size.height;
 4844            measured_hover_popovers.push(MeasuredHoverPopover {
 4845                element: hover_popover,
 4846                size,
 4847                horizontal_offset,
 4848            });
 4849        }
 4850
 4851        fn draw_occluder(
 4852            width: Pixels,
 4853            origin: gpui::Point<Pixels>,
 4854            window: &mut Window,
 4855            cx: &mut App,
 4856        ) {
 4857            let mut occlusion = div()
 4858                .size_full()
 4859                .occlude()
 4860                .on_mouse_move(|_, _, cx| cx.stop_propagation())
 4861                .into_any_element();
 4862            occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
 4863            window.defer_draw(occlusion, origin, 2);
 4864        }
 4865
 4866        fn place_popovers_above(
 4867            hovered_point: gpui::Point<Pixels>,
 4868            measured_hover_popovers: Vec<MeasuredHoverPopover>,
 4869            window: &mut Window,
 4870            cx: &mut App,
 4871        ) {
 4872            let mut current_y = hovered_point.y;
 4873            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 4874                let size = popover.size;
 4875                let popover_origin = point(
 4876                    hovered_point.x + popover.horizontal_offset,
 4877                    current_y - size.height,
 4878                );
 4879
 4880                window.defer_draw(popover.element, popover_origin, 2);
 4881                if position != itertools::Position::Last {
 4882                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
 4883                    draw_occluder(size.width, origin, window, cx);
 4884                }
 4885
 4886                current_y = popover_origin.y - HOVER_POPOVER_GAP;
 4887            }
 4888        }
 4889
 4890        fn place_popovers_below(
 4891            hovered_point: gpui::Point<Pixels>,
 4892            measured_hover_popovers: Vec<MeasuredHoverPopover>,
 4893            line_height: Pixels,
 4894            window: &mut Window,
 4895            cx: &mut App,
 4896        ) {
 4897            let mut current_y = hovered_point.y + line_height;
 4898            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 4899                let size = popover.size;
 4900                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
 4901
 4902                window.defer_draw(popover.element, popover_origin, 2);
 4903                if position != itertools::Position::Last {
 4904                    let origin = point(popover_origin.x, popover_origin.y + size.height);
 4905                    draw_occluder(size.width, origin, window, cx);
 4906                }
 4907
 4908                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 4909            }
 4910        }
 4911
 4912        let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
 4913            context_menu_layout
 4914                .as_ref()
 4915                .is_some_and(|menu| bounds.intersects(&menu.bounds))
 4916        };
 4917
 4918        let can_place_above = {
 4919            let mut bounds_above = Vec::new();
 4920            let mut current_y = hovered_point.y;
 4921            for popover in &measured_hover_popovers {
 4922                let size = popover.size;
 4923                let popover_origin = point(
 4924                    hovered_point.x + popover.horizontal_offset,
 4925                    current_y - size.height,
 4926                );
 4927                bounds_above.push(Bounds::new(popover_origin, size));
 4928                current_y = popover_origin.y - HOVER_POPOVER_GAP;
 4929            }
 4930            bounds_above
 4931                .iter()
 4932                .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
 4933        };
 4934
 4935        let can_place_below = || {
 4936            let mut bounds_below = Vec::new();
 4937            let mut current_y = hovered_point.y + line_height;
 4938            for popover in &measured_hover_popovers {
 4939                let size = popover.size;
 4940                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
 4941                bounds_below.push(Bounds::new(popover_origin, size));
 4942                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 4943            }
 4944            bounds_below
 4945                .iter()
 4946                .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
 4947        };
 4948
 4949        if can_place_above {
 4950            // try placing above hovered point
 4951            place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
 4952        } else if can_place_below() {
 4953            // try placing below hovered point
 4954            place_popovers_below(
 4955                hovered_point,
 4956                measured_hover_popovers,
 4957                line_height,
 4958                window,
 4959                cx,
 4960            );
 4961        } else {
 4962            // try to place popovers around the context menu
 4963            let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
 4964                let total_width = measured_hover_popovers
 4965                    .iter()
 4966                    .map(|p| p.size.width)
 4967                    .max()
 4968                    .unwrap_or(Pixels::ZERO);
 4969                let y_for_horizontal_positioning = if menu.y_flipped {
 4970                    menu.bounds.bottom() - overall_height
 4971                } else {
 4972                    menu.bounds.top()
 4973                };
 4974                let possible_origins = vec![
 4975                    // left of context menu
 4976                    point(
 4977                        menu.bounds.left() - total_width - HOVER_POPOVER_GAP,
 4978                        y_for_horizontal_positioning,
 4979                    ),
 4980                    // right of context menu
 4981                    point(
 4982                        menu.bounds.right() + HOVER_POPOVER_GAP,
 4983                        y_for_horizontal_positioning,
 4984                    ),
 4985                    // top of context menu
 4986                    point(
 4987                        menu.bounds.left(),
 4988                        menu.bounds.top() - overall_height - HOVER_POPOVER_GAP,
 4989                    ),
 4990                    // bottom of context menu
 4991                    point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
 4992                ];
 4993                possible_origins.into_iter().find(|&origin| {
 4994                    Bounds::new(origin, size(total_width, overall_height))
 4995                        .is_contained_within(hitbox)
 4996                })
 4997            });
 4998            if let Some(origin) = origin_surrounding_menu {
 4999                let mut current_y = origin.y;
 5000                for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 5001                    let size = popover.size;
 5002                    let popover_origin = point(origin.x, current_y);
 5003
 5004                    window.defer_draw(popover.element, popover_origin, 2);
 5005                    if position != itertools::Position::Last {
 5006                        let origin = point(popover_origin.x, popover_origin.y + size.height);
 5007                        draw_occluder(size.width, origin, window, cx);
 5008                    }
 5009
 5010                    current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 5011                }
 5012            } else {
 5013                // fallback to existing above/below cursor logic
 5014                // this might overlap menu or overflow in rare case
 5015                if can_place_above {
 5016                    place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
 5017                } else {
 5018                    place_popovers_below(
 5019                        hovered_point,
 5020                        measured_hover_popovers,
 5021                        line_height,
 5022                        window,
 5023                        cx,
 5024                    );
 5025                }
 5026            }
 5027        }
 5028    }
 5029
 5030    fn layout_diff_hunk_controls(
 5031        &self,
 5032        row_range: Range<DisplayRow>,
 5033        row_infos: &[RowInfo],
 5034        text_hitbox: &Hitbox,
 5035        newest_cursor_position: Option<DisplayPoint>,
 5036        line_height: Pixels,
 5037        right_margin: Pixels,
 5038        scroll_pixel_position: gpui::Point<Pixels>,
 5039        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 5040        highlighted_rows: &BTreeMap<DisplayRow, LineHighlight>,
 5041        editor: Entity<Editor>,
 5042        window: &mut Window,
 5043        cx: &mut App,
 5044    ) -> (Vec<AnyElement>, Vec<(DisplayRow, Bounds<Pixels>)>) {
 5045        let render_diff_hunk_controls = editor.read(cx).render_diff_hunk_controls.clone();
 5046        let hovered_diff_hunk_row = editor.read(cx).hovered_diff_hunk_row;
 5047
 5048        let mut controls = vec![];
 5049        let mut control_bounds = vec![];
 5050
 5051        let active_positions = [
 5052            hovered_diff_hunk_row.map(|row| DisplayPoint::new(row, 0)),
 5053            newest_cursor_position,
 5054        ];
 5055
 5056        for (hunk, _) in display_hunks {
 5057            if let DisplayDiffHunk::Unfolded {
 5058                display_row_range,
 5059                multi_buffer_range,
 5060                status,
 5061                is_created_file,
 5062                ..
 5063            } = &hunk
 5064            {
 5065                if display_row_range.start < row_range.start
 5066                    || display_row_range.start >= row_range.end
 5067                {
 5068                    continue;
 5069                }
 5070                if highlighted_rows
 5071                    .get(&display_row_range.start)
 5072                    .and_then(|highlight| highlight.type_id)
 5073                    .is_some_and(|type_id| {
 5074                        [
 5075                            TypeId::of::<ConflictsOuter>(),
 5076                            TypeId::of::<ConflictsOursMarker>(),
 5077                            TypeId::of::<ConflictsOurs>(),
 5078                            TypeId::of::<ConflictsTheirs>(),
 5079                            TypeId::of::<ConflictsTheirsMarker>(),
 5080                        ]
 5081                        .contains(&type_id)
 5082                    })
 5083                {
 5084                    continue;
 5085                }
 5086                let row_ix = (display_row_range.start - row_range.start).0 as usize;
 5087                if row_infos[row_ix].diff_status.is_none() {
 5088                    continue;
 5089                }
 5090                if row_infos[row_ix]
 5091                    .diff_status
 5092                    .is_some_and(|status| status.is_added())
 5093                    && !status.is_added()
 5094                {
 5095                    continue;
 5096                }
 5097
 5098                if active_positions
 5099                    .iter()
 5100                    .any(|p| p.is_some_and(|p| display_row_range.contains(&p.row())))
 5101                {
 5102                    let y = display_row_range.start.as_f32() * line_height
 5103                        + text_hitbox.bounds.top()
 5104                        - scroll_pixel_position.y;
 5105
 5106                    let mut element = render_diff_hunk_controls(
 5107                        display_row_range.start.0,
 5108                        status,
 5109                        multi_buffer_range.clone(),
 5110                        *is_created_file,
 5111                        line_height,
 5112                        &editor,
 5113                        window,
 5114                        cx,
 5115                    );
 5116                    let size =
 5117                        element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
 5118
 5119                    let x = text_hitbox.bounds.right() - right_margin - px(10.) - size.width;
 5120
 5121                    let bounds = Bounds::new(gpui::Point::new(x, y), size);
 5122                    control_bounds.push((display_row_range.start, bounds));
 5123
 5124                    window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
 5125                        element.prepaint(window, cx)
 5126                    });
 5127                    controls.push(element);
 5128                }
 5129            }
 5130        }
 5131
 5132        (controls, control_bounds)
 5133    }
 5134
 5135    fn layout_signature_help(
 5136        &self,
 5137        hitbox: &Hitbox,
 5138        content_origin: gpui::Point<Pixels>,
 5139        scroll_pixel_position: gpui::Point<Pixels>,
 5140        newest_selection_head: Option<DisplayPoint>,
 5141        start_row: DisplayRow,
 5142        line_layouts: &[LineWithInvisibles],
 5143        line_height: Pixels,
 5144        em_width: Pixels,
 5145        context_menu_layout: Option<ContextMenuLayout>,
 5146        window: &mut Window,
 5147        cx: &mut App,
 5148    ) {
 5149        if !self.editor.focus_handle(cx).is_focused(window) {
 5150            return;
 5151        }
 5152        let Some(newest_selection_head) = newest_selection_head else {
 5153            return;
 5154        };
 5155
 5156        let max_size = size(
 5157            (120. * em_width) // Default size
 5158                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
 5159                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
 5160            (16. * line_height) // Default size
 5161                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
 5162                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
 5163        );
 5164
 5165        let maybe_element = self.editor.update(cx, |editor, cx| {
 5166            if let Some(popover) = editor.signature_help_state.popover_mut() {
 5167                let element = popover.render(max_size, window, cx);
 5168                Some(element)
 5169            } else {
 5170                None
 5171            }
 5172        });
 5173        let Some(mut element) = maybe_element else {
 5174            return;
 5175        };
 5176
 5177        let selection_row = newest_selection_head.row();
 5178        let Some(cursor_row_layout) = (selection_row >= start_row)
 5179            .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
 5180            .flatten()
 5181        else {
 5182            return;
 5183        };
 5184
 5185        let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
 5186            - scroll_pixel_position.x;
 5187        let target_y = selection_row.as_f32() * line_height - scroll_pixel_position.y;
 5188        let target_point = content_origin + point(target_x, target_y);
 5189
 5190        let actual_size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
 5191
 5192        let (popover_bounds_above, popover_bounds_below) = {
 5193            let horizontal_offset = (hitbox.top_right().x
 5194                - POPOVER_RIGHT_OFFSET
 5195                - (target_point.x + actual_size.width))
 5196                .min(Pixels::ZERO);
 5197            let initial_x = target_point.x + horizontal_offset;
 5198            (
 5199                Bounds::new(
 5200                    point(initial_x, target_point.y - actual_size.height),
 5201                    actual_size,
 5202                ),
 5203                Bounds::new(
 5204                    point(initial_x, target_point.y + line_height + HOVER_POPOVER_GAP),
 5205                    actual_size,
 5206                ),
 5207            )
 5208        };
 5209
 5210        let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
 5211            context_menu_layout
 5212                .as_ref()
 5213                .is_some_and(|menu| bounds.intersects(&menu.bounds))
 5214        };
 5215
 5216        let final_origin = if popover_bounds_above.is_contained_within(hitbox)
 5217            && !intersects_menu(popover_bounds_above)
 5218        {
 5219            // try placing above cursor
 5220            popover_bounds_above.origin
 5221        } else if popover_bounds_below.is_contained_within(hitbox)
 5222            && !intersects_menu(popover_bounds_below)
 5223        {
 5224            // try placing below cursor
 5225            popover_bounds_below.origin
 5226        } else {
 5227            // try surrounding context menu if exists
 5228            let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
 5229                let y_for_horizontal_positioning = if menu.y_flipped {
 5230                    menu.bounds.bottom() - actual_size.height
 5231                } else {
 5232                    menu.bounds.top()
 5233                };
 5234                let possible_origins = vec![
 5235                    // left of context menu
 5236                    point(
 5237                        menu.bounds.left() - actual_size.width - HOVER_POPOVER_GAP,
 5238                        y_for_horizontal_positioning,
 5239                    ),
 5240                    // right of context menu
 5241                    point(
 5242                        menu.bounds.right() + HOVER_POPOVER_GAP,
 5243                        y_for_horizontal_positioning,
 5244                    ),
 5245                    // top of context menu
 5246                    point(
 5247                        menu.bounds.left(),
 5248                        menu.bounds.top() - actual_size.height - HOVER_POPOVER_GAP,
 5249                    ),
 5250                    // bottom of context menu
 5251                    point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
 5252                ];
 5253                possible_origins
 5254                    .into_iter()
 5255                    .find(|&origin| Bounds::new(origin, actual_size).is_contained_within(hitbox))
 5256            });
 5257            origin_surrounding_menu.unwrap_or_else(|| {
 5258                // fallback to existing above/below cursor logic
 5259                // this might overlap menu or overflow in rare case
 5260                if popover_bounds_above.is_contained_within(hitbox) {
 5261                    popover_bounds_above.origin
 5262                } else {
 5263                    popover_bounds_below.origin
 5264                }
 5265            })
 5266        };
 5267
 5268        window.defer_draw(element, final_origin, 2);
 5269    }
 5270
 5271    fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
 5272        window.paint_layer(layout.hitbox.bounds, |window| {
 5273            let scroll_top = layout.position_map.snapshot.scroll_position().y;
 5274            let gutter_bg = cx.theme().colors().editor_gutter_background;
 5275            window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
 5276            window.paint_quad(fill(
 5277                layout.position_map.text_hitbox.bounds,
 5278                self.style.background,
 5279            ));
 5280
 5281            if matches!(
 5282                layout.mode,
 5283                EditorMode::Full { .. } | EditorMode::Minimap { .. }
 5284            ) {
 5285                let show_active_line_background = match layout.mode {
 5286                    EditorMode::Full {
 5287                        show_active_line_background,
 5288                        ..
 5289                    } => show_active_line_background,
 5290                    EditorMode::Minimap { .. } => true,
 5291                    _ => false,
 5292                };
 5293                let mut active_rows = layout.active_rows.iter().peekable();
 5294                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
 5295                    let mut end_row = start_row.0;
 5296                    while active_rows
 5297                        .peek()
 5298                        .is_some_and(|(active_row, has_selection)| {
 5299                            active_row.0 == end_row + 1
 5300                                && has_selection.selection == contains_non_empty_selection.selection
 5301                        })
 5302                    {
 5303                        active_rows.next().unwrap();
 5304                        end_row += 1;
 5305                    }
 5306
 5307                    if show_active_line_background && !contains_non_empty_selection.selection {
 5308                        let highlight_h_range =
 5309                            match layout.position_map.snapshot.current_line_highlight {
 5310                                CurrentLineHighlight::Gutter => Some(Range {
 5311                                    start: layout.hitbox.left(),
 5312                                    end: layout.gutter_hitbox.right(),
 5313                                }),
 5314                                CurrentLineHighlight::Line => Some(Range {
 5315                                    start: layout.position_map.text_hitbox.bounds.left(),
 5316                                    end: layout.position_map.text_hitbox.bounds.right(),
 5317                                }),
 5318                                CurrentLineHighlight::All => Some(Range {
 5319                                    start: layout.hitbox.left(),
 5320                                    end: layout.hitbox.right(),
 5321                                }),
 5322                                CurrentLineHighlight::None => None,
 5323                            };
 5324                        if let Some(range) = highlight_h_range {
 5325                            let active_line_bg = cx.theme().colors().editor_active_line_background;
 5326                            let bounds = Bounds {
 5327                                origin: point(
 5328                                    range.start,
 5329                                    layout.hitbox.origin.y
 5330                                        + (start_row.as_f32() - scroll_top)
 5331                                            * layout.position_map.line_height,
 5332                                ),
 5333                                size: size(
 5334                                    range.end - range.start,
 5335                                    layout.position_map.line_height
 5336                                        * (end_row - start_row.0 + 1) as f32,
 5337                                ),
 5338                            };
 5339                            window.paint_quad(fill(bounds, active_line_bg));
 5340                        }
 5341                    }
 5342                }
 5343
 5344                let mut paint_highlight = |highlight_row_start: DisplayRow,
 5345                                           highlight_row_end: DisplayRow,
 5346                                           highlight: crate::LineHighlight,
 5347                                           edges| {
 5348                    let mut origin_x = layout.hitbox.left();
 5349                    let mut width = layout.hitbox.size.width;
 5350                    if !highlight.include_gutter {
 5351                        origin_x += layout.gutter_hitbox.size.width;
 5352                        width -= layout.gutter_hitbox.size.width;
 5353                    }
 5354
 5355                    let origin = point(
 5356                        origin_x,
 5357                        layout.hitbox.origin.y
 5358                            + (highlight_row_start.as_f32() - scroll_top)
 5359                                * layout.position_map.line_height,
 5360                    );
 5361                    let size = size(
 5362                        width,
 5363                        layout.position_map.line_height
 5364                            * highlight_row_end.next_row().minus(highlight_row_start) as f32,
 5365                    );
 5366                    let mut quad = fill(Bounds { origin, size }, highlight.background);
 5367                    if let Some(border_color) = highlight.border {
 5368                        quad.border_color = border_color;
 5369                        quad.border_widths = edges
 5370                    }
 5371                    window.paint_quad(quad);
 5372                };
 5373
 5374                let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
 5375                    None;
 5376                for (&new_row, &new_background) in &layout.highlighted_rows {
 5377                    match &mut current_paint {
 5378                        &mut Some((current_background, ref mut current_range, mut edges)) => {
 5379                            let new_range_started = current_background != new_background
 5380                                || current_range.end.next_row() != new_row;
 5381                            if new_range_started {
 5382                                if current_range.end.next_row() == new_row {
 5383                                    edges.bottom = px(0.);
 5384                                };
 5385                                paint_highlight(
 5386                                    current_range.start,
 5387                                    current_range.end,
 5388                                    current_background,
 5389                                    edges,
 5390                                );
 5391                                let edges = Edges {
 5392                                    top: if current_range.end.next_row() != new_row {
 5393                                        px(1.)
 5394                                    } else {
 5395                                        px(0.)
 5396                                    },
 5397                                    bottom: px(1.),
 5398                                    ..Default::default()
 5399                                };
 5400                                current_paint = Some((new_background, new_row..new_row, edges));
 5401                                continue;
 5402                            } else {
 5403                                current_range.end = current_range.end.next_row();
 5404                            }
 5405                        }
 5406                        None => {
 5407                            let edges = Edges {
 5408                                top: px(1.),
 5409                                bottom: px(1.),
 5410                                ..Default::default()
 5411                            };
 5412                            current_paint = Some((new_background, new_row..new_row, edges))
 5413                        }
 5414                    };
 5415                }
 5416                if let Some((color, range, edges)) = current_paint {
 5417                    paint_highlight(range.start, range.end, color, edges);
 5418                }
 5419
 5420                for (guide_x, active) in layout.wrap_guides.iter() {
 5421                    let color = if *active {
 5422                        cx.theme().colors().editor_active_wrap_guide
 5423                    } else {
 5424                        cx.theme().colors().editor_wrap_guide
 5425                    };
 5426                    window.paint_quad(fill(
 5427                        Bounds {
 5428                            origin: point(*guide_x, layout.position_map.text_hitbox.origin.y),
 5429                            size: size(px(1.), layout.position_map.text_hitbox.size.height),
 5430                        },
 5431                        color,
 5432                    ));
 5433                }
 5434            }
 5435        })
 5436    }
 5437
 5438    fn paint_indent_guides(
 5439        &mut self,
 5440        layout: &mut EditorLayout,
 5441        window: &mut Window,
 5442        cx: &mut App,
 5443    ) {
 5444        let Some(indent_guides) = &layout.indent_guides else {
 5445            return;
 5446        };
 5447
 5448        let faded_color = |color: Hsla, alpha: f32| {
 5449            let mut faded = color;
 5450            faded.a = alpha;
 5451            faded
 5452        };
 5453
 5454        for indent_guide in indent_guides {
 5455            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
 5456            let settings = indent_guide.settings;
 5457
 5458            // TODO fixed for now, expose them through themes later
 5459            const INDENT_AWARE_ALPHA: f32 = 0.2;
 5460            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
 5461            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
 5462            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
 5463
 5464            let line_color = match (settings.coloring, indent_guide.active) {
 5465                (IndentGuideColoring::Disabled, _) => None,
 5466                (IndentGuideColoring::Fixed, false) => {
 5467                    Some(cx.theme().colors().editor_indent_guide)
 5468                }
 5469                (IndentGuideColoring::Fixed, true) => {
 5470                    Some(cx.theme().colors().editor_indent_guide_active)
 5471                }
 5472                (IndentGuideColoring::IndentAware, false) => {
 5473                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
 5474                }
 5475                (IndentGuideColoring::IndentAware, true) => {
 5476                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
 5477                }
 5478            };
 5479
 5480            let background_color = match (settings.background_coloring, indent_guide.active) {
 5481                (IndentGuideBackgroundColoring::Disabled, _) => None,
 5482                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
 5483                    indent_accent_colors,
 5484                    INDENT_AWARE_BACKGROUND_ALPHA,
 5485                )),
 5486                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
 5487                    indent_accent_colors,
 5488                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
 5489                )),
 5490            };
 5491
 5492            let requested_line_width = if indent_guide.active {
 5493                settings.active_line_width
 5494            } else {
 5495                settings.line_width
 5496            }
 5497            .clamp(1, 10);
 5498            let mut line_indicator_width = 0.;
 5499            if let Some(color) = line_color {
 5500                window.paint_quad(fill(
 5501                    Bounds {
 5502                        origin: indent_guide.origin,
 5503                        size: size(px(requested_line_width as f32), indent_guide.length),
 5504                    },
 5505                    color,
 5506                ));
 5507                line_indicator_width = requested_line_width as f32;
 5508            }
 5509
 5510            if let Some(color) = background_color {
 5511                let width = indent_guide.single_indent_width - px(line_indicator_width);
 5512                window.paint_quad(fill(
 5513                    Bounds {
 5514                        origin: point(
 5515                            indent_guide.origin.x + px(line_indicator_width),
 5516                            indent_guide.origin.y,
 5517                        ),
 5518                        size: size(width, indent_guide.length),
 5519                    },
 5520                    color,
 5521                ));
 5522            }
 5523        }
 5524    }
 5525
 5526    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 5527        let is_singleton = self.editor.read(cx).is_singleton(cx);
 5528
 5529        let line_height = layout.position_map.line_height;
 5530        window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
 5531
 5532        for LineNumberLayout {
 5533            shaped_line,
 5534            hitbox,
 5535        } in layout.line_numbers.values()
 5536        {
 5537            let Some(hitbox) = hitbox else {
 5538                continue;
 5539            };
 5540
 5541            let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
 5542                let color = cx.theme().colors().editor_hover_line_number;
 5543
 5544                let line = self.shape_line_number(shaped_line.text.clone(), color, window);
 5545                line.paint(hitbox.origin, line_height, window, cx).log_err()
 5546            } else {
 5547                shaped_line
 5548                    .paint(hitbox.origin, line_height, window, cx)
 5549                    .log_err()
 5550            }) else {
 5551                continue;
 5552            };
 5553
 5554            // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
 5555            // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
 5556            if is_singleton {
 5557                window.set_cursor_style(CursorStyle::IBeam, hitbox);
 5558            } else {
 5559                window.set_cursor_style(CursorStyle::PointingHand, hitbox);
 5560            }
 5561        }
 5562    }
 5563
 5564    fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 5565        if layout.display_hunks.is_empty() {
 5566            return;
 5567        }
 5568
 5569        let line_height = layout.position_map.line_height;
 5570        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 5571            for (hunk, hitbox) in &layout.display_hunks {
 5572                let hunk_to_paint = match hunk {
 5573                    DisplayDiffHunk::Folded { .. } => {
 5574                        let hunk_bounds = Self::diff_hunk_bounds(
 5575                            &layout.position_map.snapshot,
 5576                            line_height,
 5577                            layout.gutter_hitbox.bounds,
 5578                            hunk,
 5579                        );
 5580                        Some((
 5581                            hunk_bounds,
 5582                            cx.theme().colors().version_control_modified,
 5583                            Corners::all(px(0.)),
 5584                            DiffHunkStatus::modified_none(),
 5585                        ))
 5586                    }
 5587                    DisplayDiffHunk::Unfolded {
 5588                        status,
 5589                        display_row_range,
 5590                        ..
 5591                    } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
 5592                        DiffHunkStatusKind::Added => (
 5593                            hunk_hitbox.bounds,
 5594                            cx.theme().colors().version_control_added,
 5595                            Corners::all(px(0.)),
 5596                            *status,
 5597                        ),
 5598                        DiffHunkStatusKind::Modified => (
 5599                            hunk_hitbox.bounds,
 5600                            cx.theme().colors().version_control_modified,
 5601                            Corners::all(px(0.)),
 5602                            *status,
 5603                        ),
 5604                        DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
 5605                            hunk_hitbox.bounds,
 5606                            cx.theme().colors().version_control_deleted,
 5607                            Corners::all(px(0.)),
 5608                            *status,
 5609                        ),
 5610                        DiffHunkStatusKind::Deleted => (
 5611                            Bounds::new(
 5612                                point(
 5613                                    hunk_hitbox.origin.x - hunk_hitbox.size.width,
 5614                                    hunk_hitbox.origin.y,
 5615                                ),
 5616                                size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
 5617                            ),
 5618                            cx.theme().colors().version_control_deleted,
 5619                            Corners::all(1. * line_height),
 5620                            *status,
 5621                        ),
 5622                    }),
 5623                };
 5624
 5625                if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
 5626                    // Flatten the background color with the editor color to prevent
 5627                    // elements below transparent hunks from showing through
 5628                    let flattened_background_color = cx
 5629                        .theme()
 5630                        .colors()
 5631                        .editor_background
 5632                        .blend(background_color);
 5633
 5634                    if !Self::diff_hunk_hollow(status, cx) {
 5635                        window.paint_quad(quad(
 5636                            hunk_bounds,
 5637                            corner_radii,
 5638                            flattened_background_color,
 5639                            Edges::default(),
 5640                            transparent_black(),
 5641                            BorderStyle::default(),
 5642                        ));
 5643                    } else {
 5644                        let flattened_unstaged_background_color = cx
 5645                            .theme()
 5646                            .colors()
 5647                            .editor_background
 5648                            .blend(background_color.opacity(0.3));
 5649
 5650                        window.paint_quad(quad(
 5651                            hunk_bounds,
 5652                            corner_radii,
 5653                            flattened_unstaged_background_color,
 5654                            Edges::all(Pixels(1.0)),
 5655                            flattened_background_color,
 5656                            BorderStyle::Solid,
 5657                        ));
 5658                    }
 5659                }
 5660            }
 5661        });
 5662    }
 5663
 5664    fn gutter_strip_width(line_height: Pixels) -> Pixels {
 5665        (0.275 * line_height).floor()
 5666    }
 5667
 5668    fn diff_hunk_bounds(
 5669        snapshot: &EditorSnapshot,
 5670        line_height: Pixels,
 5671        gutter_bounds: Bounds<Pixels>,
 5672        hunk: &DisplayDiffHunk,
 5673    ) -> Bounds<Pixels> {
 5674        let scroll_position = snapshot.scroll_position();
 5675        let scroll_top = scroll_position.y * line_height;
 5676        let gutter_strip_width = Self::gutter_strip_width(line_height);
 5677
 5678        match hunk {
 5679            DisplayDiffHunk::Folded { display_row, .. } => {
 5680                let start_y = display_row.as_f32() * line_height - scroll_top;
 5681                let end_y = start_y + line_height;
 5682                let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 5683                let highlight_size = size(gutter_strip_width, end_y - start_y);
 5684                Bounds::new(highlight_origin, highlight_size)
 5685            }
 5686            DisplayDiffHunk::Unfolded {
 5687                display_row_range,
 5688                status,
 5689                ..
 5690            } => {
 5691                if status.is_deleted() && display_row_range.is_empty() {
 5692                    let row = display_row_range.start;
 5693
 5694                    let offset = line_height / 2.;
 5695                    let start_y = row.as_f32() * line_height - offset - scroll_top;
 5696                    let end_y = start_y + line_height;
 5697
 5698                    let width = (0.35 * line_height).floor();
 5699                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 5700                    let highlight_size = size(width, end_y - start_y);
 5701                    Bounds::new(highlight_origin, highlight_size)
 5702                } else {
 5703                    let start_row = display_row_range.start;
 5704                    let end_row = display_row_range.end;
 5705                    // If we're in a multibuffer, row range span might include an
 5706                    // excerpt header, so if we were to draw the marker straight away,
 5707                    // the hunk might include the rows of that header.
 5708                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
 5709                    // Instead, we simply check whether the range we're dealing with includes
 5710                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
 5711                    let end_row_in_current_excerpt = snapshot
 5712                        .blocks_in_range(start_row..end_row)
 5713                        .find_map(|(start_row, block)| {
 5714                            if matches!(block, Block::ExcerptBoundary { .. }) {
 5715                                Some(start_row)
 5716                            } else {
 5717                                None
 5718                            }
 5719                        })
 5720                        .unwrap_or(end_row);
 5721
 5722                    let start_y = start_row.as_f32() * line_height - scroll_top;
 5723                    let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
 5724
 5725                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 5726                    let highlight_size = size(gutter_strip_width, end_y - start_y);
 5727                    Bounds::new(highlight_origin, highlight_size)
 5728                }
 5729            }
 5730        }
 5731    }
 5732
 5733    fn paint_gutter_indicators(
 5734        &self,
 5735        layout: &mut EditorLayout,
 5736        window: &mut Window,
 5737        cx: &mut App,
 5738    ) {
 5739        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 5740            window.with_element_namespace("crease_toggles", |window| {
 5741                for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
 5742                    crease_toggle.paint(window, cx);
 5743                }
 5744            });
 5745
 5746            window.with_element_namespace("expand_toggles", |window| {
 5747                for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
 5748                    expand_toggle.paint(window, cx);
 5749                }
 5750            });
 5751
 5752            for breakpoint in layout.breakpoints.iter_mut() {
 5753                breakpoint.paint(window, cx);
 5754            }
 5755
 5756            for test_indicator in layout.test_indicators.iter_mut() {
 5757                test_indicator.paint(window, cx);
 5758            }
 5759        });
 5760    }
 5761
 5762    fn paint_gutter_highlights(
 5763        &self,
 5764        layout: &mut EditorLayout,
 5765        window: &mut Window,
 5766        cx: &mut App,
 5767    ) {
 5768        for (_, hunk_hitbox) in &layout.display_hunks {
 5769            if let Some(hunk_hitbox) = hunk_hitbox
 5770                && !self
 5771                    .editor
 5772                    .read(cx)
 5773                    .buffer()
 5774                    .read(cx)
 5775                    .all_diff_hunks_expanded()
 5776            {
 5777                window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
 5778            }
 5779        }
 5780
 5781        let show_git_gutter = layout
 5782            .position_map
 5783            .snapshot
 5784            .show_git_diff_gutter
 5785            .unwrap_or_else(|| {
 5786                matches!(
 5787                    ProjectSettings::get_global(cx).git.git_gutter,
 5788                    Some(GitGutterSetting::TrackedFiles)
 5789                )
 5790            });
 5791        if show_git_gutter {
 5792            Self::paint_gutter_diff_hunks(layout, window, cx)
 5793        }
 5794
 5795        let highlight_width = 0.275 * layout.position_map.line_height;
 5796        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
 5797        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 5798            for (range, color) in &layout.highlighted_gutter_ranges {
 5799                let start_row = if range.start.row() < layout.visible_display_row_range.start {
 5800                    layout.visible_display_row_range.start - DisplayRow(1)
 5801                } else {
 5802                    range.start.row()
 5803                };
 5804                let end_row = if range.end.row() > layout.visible_display_row_range.end {
 5805                    layout.visible_display_row_range.end + DisplayRow(1)
 5806                } else {
 5807                    range.end.row()
 5808                };
 5809
 5810                let start_y = layout.gutter_hitbox.top()
 5811                    + start_row.0 as f32 * layout.position_map.line_height
 5812                    - layout.position_map.scroll_pixel_position.y;
 5813                let end_y = layout.gutter_hitbox.top()
 5814                    + (end_row.0 + 1) as f32 * layout.position_map.line_height
 5815                    - layout.position_map.scroll_pixel_position.y;
 5816                let bounds = Bounds::from_corners(
 5817                    point(layout.gutter_hitbox.left(), start_y),
 5818                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
 5819                );
 5820                window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
 5821            }
 5822        });
 5823    }
 5824
 5825    fn paint_blamed_display_rows(
 5826        &self,
 5827        layout: &mut EditorLayout,
 5828        window: &mut Window,
 5829        cx: &mut App,
 5830    ) {
 5831        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
 5832            return;
 5833        };
 5834
 5835        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 5836            for mut blame_element in blamed_display_rows.into_iter() {
 5837                blame_element.paint(window, cx);
 5838            }
 5839        })
 5840    }
 5841
 5842    fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 5843        window.with_content_mask(
 5844            Some(ContentMask {
 5845                bounds: layout.position_map.text_hitbox.bounds,
 5846            }),
 5847            |window| {
 5848                let editor = self.editor.read(cx);
 5849                if editor.mouse_cursor_hidden {
 5850                    window.set_window_cursor_style(CursorStyle::None);
 5851                } else if let SelectionDragState::ReadyToDrag {
 5852                    mouse_down_time, ..
 5853                } = &editor.selection_drag_state
 5854                {
 5855                    let drag_and_drop_delay = Duration::from_millis(
 5856                        EditorSettings::get_global(cx).drag_and_drop_selection.delay,
 5857                    );
 5858                    if mouse_down_time.elapsed() >= drag_and_drop_delay {
 5859                        window.set_cursor_style(
 5860                            CursorStyle::DragCopy,
 5861                            &layout.position_map.text_hitbox,
 5862                        );
 5863                    }
 5864                } else if matches!(
 5865                    editor.selection_drag_state,
 5866                    SelectionDragState::Dragging { .. }
 5867                ) {
 5868                    window
 5869                        .set_cursor_style(CursorStyle::DragCopy, &layout.position_map.text_hitbox);
 5870                } else if editor
 5871                    .hovered_link_state
 5872                    .as_ref()
 5873                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
 5874                {
 5875                    window.set_cursor_style(
 5876                        CursorStyle::PointingHand,
 5877                        &layout.position_map.text_hitbox,
 5878                    );
 5879                } else {
 5880                    window.set_cursor_style(CursorStyle::IBeam, &layout.position_map.text_hitbox);
 5881                };
 5882
 5883                self.paint_lines_background(layout, window, cx);
 5884                let invisible_display_ranges = self.paint_highlights(layout, window);
 5885                self.paint_document_colors(layout, window);
 5886                self.paint_lines(&invisible_display_ranges, layout, window, cx);
 5887                self.paint_redactions(layout, window);
 5888                self.paint_cursors(layout, window, cx);
 5889                self.paint_inline_diagnostics(layout, window, cx);
 5890                self.paint_inline_blame(layout, window, cx);
 5891                self.paint_inline_code_actions(layout, window, cx);
 5892                self.paint_diff_hunk_controls(layout, window, cx);
 5893                window.with_element_namespace("crease_trailers", |window| {
 5894                    for trailer in layout.crease_trailers.iter_mut().flatten() {
 5895                        trailer.element.paint(window, cx);
 5896                    }
 5897                });
 5898            },
 5899        )
 5900    }
 5901
 5902    fn paint_highlights(
 5903        &mut self,
 5904        layout: &mut EditorLayout,
 5905        window: &mut Window,
 5906    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
 5907        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 5908            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
 5909            let line_end_overshoot = 0.15 * layout.position_map.line_height;
 5910            for (range, color) in &layout.highlighted_ranges {
 5911                self.paint_highlighted_range(
 5912                    range.clone(),
 5913                    true,
 5914                    *color,
 5915                    Pixels::ZERO,
 5916                    line_end_overshoot,
 5917                    layout,
 5918                    window,
 5919                );
 5920            }
 5921
 5922            let corner_radius = 0.15 * layout.position_map.line_height;
 5923
 5924            for (player_color, selections) in &layout.selections {
 5925                for selection in selections.iter() {
 5926                    self.paint_highlighted_range(
 5927                        selection.range.clone(),
 5928                        true,
 5929                        player_color.selection,
 5930                        corner_radius,
 5931                        corner_radius * 2.,
 5932                        layout,
 5933                        window,
 5934                    );
 5935
 5936                    if selection.is_local && !selection.range.is_empty() {
 5937                        invisible_display_ranges.push(selection.range.clone());
 5938                    }
 5939                }
 5940            }
 5941            invisible_display_ranges
 5942        })
 5943    }
 5944
 5945    fn paint_lines(
 5946        &mut self,
 5947        invisible_display_ranges: &[Range<DisplayPoint>],
 5948        layout: &mut EditorLayout,
 5949        window: &mut Window,
 5950        cx: &mut App,
 5951    ) {
 5952        let whitespace_setting = self
 5953            .editor
 5954            .read(cx)
 5955            .buffer
 5956            .read(cx)
 5957            .language_settings(cx)
 5958            .show_whitespaces;
 5959
 5960        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
 5961            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
 5962            line_with_invisibles.draw(
 5963                layout,
 5964                row,
 5965                layout.content_origin,
 5966                whitespace_setting,
 5967                invisible_display_ranges,
 5968                window,
 5969                cx,
 5970            )
 5971        }
 5972
 5973        for line_element in &mut layout.line_elements {
 5974            line_element.paint(window, cx);
 5975        }
 5976    }
 5977
 5978    fn paint_lines_background(
 5979        &mut self,
 5980        layout: &mut EditorLayout,
 5981        window: &mut Window,
 5982        cx: &mut App,
 5983    ) {
 5984        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
 5985            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
 5986            line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
 5987        }
 5988    }
 5989
 5990    fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
 5991        if layout.redacted_ranges.is_empty() {
 5992            return;
 5993        }
 5994
 5995        let line_end_overshoot = layout.line_end_overshoot();
 5996
 5997        // A softer than perfect black
 5998        let redaction_color = gpui::rgb(0x0e1111);
 5999
 6000        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6001            for range in layout.redacted_ranges.iter() {
 6002                self.paint_highlighted_range(
 6003                    range.clone(),
 6004                    true,
 6005                    redaction_color.into(),
 6006                    Pixels::ZERO,
 6007                    line_end_overshoot,
 6008                    layout,
 6009                    window,
 6010                );
 6011            }
 6012        });
 6013    }
 6014
 6015    fn paint_document_colors(&self, layout: &mut EditorLayout, window: &mut Window) {
 6016        let Some((colors_render_mode, image_colors)) = &layout.document_colors else {
 6017            return;
 6018        };
 6019        if image_colors.is_empty()
 6020            || colors_render_mode == &DocumentColorsRenderMode::None
 6021            || colors_render_mode == &DocumentColorsRenderMode::Inlay
 6022        {
 6023            return;
 6024        }
 6025
 6026        let line_end_overshoot = layout.line_end_overshoot();
 6027
 6028        for (range, color) in image_colors {
 6029            match colors_render_mode {
 6030                DocumentColorsRenderMode::Inlay | DocumentColorsRenderMode::None => return,
 6031                DocumentColorsRenderMode::Background => {
 6032                    self.paint_highlighted_range(
 6033                        range.clone(),
 6034                        true,
 6035                        *color,
 6036                        Pixels::ZERO,
 6037                        line_end_overshoot,
 6038                        layout,
 6039                        window,
 6040                    );
 6041                }
 6042                DocumentColorsRenderMode::Border => {
 6043                    self.paint_highlighted_range(
 6044                        range.clone(),
 6045                        false,
 6046                        *color,
 6047                        Pixels::ZERO,
 6048                        line_end_overshoot,
 6049                        layout,
 6050                        window,
 6051                    );
 6052                }
 6053            }
 6054        }
 6055    }
 6056
 6057    fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6058        for cursor in &mut layout.visible_cursors {
 6059            cursor.paint(layout.content_origin, window, cx);
 6060        }
 6061    }
 6062
 6063    fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6064        let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
 6065            return;
 6066        };
 6067        let any_scrollbar_dragged = self.editor.read(cx).scroll_manager.any_scrollbar_dragged();
 6068
 6069        for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
 6070            let hitbox = &scrollbar_layout.hitbox;
 6071            if scrollbars_layout.visible {
 6072                let scrollbar_edges = match axis {
 6073                    ScrollbarAxis::Horizontal => Edges {
 6074                        top: Pixels::ZERO,
 6075                        right: Pixels::ZERO,
 6076                        bottom: Pixels::ZERO,
 6077                        left: Pixels::ZERO,
 6078                    },
 6079                    ScrollbarAxis::Vertical => Edges {
 6080                        top: Pixels::ZERO,
 6081                        right: Pixels::ZERO,
 6082                        bottom: Pixels::ZERO,
 6083                        left: ScrollbarLayout::BORDER_WIDTH,
 6084                    },
 6085                };
 6086
 6087                window.paint_layer(hitbox.bounds, |window| {
 6088                    window.paint_quad(quad(
 6089                        hitbox.bounds,
 6090                        Corners::default(),
 6091                        cx.theme().colors().scrollbar_track_background,
 6092                        scrollbar_edges,
 6093                        cx.theme().colors().scrollbar_track_border,
 6094                        BorderStyle::Solid,
 6095                    ));
 6096
 6097                    if axis == ScrollbarAxis::Vertical {
 6098                        let fast_markers =
 6099                            self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
 6100                        // Refresh slow scrollbar markers in the background. Below, we
 6101                        // paint whatever markers have already been computed.
 6102                        self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, window, cx);
 6103
 6104                        let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
 6105                        for marker in markers.iter().chain(&fast_markers) {
 6106                            let mut marker = marker.clone();
 6107                            marker.bounds.origin += hitbox.origin;
 6108                            window.paint_quad(marker);
 6109                        }
 6110                    }
 6111
 6112                    if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
 6113                        let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
 6114                            ScrollbarThumbState::Dragging => {
 6115                                cx.theme().colors().scrollbar_thumb_active_background
 6116                            }
 6117                            ScrollbarThumbState::Hovered => {
 6118                                cx.theme().colors().scrollbar_thumb_hover_background
 6119                            }
 6120                            ScrollbarThumbState::Idle => {
 6121                                cx.theme().colors().scrollbar_thumb_background
 6122                            }
 6123                        };
 6124                        window.paint_quad(quad(
 6125                            thumb_bounds,
 6126                            Corners::default(),
 6127                            scrollbar_thumb_color,
 6128                            scrollbar_edges,
 6129                            cx.theme().colors().scrollbar_thumb_border,
 6130                            BorderStyle::Solid,
 6131                        ));
 6132
 6133                        if any_scrollbar_dragged {
 6134                            window.set_window_cursor_style(CursorStyle::Arrow);
 6135                        } else {
 6136                            window.set_cursor_style(CursorStyle::Arrow, hitbox);
 6137                        }
 6138                    }
 6139                })
 6140            }
 6141        }
 6142
 6143        window.on_mouse_event({
 6144            let editor = self.editor.clone();
 6145            let scrollbars_layout = scrollbars_layout.clone();
 6146
 6147            let mut mouse_position = window.mouse_position();
 6148            move |event: &MouseMoveEvent, phase, window, cx| {
 6149                if phase == DispatchPhase::Capture {
 6150                    return;
 6151                }
 6152
 6153                editor.update(cx, |editor, cx| {
 6154                    if let Some((scrollbar_layout, axis)) = event
 6155                        .pressed_button
 6156                        .filter(|button| *button == MouseButton::Left)
 6157                        .and(editor.scroll_manager.dragging_scrollbar_axis())
 6158                        .and_then(|axis| {
 6159                            scrollbars_layout
 6160                                .iter_scrollbars()
 6161                                .find(|(_, a)| *a == axis)
 6162                        })
 6163                    {
 6164                        let ScrollbarLayout {
 6165                            hitbox,
 6166                            text_unit_size,
 6167                            ..
 6168                        } = scrollbar_layout;
 6169
 6170                        let old_position = mouse_position.along(axis);
 6171                        let new_position = event.position.along(axis);
 6172                        if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
 6173                            .contains(&old_position)
 6174                        {
 6175                            let position = editor.scroll_position(cx).apply_along(axis, |p| {
 6176                                (p + (new_position - old_position) / *text_unit_size).max(0.)
 6177                            });
 6178                            editor.set_scroll_position(position, window, cx);
 6179                        }
 6180
 6181                        editor.scroll_manager.show_scrollbars(window, cx);
 6182                        cx.stop_propagation();
 6183                    } else if let Some((layout, axis)) = scrollbars_layout
 6184                        .get_hovered_axis(window)
 6185                        .filter(|_| !event.dragging())
 6186                    {
 6187                        if layout.thumb_hovered(&event.position) {
 6188                            editor
 6189                                .scroll_manager
 6190                                .set_hovered_scroll_thumb_axis(axis, cx);
 6191                        } else {
 6192                            editor.scroll_manager.reset_scrollbar_state(cx);
 6193                        }
 6194
 6195                        editor.scroll_manager.show_scrollbars(window, cx);
 6196                    } else {
 6197                        editor.scroll_manager.reset_scrollbar_state(cx);
 6198                    }
 6199
 6200                    mouse_position = event.position;
 6201                })
 6202            }
 6203        });
 6204
 6205        if any_scrollbar_dragged {
 6206            window.on_mouse_event({
 6207                let editor = self.editor.clone();
 6208                move |_: &MouseUpEvent, phase, window, cx| {
 6209                    if phase == DispatchPhase::Capture {
 6210                        return;
 6211                    }
 6212
 6213                    editor.update(cx, |editor, cx| {
 6214                        if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
 6215                            editor
 6216                                .scroll_manager
 6217                                .set_hovered_scroll_thumb_axis(axis, cx);
 6218                        } else {
 6219                            editor.scroll_manager.reset_scrollbar_state(cx);
 6220                        }
 6221                        cx.stop_propagation();
 6222                    });
 6223                }
 6224            });
 6225        } else {
 6226            window.on_mouse_event({
 6227                let editor = self.editor.clone();
 6228
 6229                move |event: &MouseDownEvent, phase, window, cx| {
 6230                    if phase == DispatchPhase::Capture {
 6231                        return;
 6232                    }
 6233                    let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
 6234                    else {
 6235                        return;
 6236                    };
 6237
 6238                    let ScrollbarLayout {
 6239                        hitbox,
 6240                        visible_range,
 6241                        text_unit_size,
 6242                        thumb_bounds,
 6243                        ..
 6244                    } = scrollbar_layout;
 6245
 6246                    let Some(thumb_bounds) = thumb_bounds else {
 6247                        return;
 6248                    };
 6249
 6250                    editor.update(cx, |editor, cx| {
 6251                        editor
 6252                            .scroll_manager
 6253                            .set_dragged_scroll_thumb_axis(axis, cx);
 6254
 6255                        let event_position = event.position.along(axis);
 6256
 6257                        if event_position < thumb_bounds.origin.along(axis)
 6258                            || thumb_bounds.bottom_right().along(axis) < event_position
 6259                        {
 6260                            let center_position = ((event_position - hitbox.origin.along(axis))
 6261                                / *text_unit_size)
 6262                                .round() as u32;
 6263                            let start_position = center_position.saturating_sub(
 6264                                (visible_range.end - visible_range.start) as u32 / 2,
 6265                            );
 6266
 6267                            let position = editor
 6268                                .scroll_position(cx)
 6269                                .apply_along(axis, |_| start_position as f32);
 6270
 6271                            editor.set_scroll_position(position, window, cx);
 6272                        } else {
 6273                            editor.scroll_manager.show_scrollbars(window, cx);
 6274                        }
 6275
 6276                        cx.stop_propagation();
 6277                    });
 6278                }
 6279            });
 6280        }
 6281    }
 6282
 6283    fn collect_fast_scrollbar_markers(
 6284        &self,
 6285        layout: &EditorLayout,
 6286        scrollbar_layout: &ScrollbarLayout,
 6287        cx: &mut App,
 6288    ) -> Vec<PaintQuad> {
 6289        const LIMIT: usize = 100;
 6290        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
 6291            return vec![];
 6292        }
 6293        let cursor_ranges = layout
 6294            .cursors
 6295            .iter()
 6296            .map(|(point, color)| ColoredRange {
 6297                start: point.row(),
 6298                end: point.row(),
 6299                color: *color,
 6300            })
 6301            .collect_vec();
 6302        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
 6303    }
 6304
 6305    fn refresh_slow_scrollbar_markers(
 6306        &self,
 6307        layout: &EditorLayout,
 6308        scrollbar_layout: &ScrollbarLayout,
 6309        window: &mut Window,
 6310        cx: &mut App,
 6311    ) {
 6312        self.editor.update(cx, |editor, cx| {
 6313            if !editor.is_singleton(cx)
 6314                || !editor
 6315                    .scrollbar_marker_state
 6316                    .should_refresh(scrollbar_layout.hitbox.size)
 6317            {
 6318                return;
 6319            }
 6320
 6321            let scrollbar_layout = scrollbar_layout.clone();
 6322            let background_highlights = editor.background_highlights.clone();
 6323            let snapshot = layout.position_map.snapshot.clone();
 6324            let theme = cx.theme().clone();
 6325            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
 6326
 6327            editor.scrollbar_marker_state.dirty = false;
 6328            editor.scrollbar_marker_state.pending_refresh =
 6329                Some(cx.spawn_in(window, async move |editor, cx| {
 6330                    let scrollbar_size = scrollbar_layout.hitbox.size;
 6331                    let scrollbar_markers = cx
 6332                        .background_spawn(async move {
 6333                            let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
 6334                            let mut marker_quads = Vec::new();
 6335                            if scrollbar_settings.git_diff {
 6336                                let marker_row_ranges =
 6337                                    snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
 6338                                        let start_display_row =
 6339                                            MultiBufferPoint::new(hunk.row_range.start.0, 0)
 6340                                                .to_display_point(&snapshot.display_snapshot)
 6341                                                .row();
 6342                                        let mut end_display_row =
 6343                                            MultiBufferPoint::new(hunk.row_range.end.0, 0)
 6344                                                .to_display_point(&snapshot.display_snapshot)
 6345                                                .row();
 6346                                        if end_display_row != start_display_row {
 6347                                            end_display_row.0 -= 1;
 6348                                        }
 6349                                        let color = match &hunk.status().kind {
 6350                                            DiffHunkStatusKind::Added => {
 6351                                                theme.colors().version_control_added
 6352                                            }
 6353                                            DiffHunkStatusKind::Modified => {
 6354                                                theme.colors().version_control_modified
 6355                                            }
 6356                                            DiffHunkStatusKind::Deleted => {
 6357                                                theme.colors().version_control_deleted
 6358                                            }
 6359                                        };
 6360                                        ColoredRange {
 6361                                            start: start_display_row,
 6362                                            end: end_display_row,
 6363                                            color,
 6364                                        }
 6365                                    });
 6366
 6367                                marker_quads.extend(
 6368                                    scrollbar_layout
 6369                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
 6370                                );
 6371                            }
 6372
 6373                            for (background_highlight_id, (_, background_ranges)) in
 6374                                background_highlights.iter()
 6375                            {
 6376                                let is_search_highlights = *background_highlight_id
 6377                                    == HighlightKey::Type(TypeId::of::<BufferSearchHighlights>());
 6378                                let is_text_highlights = *background_highlight_id
 6379                                    == HighlightKey::Type(TypeId::of::<SelectedTextHighlight>());
 6380                                let is_symbol_occurrences = *background_highlight_id
 6381                                    == HighlightKey::Type(TypeId::of::<DocumentHighlightRead>())
 6382                                    || *background_highlight_id
 6383                                        == HighlightKey::Type(
 6384                                            TypeId::of::<DocumentHighlightWrite>(),
 6385                                        );
 6386                                if (is_search_highlights && scrollbar_settings.search_results)
 6387                                    || (is_text_highlights && scrollbar_settings.selected_text)
 6388                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
 6389                                {
 6390                                    let mut color = theme.status().info;
 6391                                    if is_symbol_occurrences {
 6392                                        color.fade_out(0.5);
 6393                                    }
 6394                                    let marker_row_ranges = background_ranges.iter().map(|range| {
 6395                                        let display_start = range
 6396                                            .start
 6397                                            .to_display_point(&snapshot.display_snapshot);
 6398                                        let display_end =
 6399                                            range.end.to_display_point(&snapshot.display_snapshot);
 6400                                        ColoredRange {
 6401                                            start: display_start.row(),
 6402                                            end: display_end.row(),
 6403                                            color,
 6404                                        }
 6405                                    });
 6406                                    marker_quads.extend(
 6407                                        scrollbar_layout
 6408                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
 6409                                    );
 6410                                }
 6411                            }
 6412
 6413                            if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
 6414                                let diagnostics = snapshot
 6415                                    .buffer_snapshot
 6416                                    .diagnostics_in_range::<Point>(Point::zero()..max_point)
 6417                                    // Don't show diagnostics the user doesn't care about
 6418                                    .filter(|diagnostic| {
 6419                                        match (
 6420                                            scrollbar_settings.diagnostics,
 6421                                            diagnostic.diagnostic.severity,
 6422                                        ) {
 6423                                            (ScrollbarDiagnostics::All, _) => true,
 6424                                            (
 6425                                                ScrollbarDiagnostics::Error,
 6426                                                lsp::DiagnosticSeverity::ERROR,
 6427                                            ) => true,
 6428                                            (
 6429                                                ScrollbarDiagnostics::Warning,
 6430                                                lsp::DiagnosticSeverity::ERROR
 6431                                                | lsp::DiagnosticSeverity::WARNING,
 6432                                            ) => true,
 6433                                            (
 6434                                                ScrollbarDiagnostics::Information,
 6435                                                lsp::DiagnosticSeverity::ERROR
 6436                                                | lsp::DiagnosticSeverity::WARNING
 6437                                                | lsp::DiagnosticSeverity::INFORMATION,
 6438                                            ) => true,
 6439                                            (_, _) => false,
 6440                                        }
 6441                                    })
 6442                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
 6443                                    .sorted_by_key(|diagnostic| {
 6444                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
 6445                                    });
 6446
 6447                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
 6448                                    let start_display = diagnostic
 6449                                        .range
 6450                                        .start
 6451                                        .to_display_point(&snapshot.display_snapshot);
 6452                                    let end_display = diagnostic
 6453                                        .range
 6454                                        .end
 6455                                        .to_display_point(&snapshot.display_snapshot);
 6456                                    let color = match diagnostic.diagnostic.severity {
 6457                                        lsp::DiagnosticSeverity::ERROR => theme.status().error,
 6458                                        lsp::DiagnosticSeverity::WARNING => theme.status().warning,
 6459                                        lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
 6460                                        _ => theme.status().hint,
 6461                                    };
 6462                                    ColoredRange {
 6463                                        start: start_display.row(),
 6464                                        end: end_display.row(),
 6465                                        color,
 6466                                    }
 6467                                });
 6468                                marker_quads.extend(
 6469                                    scrollbar_layout
 6470                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
 6471                                );
 6472                            }
 6473
 6474                            Arc::from(marker_quads)
 6475                        })
 6476                        .await;
 6477
 6478                    editor.update(cx, |editor, cx| {
 6479                        editor.scrollbar_marker_state.markers = scrollbar_markers;
 6480                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
 6481                        editor.scrollbar_marker_state.pending_refresh = None;
 6482                        cx.notify();
 6483                    })?;
 6484
 6485                    Ok(())
 6486                }));
 6487        });
 6488    }
 6489
 6490    fn paint_highlighted_range(
 6491        &self,
 6492        range: Range<DisplayPoint>,
 6493        fill: bool,
 6494        color: Hsla,
 6495        corner_radius: Pixels,
 6496        line_end_overshoot: Pixels,
 6497        layout: &EditorLayout,
 6498        window: &mut Window,
 6499    ) {
 6500        let start_row = layout.visible_display_row_range.start;
 6501        let end_row = layout.visible_display_row_range.end;
 6502        if range.start != range.end {
 6503            let row_range = if range.end.column() == 0 {
 6504                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
 6505            } else {
 6506                cmp::max(range.start.row(), start_row)
 6507                    ..cmp::min(range.end.row().next_row(), end_row)
 6508            };
 6509
 6510            let highlighted_range = HighlightedRange {
 6511                color,
 6512                line_height: layout.position_map.line_height,
 6513                corner_radius,
 6514                start_y: layout.content_origin.y
 6515                    + row_range.start.as_f32() * layout.position_map.line_height
 6516                    - layout.position_map.scroll_pixel_position.y,
 6517                lines: row_range
 6518                    .iter_rows()
 6519                    .map(|row| {
 6520                        let line_layout =
 6521                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
 6522                        HighlightedRangeLine {
 6523                            start_x: if row == range.start.row() {
 6524                                layout.content_origin.x
 6525                                    + line_layout.x_for_index(range.start.column() as usize)
 6526                                    - layout.position_map.scroll_pixel_position.x
 6527                            } else {
 6528                                layout.content_origin.x
 6529                                    - layout.position_map.scroll_pixel_position.x
 6530                            },
 6531                            end_x: if row == range.end.row() {
 6532                                layout.content_origin.x
 6533                                    + line_layout.x_for_index(range.end.column() as usize)
 6534                                    - layout.position_map.scroll_pixel_position.x
 6535                            } else {
 6536                                layout.content_origin.x + line_layout.width + line_end_overshoot
 6537                                    - layout.position_map.scroll_pixel_position.x
 6538                            },
 6539                        }
 6540                    })
 6541                    .collect(),
 6542            };
 6543
 6544            highlighted_range.paint(fill, layout.position_map.text_hitbox.bounds, window);
 6545        }
 6546    }
 6547
 6548    fn paint_inline_diagnostics(
 6549        &mut self,
 6550        layout: &mut EditorLayout,
 6551        window: &mut Window,
 6552        cx: &mut App,
 6553    ) {
 6554        for mut inline_diagnostic in layout.inline_diagnostics.drain() {
 6555            inline_diagnostic.1.paint(window, cx);
 6556        }
 6557    }
 6558
 6559    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6560        if let Some(mut blame_layout) = layout.inline_blame_layout.take() {
 6561            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6562                blame_layout.element.paint(window, cx);
 6563            })
 6564        }
 6565    }
 6566
 6567    fn paint_inline_code_actions(
 6568        &mut self,
 6569        layout: &mut EditorLayout,
 6570        window: &mut Window,
 6571        cx: &mut App,
 6572    ) {
 6573        if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
 6574            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6575                inline_code_actions.paint(window, cx);
 6576            })
 6577        }
 6578    }
 6579
 6580    fn paint_diff_hunk_controls(
 6581        &mut self,
 6582        layout: &mut EditorLayout,
 6583        window: &mut Window,
 6584        cx: &mut App,
 6585    ) {
 6586        for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
 6587            diff_hunk_control.paint(window, cx);
 6588        }
 6589    }
 6590
 6591    fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6592        if let Some(mut layout) = layout.minimap.take() {
 6593            let minimap_hitbox = layout.thumb_layout.hitbox.clone();
 6594            let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
 6595
 6596            window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
 6597                window.with_element_namespace("minimap", |window| {
 6598                    layout.minimap.paint(window, cx);
 6599                    if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
 6600                        let minimap_thumb_color = match layout.thumb_layout.thumb_state {
 6601                            ScrollbarThumbState::Idle => {
 6602                                cx.theme().colors().minimap_thumb_background
 6603                            }
 6604                            ScrollbarThumbState::Hovered => {
 6605                                cx.theme().colors().minimap_thumb_hover_background
 6606                            }
 6607                            ScrollbarThumbState::Dragging => {
 6608                                cx.theme().colors().minimap_thumb_active_background
 6609                            }
 6610                        };
 6611                        let minimap_thumb_border = match layout.thumb_border_style {
 6612                            MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
 6613                            MinimapThumbBorder::LeftOnly => Edges {
 6614                                left: ScrollbarLayout::BORDER_WIDTH,
 6615                                ..Default::default()
 6616                            },
 6617                            MinimapThumbBorder::LeftOpen => Edges {
 6618                                right: ScrollbarLayout::BORDER_WIDTH,
 6619                                top: ScrollbarLayout::BORDER_WIDTH,
 6620                                bottom: ScrollbarLayout::BORDER_WIDTH,
 6621                                ..Default::default()
 6622                            },
 6623                            MinimapThumbBorder::RightOpen => Edges {
 6624                                left: ScrollbarLayout::BORDER_WIDTH,
 6625                                top: ScrollbarLayout::BORDER_WIDTH,
 6626                                bottom: ScrollbarLayout::BORDER_WIDTH,
 6627                                ..Default::default()
 6628                            },
 6629                            MinimapThumbBorder::None => Default::default(),
 6630                        };
 6631
 6632                        window.paint_layer(minimap_hitbox.bounds, |window| {
 6633                            window.paint_quad(quad(
 6634                                thumb_bounds,
 6635                                Corners::default(),
 6636                                minimap_thumb_color,
 6637                                minimap_thumb_border,
 6638                                cx.theme().colors().minimap_thumb_border,
 6639                                BorderStyle::Solid,
 6640                            ));
 6641                        });
 6642                    }
 6643                });
 6644            });
 6645
 6646            if dragging_minimap {
 6647                window.set_window_cursor_style(CursorStyle::Arrow);
 6648            } else {
 6649                window.set_cursor_style(CursorStyle::Arrow, &minimap_hitbox);
 6650            }
 6651
 6652            let minimap_axis = ScrollbarAxis::Vertical;
 6653            let pixels_per_line = (minimap_hitbox.size.height / layout.max_scroll_top)
 6654                .min(layout.minimap_line_height);
 6655
 6656            let mut mouse_position = window.mouse_position();
 6657
 6658            window.on_mouse_event({
 6659                let editor = self.editor.clone();
 6660
 6661                let minimap_hitbox = minimap_hitbox.clone();
 6662
 6663                move |event: &MouseMoveEvent, phase, window, cx| {
 6664                    if phase == DispatchPhase::Capture {
 6665                        return;
 6666                    }
 6667
 6668                    editor.update(cx, |editor, cx| {
 6669                        if event.pressed_button == Some(MouseButton::Left)
 6670                            && editor.scroll_manager.is_dragging_minimap()
 6671                        {
 6672                            let old_position = mouse_position.along(minimap_axis);
 6673                            let new_position = event.position.along(minimap_axis);
 6674                            if (minimap_hitbox.origin.along(minimap_axis)
 6675                                ..minimap_hitbox.bottom_right().along(minimap_axis))
 6676                                .contains(&old_position)
 6677                            {
 6678                                let position =
 6679                                    editor.scroll_position(cx).apply_along(minimap_axis, |p| {
 6680                                        (p + (new_position - old_position) / pixels_per_line)
 6681                                            .max(0.)
 6682                                    });
 6683                                editor.set_scroll_position(position, window, cx);
 6684                            }
 6685                            cx.stop_propagation();
 6686                        } else if minimap_hitbox.is_hovered(window) {
 6687                            editor.scroll_manager.set_is_hovering_minimap_thumb(
 6688                                !event.dragging()
 6689                                    && layout
 6690                                        .thumb_layout
 6691                                        .thumb_bounds
 6692                                        .is_some_and(|bounds| bounds.contains(&event.position)),
 6693                                cx,
 6694                            );
 6695
 6696                            // Stop hover events from propagating to the
 6697                            // underlying editor if the minimap hitbox is hovered
 6698                            if !event.dragging() {
 6699                                cx.stop_propagation();
 6700                            }
 6701                        } else {
 6702                            editor.scroll_manager.hide_minimap_thumb(cx);
 6703                        }
 6704                        mouse_position = event.position;
 6705                    });
 6706                }
 6707            });
 6708
 6709            if dragging_minimap {
 6710                window.on_mouse_event({
 6711                    let editor = self.editor.clone();
 6712                    move |event: &MouseUpEvent, phase, window, cx| {
 6713                        if phase == DispatchPhase::Capture {
 6714                            return;
 6715                        }
 6716
 6717                        editor.update(cx, |editor, cx| {
 6718                            if minimap_hitbox.is_hovered(window) {
 6719                                editor.scroll_manager.set_is_hovering_minimap_thumb(
 6720                                    layout
 6721                                        .thumb_layout
 6722                                        .thumb_bounds
 6723                                        .is_some_and(|bounds| bounds.contains(&event.position)),
 6724                                    cx,
 6725                                );
 6726                            } else {
 6727                                editor.scroll_manager.hide_minimap_thumb(cx);
 6728                            }
 6729                            cx.stop_propagation();
 6730                        });
 6731                    }
 6732                });
 6733            } else {
 6734                window.on_mouse_event({
 6735                    let editor = self.editor.clone();
 6736
 6737                    move |event: &MouseDownEvent, phase, window, cx| {
 6738                        if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
 6739                            return;
 6740                        }
 6741
 6742                        let event_position = event.position;
 6743
 6744                        let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
 6745                            return;
 6746                        };
 6747
 6748                        editor.update(cx, |editor, cx| {
 6749                            if !thumb_bounds.contains(&event_position) {
 6750                                let click_position =
 6751                                    event_position.relative_to(&minimap_hitbox.origin).y;
 6752
 6753                                let top_position = (click_position
 6754                                    - thumb_bounds.size.along(minimap_axis) / 2.0)
 6755                                    .max(Pixels::ZERO);
 6756
 6757                                let scroll_offset = (layout.minimap_scroll_top
 6758                                    + top_position / layout.minimap_line_height)
 6759                                    .min(layout.max_scroll_top);
 6760
 6761                                let scroll_position = editor
 6762                                    .scroll_position(cx)
 6763                                    .apply_along(minimap_axis, |_| scroll_offset);
 6764                                editor.set_scroll_position(scroll_position, window, cx);
 6765                            }
 6766
 6767                            editor.scroll_manager.set_is_dragging_minimap(cx);
 6768                            cx.stop_propagation();
 6769                        });
 6770                    }
 6771                });
 6772            }
 6773        }
 6774    }
 6775
 6776    fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6777        for mut block in layout.blocks.drain(..) {
 6778            if block.overlaps_gutter {
 6779                block.element.paint(window, cx);
 6780            } else {
 6781                let mut bounds = layout.hitbox.bounds;
 6782                bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
 6783                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 6784                    block.element.paint(window, cx);
 6785                })
 6786            }
 6787        }
 6788    }
 6789
 6790    fn paint_edit_prediction_popover(
 6791        &mut self,
 6792        layout: &mut EditorLayout,
 6793        window: &mut Window,
 6794        cx: &mut App,
 6795    ) {
 6796        if let Some(edit_prediction_popover) = layout.edit_prediction_popover.as_mut() {
 6797            edit_prediction_popover.paint(window, cx);
 6798        }
 6799    }
 6800
 6801    fn paint_mouse_context_menu(
 6802        &mut self,
 6803        layout: &mut EditorLayout,
 6804        window: &mut Window,
 6805        cx: &mut App,
 6806    ) {
 6807        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
 6808            mouse_context_menu.paint(window, cx);
 6809        }
 6810    }
 6811
 6812    fn paint_scroll_wheel_listener(
 6813        &mut self,
 6814        layout: &EditorLayout,
 6815        window: &mut Window,
 6816        cx: &mut App,
 6817    ) {
 6818        window.on_mouse_event({
 6819            let position_map = layout.position_map.clone();
 6820            let editor = self.editor.clone();
 6821            let hitbox = layout.hitbox.clone();
 6822            let mut delta = ScrollDelta::default();
 6823
 6824            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
 6825            // accidentally turn off their scrolling.
 6826            let base_scroll_sensitivity =
 6827                EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
 6828
 6829            // Use a minimum fast_scroll_sensitivity for same reason above
 6830            let fast_scroll_sensitivity = EditorSettings::get_global(cx)
 6831                .fast_scroll_sensitivity
 6832                .max(0.01);
 6833
 6834            move |event: &ScrollWheelEvent, phase, window, cx| {
 6835                let scroll_sensitivity = {
 6836                    if event.modifiers.alt {
 6837                        fast_scroll_sensitivity
 6838                    } else {
 6839                        base_scroll_sensitivity
 6840                    }
 6841                };
 6842
 6843                if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
 6844                    delta = delta.coalesce(event.delta);
 6845                    editor.update(cx, |editor, cx| {
 6846                        let position_map: &PositionMap = &position_map;
 6847
 6848                        let line_height = position_map.line_height;
 6849                        let max_glyph_advance = position_map.em_advance;
 6850                        let (delta, axis) = match delta {
 6851                            gpui::ScrollDelta::Pixels(mut pixels) => {
 6852                                //Trackpad
 6853                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
 6854                                (pixels, axis)
 6855                            }
 6856
 6857                            gpui::ScrollDelta::Lines(lines) => {
 6858                                //Not trackpad
 6859                                let pixels =
 6860                                    point(lines.x * max_glyph_advance, lines.y * line_height);
 6861                                (pixels, None)
 6862                            }
 6863                        };
 6864
 6865                        let current_scroll_position = position_map.snapshot.scroll_position();
 6866                        let x = (current_scroll_position.x * max_glyph_advance
 6867                            - (delta.x * scroll_sensitivity))
 6868                            / max_glyph_advance;
 6869                        let y = (current_scroll_position.y * line_height
 6870                            - (delta.y * scroll_sensitivity))
 6871                            / line_height;
 6872                        let mut scroll_position =
 6873                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
 6874                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
 6875                        if forbid_vertical_scroll {
 6876                            scroll_position.y = current_scroll_position.y;
 6877                        }
 6878
 6879                        if scroll_position != current_scroll_position {
 6880                            editor.scroll(scroll_position, axis, window, cx);
 6881                            cx.stop_propagation();
 6882                        } else if y < 0. {
 6883                            // Due to clamping, we may fail to detect cases of overscroll to the top;
 6884                            // We want the scroll manager to get an update in such cases and detect the change of direction
 6885                            // on the next frame.
 6886                            cx.notify();
 6887                        }
 6888                    });
 6889                }
 6890            }
 6891        });
 6892    }
 6893
 6894    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
 6895        if layout.mode.is_minimap() {
 6896            return;
 6897        }
 6898
 6899        self.paint_scroll_wheel_listener(layout, window, cx);
 6900
 6901        window.on_mouse_event({
 6902            let position_map = layout.position_map.clone();
 6903            let editor = self.editor.clone();
 6904            let diff_hunk_range =
 6905                layout
 6906                    .display_hunks
 6907                    .iter()
 6908                    .find_map(|(hunk, hunk_hitbox)| match hunk {
 6909                        DisplayDiffHunk::Folded { .. } => None,
 6910                        DisplayDiffHunk::Unfolded {
 6911                            multi_buffer_range, ..
 6912                        } => {
 6913                            if hunk_hitbox
 6914                                .as_ref()
 6915                                .map(|hitbox| hitbox.is_hovered(window))
 6916                                .unwrap_or(false)
 6917                            {
 6918                                Some(multi_buffer_range.clone())
 6919                            } else {
 6920                                None
 6921                            }
 6922                        }
 6923                    });
 6924            let line_numbers = layout.line_numbers.clone();
 6925
 6926            move |event: &MouseDownEvent, phase, window, cx| {
 6927                if phase == DispatchPhase::Bubble {
 6928                    match event.button {
 6929                        MouseButton::Left => editor.update(cx, |editor, cx| {
 6930                            let pending_mouse_down = editor
 6931                                .pending_mouse_down
 6932                                .get_or_insert_with(Default::default)
 6933                                .clone();
 6934
 6935                            *pending_mouse_down.borrow_mut() = Some(event.clone());
 6936
 6937                            Self::mouse_left_down(
 6938                                editor,
 6939                                event,
 6940                                diff_hunk_range.clone(),
 6941                                &position_map,
 6942                                line_numbers.as_ref(),
 6943                                window,
 6944                                cx,
 6945                            );
 6946                        }),
 6947                        MouseButton::Right => editor.update(cx, |editor, cx| {
 6948                            Self::mouse_right_down(editor, event, &position_map, window, cx);
 6949                        }),
 6950                        MouseButton::Middle => editor.update(cx, |editor, cx| {
 6951                            Self::mouse_middle_down(editor, event, &position_map, window, cx);
 6952                        }),
 6953                        _ => {}
 6954                    };
 6955                }
 6956            }
 6957        });
 6958
 6959        window.on_mouse_event({
 6960            let editor = self.editor.clone();
 6961            let position_map = layout.position_map.clone();
 6962
 6963            move |event: &MouseUpEvent, phase, window, cx| {
 6964                if phase == DispatchPhase::Bubble {
 6965                    editor.update(cx, |editor, cx| {
 6966                        Self::mouse_up(editor, event, &position_map, window, cx)
 6967                    });
 6968                }
 6969            }
 6970        });
 6971
 6972        window.on_mouse_event({
 6973            let editor = self.editor.clone();
 6974            let position_map = layout.position_map.clone();
 6975            let mut captured_mouse_down = None;
 6976
 6977            move |event: &MouseUpEvent, phase, window, cx| match phase {
 6978                // Clear the pending mouse down during the capture phase,
 6979                // so that it happens even if another event handler stops
 6980                // propagation.
 6981                DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
 6982                    let pending_mouse_down = editor
 6983                        .pending_mouse_down
 6984                        .get_or_insert_with(Default::default)
 6985                        .clone();
 6986
 6987                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
 6988                    if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
 6989                        captured_mouse_down = pending_mouse_down.take();
 6990                        window.refresh();
 6991                    }
 6992                }),
 6993                // Fire click handlers during the bubble phase.
 6994                DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
 6995                    if let Some(mouse_down) = captured_mouse_down.take() {
 6996                        let event = ClickEvent::Mouse(MouseClickEvent {
 6997                            down: mouse_down,
 6998                            up: event.clone(),
 6999                        });
 7000                        Self::click(editor, &event, &position_map, window, cx);
 7001                    }
 7002                }),
 7003            }
 7004        });
 7005
 7006        window.on_mouse_event({
 7007            let position_map = layout.position_map.clone();
 7008            let editor = self.editor.clone();
 7009
 7010            move |event: &MouseMoveEvent, phase, window, cx| {
 7011                if phase == DispatchPhase::Bubble {
 7012                    editor.update(cx, |editor, cx| {
 7013                        if editor.hover_state.focused(window, cx) {
 7014                            return;
 7015                        }
 7016                        if event.pressed_button == Some(MouseButton::Left)
 7017                            || event.pressed_button == Some(MouseButton::Middle)
 7018                        {
 7019                            Self::mouse_dragged(editor, event, &position_map, window, cx)
 7020                        }
 7021
 7022                        Self::mouse_moved(editor, event, &position_map, window, cx)
 7023                    });
 7024                }
 7025            }
 7026        });
 7027    }
 7028
 7029    fn column_pixels(&self, column: usize, window: &Window) -> Pixels {
 7030        let style = &self.style;
 7031        let font_size = style.text.font_size.to_pixels(window.rem_size());
 7032        let layout = window.text_system().shape_line(
 7033            SharedString::from(" ".repeat(column)),
 7034            font_size,
 7035            &[TextRun {
 7036                len: column,
 7037                font: style.text.font(),
 7038                color: Hsla::default(),
 7039                background_color: None,
 7040                underline: None,
 7041                strikethrough: None,
 7042            }],
 7043            None,
 7044        );
 7045
 7046        layout.width
 7047    }
 7048
 7049    fn max_line_number_width(&self, snapshot: &EditorSnapshot, window: &mut Window) -> Pixels {
 7050        let digit_count = snapshot.widest_line_number().ilog10() + 1;
 7051        self.column_pixels(digit_count as usize, window)
 7052    }
 7053
 7054    fn shape_line_number(
 7055        &self,
 7056        text: SharedString,
 7057        color: Hsla,
 7058        window: &mut Window,
 7059    ) -> ShapedLine {
 7060        let run = TextRun {
 7061            len: text.len(),
 7062            font: self.style.text.font(),
 7063            color,
 7064            background_color: None,
 7065            underline: None,
 7066            strikethrough: None,
 7067        };
 7068        window.text_system().shape_line(
 7069            text,
 7070            self.style.text.font_size.to_pixels(window.rem_size()),
 7071            &[run],
 7072            None,
 7073        )
 7074    }
 7075
 7076    fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
 7077        let unstaged = status.has_secondary_hunk();
 7078        let unstaged_hollow = ProjectSettings::get_global(cx)
 7079            .git
 7080            .hunk_style
 7081            .is_some_and(|style| matches!(style, GitHunkStyleSetting::UnstagedHollow));
 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                            .is_none_or(|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 if candidate_row == start_row {
 9714            candidate_col >= start_col
 9715        } else if candidate_row == end_row {
 9716            candidate_col < end_col
 9717        } else {
 9718            true
 9719        }
 9720    }
 9721}
 9722
 9723impl PositionMap {
 9724    pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
 9725        let text_bounds = self.text_hitbox.bounds;
 9726        let scroll_position = self.snapshot.scroll_position();
 9727        let position = position - text_bounds.origin;
 9728        let y = position.y.max(px(0.)).min(self.size.height);
 9729        let x = position.x + (scroll_position.x * self.em_advance);
 9730        let row = ((y / self.line_height) + scroll_position.y) as u32;
 9731
 9732        let (column, x_overshoot_after_line_end) = if let Some(line) = self
 9733            .line_layouts
 9734            .get(row as usize - scroll_position.y as usize)
 9735        {
 9736            if let Some(ix) = line.index_for_x(x) {
 9737                (ix as u32, px(0.))
 9738            } else {
 9739                (line.len as u32, px(0.).max(x - line.width))
 9740            }
 9741        } else {
 9742            (0, x)
 9743        };
 9744
 9745        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
 9746        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
 9747        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
 9748
 9749        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
 9750        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
 9751        PointForPosition {
 9752            previous_valid,
 9753            next_valid,
 9754            exact_unclipped,
 9755            column_overshoot_after_line_end,
 9756        }
 9757    }
 9758}
 9759
 9760struct BlockLayout {
 9761    id: BlockId,
 9762    x_offset: Pixels,
 9763    row: Option<DisplayRow>,
 9764    element: AnyElement,
 9765    available_space: Size<AvailableSpace>,
 9766    style: BlockStyle,
 9767    overlaps_gutter: bool,
 9768    is_buffer_header: bool,
 9769}
 9770
 9771pub fn layout_line(
 9772    row: DisplayRow,
 9773    snapshot: &EditorSnapshot,
 9774    style: &EditorStyle,
 9775    text_width: Pixels,
 9776    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 9777    window: &mut Window,
 9778    cx: &mut App,
 9779) -> LineWithInvisibles {
 9780    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
 9781    LineWithInvisibles::from_chunks(
 9782        chunks,
 9783        style,
 9784        MAX_LINE_LEN,
 9785        1,
 9786        &snapshot.mode,
 9787        text_width,
 9788        is_row_soft_wrapped,
 9789        window,
 9790        cx,
 9791    )
 9792    .pop()
 9793    .unwrap()
 9794}
 9795
 9796#[derive(Debug)]
 9797pub struct IndentGuideLayout {
 9798    origin: gpui::Point<Pixels>,
 9799    length: Pixels,
 9800    single_indent_width: Pixels,
 9801    depth: u32,
 9802    active: bool,
 9803    settings: IndentGuideSettings,
 9804}
 9805
 9806pub struct CursorLayout {
 9807    origin: gpui::Point<Pixels>,
 9808    block_width: Pixels,
 9809    line_height: Pixels,
 9810    color: Hsla,
 9811    shape: CursorShape,
 9812    block_text: Option<ShapedLine>,
 9813    cursor_name: Option<AnyElement>,
 9814}
 9815
 9816#[derive(Debug)]
 9817pub struct CursorName {
 9818    string: SharedString,
 9819    color: Hsla,
 9820    is_top_row: bool,
 9821}
 9822
 9823impl CursorLayout {
 9824    pub fn new(
 9825        origin: gpui::Point<Pixels>,
 9826        block_width: Pixels,
 9827        line_height: Pixels,
 9828        color: Hsla,
 9829        shape: CursorShape,
 9830        block_text: Option<ShapedLine>,
 9831    ) -> CursorLayout {
 9832        CursorLayout {
 9833            origin,
 9834            block_width,
 9835            line_height,
 9836            color,
 9837            shape,
 9838            block_text,
 9839            cursor_name: None,
 9840        }
 9841    }
 9842
 9843    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
 9844        Bounds {
 9845            origin: self.origin + origin,
 9846            size: size(self.block_width, self.line_height),
 9847        }
 9848    }
 9849
 9850    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
 9851        match self.shape {
 9852            CursorShape::Bar => Bounds {
 9853                origin: self.origin + origin,
 9854                size: size(px(2.0), self.line_height),
 9855            },
 9856            CursorShape::Block | CursorShape::Hollow => Bounds {
 9857                origin: self.origin + origin,
 9858                size: size(self.block_width, self.line_height),
 9859            },
 9860            CursorShape::Underline => Bounds {
 9861                origin: self.origin
 9862                    + origin
 9863                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
 9864                size: size(self.block_width, px(2.0)),
 9865            },
 9866        }
 9867    }
 9868
 9869    pub fn layout(
 9870        &mut self,
 9871        origin: gpui::Point<Pixels>,
 9872        cursor_name: Option<CursorName>,
 9873        window: &mut Window,
 9874        cx: &mut App,
 9875    ) {
 9876        if let Some(cursor_name) = cursor_name {
 9877            let bounds = self.bounds(origin);
 9878            let text_size = self.line_height / 1.5;
 9879
 9880            let name_origin = if cursor_name.is_top_row {
 9881                point(bounds.right() - px(1.), bounds.top())
 9882            } else {
 9883                match self.shape {
 9884                    CursorShape::Bar => point(
 9885                        bounds.right() - px(2.),
 9886                        bounds.top() - text_size / 2. - px(1.),
 9887                    ),
 9888                    _ => point(
 9889                        bounds.right() - px(1.),
 9890                        bounds.top() - text_size / 2. - px(1.),
 9891                    ),
 9892                }
 9893            };
 9894            let mut name_element = div()
 9895                .bg(self.color)
 9896                .text_size(text_size)
 9897                .px_0p5()
 9898                .line_height(text_size + px(2.))
 9899                .text_color(cursor_name.color)
 9900                .child(cursor_name.string.clone())
 9901                .into_any_element();
 9902
 9903            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
 9904
 9905            self.cursor_name = Some(name_element);
 9906        }
 9907    }
 9908
 9909    pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
 9910        let bounds = self.bounds(origin);
 9911
 9912        //Draw background or border quad
 9913        let cursor = if matches!(self.shape, CursorShape::Hollow) {
 9914            outline(bounds, self.color, BorderStyle::Solid)
 9915        } else {
 9916            fill(bounds, self.color)
 9917        };
 9918
 9919        if let Some(name) = &mut self.cursor_name {
 9920            name.paint(window, cx);
 9921        }
 9922
 9923        window.paint_quad(cursor);
 9924
 9925        if let Some(block_text) = &self.block_text {
 9926            block_text
 9927                .paint(self.origin + origin, self.line_height, window, cx)
 9928                .log_err();
 9929        }
 9930    }
 9931
 9932    pub fn shape(&self) -> CursorShape {
 9933        self.shape
 9934    }
 9935}
 9936
 9937#[derive(Debug)]
 9938pub struct HighlightedRange {
 9939    pub start_y: Pixels,
 9940    pub line_height: Pixels,
 9941    pub lines: Vec<HighlightedRangeLine>,
 9942    pub color: Hsla,
 9943    pub corner_radius: Pixels,
 9944}
 9945
 9946#[derive(Debug)]
 9947pub struct HighlightedRangeLine {
 9948    pub start_x: Pixels,
 9949    pub end_x: Pixels,
 9950}
 9951
 9952impl HighlightedRange {
 9953    pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
 9954        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
 9955            self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
 9956            self.paint_lines(
 9957                self.start_y + self.line_height,
 9958                &self.lines[1..],
 9959                fill,
 9960                bounds,
 9961                window,
 9962            );
 9963        } else {
 9964            self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
 9965        }
 9966    }
 9967
 9968    fn paint_lines(
 9969        &self,
 9970        start_y: Pixels,
 9971        lines: &[HighlightedRangeLine],
 9972        fill: bool,
 9973        _bounds: Bounds<Pixels>,
 9974        window: &mut Window,
 9975    ) {
 9976        if lines.is_empty() {
 9977            return;
 9978        }
 9979
 9980        let first_line = lines.first().unwrap();
 9981        let last_line = lines.last().unwrap();
 9982
 9983        let first_top_left = point(first_line.start_x, start_y);
 9984        let first_top_right = point(first_line.end_x, start_y);
 9985
 9986        let curve_height = point(Pixels::ZERO, self.corner_radius);
 9987        let curve_width = |start_x: Pixels, end_x: Pixels| {
 9988            let max = (end_x - start_x) / 2.;
 9989            let width = if max < self.corner_radius {
 9990                max
 9991            } else {
 9992                self.corner_radius
 9993            };
 9994
 9995            point(width, Pixels::ZERO)
 9996        };
 9997
 9998        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
 9999        let mut builder = if fill {
10000            gpui::PathBuilder::fill()
10001        } else {
10002            gpui::PathBuilder::stroke(px(1.))
10003        };
10004        builder.move_to(first_top_right - top_curve_width);
10005        builder.curve_to(first_top_right + curve_height, first_top_right);
10006
10007        let mut iter = lines.iter().enumerate().peekable();
10008        while let Some((ix, line)) = iter.next() {
10009            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
10010
10011            if let Some((_, next_line)) = iter.peek() {
10012                let next_top_right = point(next_line.end_x, bottom_right.y);
10013
10014                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
10015                    Ordering::Equal => {
10016                        builder.line_to(bottom_right);
10017                    }
10018                    Ordering::Less => {
10019                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
10020                        builder.line_to(bottom_right - curve_height);
10021                        if self.corner_radius > Pixels::ZERO {
10022                            builder.curve_to(bottom_right - curve_width, bottom_right);
10023                        }
10024                        builder.line_to(next_top_right + curve_width);
10025                        if self.corner_radius > Pixels::ZERO {
10026                            builder.curve_to(next_top_right + curve_height, next_top_right);
10027                        }
10028                    }
10029                    Ordering::Greater => {
10030                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
10031                        builder.line_to(bottom_right - curve_height);
10032                        if self.corner_radius > Pixels::ZERO {
10033                            builder.curve_to(bottom_right + curve_width, bottom_right);
10034                        }
10035                        builder.line_to(next_top_right - curve_width);
10036                        if self.corner_radius > Pixels::ZERO {
10037                            builder.curve_to(next_top_right + curve_height, next_top_right);
10038                        }
10039                    }
10040                }
10041            } else {
10042                let curve_width = curve_width(line.start_x, line.end_x);
10043                builder.line_to(bottom_right - curve_height);
10044                if self.corner_radius > Pixels::ZERO {
10045                    builder.curve_to(bottom_right - curve_width, bottom_right);
10046                }
10047
10048                let bottom_left = point(line.start_x, bottom_right.y);
10049                builder.line_to(bottom_left + curve_width);
10050                if self.corner_radius > Pixels::ZERO {
10051                    builder.curve_to(bottom_left - curve_height, bottom_left);
10052                }
10053            }
10054        }
10055
10056        if first_line.start_x > last_line.start_x {
10057            let curve_width = curve_width(last_line.start_x, first_line.start_x);
10058            let second_top_left = point(last_line.start_x, start_y + self.line_height);
10059            builder.line_to(second_top_left + curve_height);
10060            if self.corner_radius > Pixels::ZERO {
10061                builder.curve_to(second_top_left + curve_width, second_top_left);
10062            }
10063            let first_bottom_left = point(first_line.start_x, second_top_left.y);
10064            builder.line_to(first_bottom_left - curve_width);
10065            if self.corner_radius > Pixels::ZERO {
10066                builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
10067            }
10068        }
10069
10070        builder.line_to(first_top_left + curve_height);
10071        if self.corner_radius > Pixels::ZERO {
10072            builder.curve_to(first_top_left + top_curve_width, first_top_left);
10073        }
10074        builder.line_to(first_top_right - top_curve_width);
10075
10076        if let Ok(path) = builder.build() {
10077            window.paint_path(path, self.color);
10078        }
10079    }
10080}
10081
10082enum CursorPopoverType {
10083    CodeContextMenu,
10084    EditPrediction,
10085}
10086
10087pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
10088    (delta.pow(1.2) / 100.0).min(px(3.0)).into()
10089}
10090
10091fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
10092    (delta.pow(1.2) / 300.0).into()
10093}
10094
10095pub fn register_action<T: Action>(
10096    editor: &Entity<Editor>,
10097    window: &mut Window,
10098    listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
10099) {
10100    let editor = editor.clone();
10101    window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
10102        let action = action.downcast_ref().unwrap();
10103        if phase == DispatchPhase::Bubble {
10104            editor.update(cx, |editor, cx| {
10105                listener(editor, action, window, cx);
10106            })
10107        }
10108    })
10109}
10110
10111fn compute_auto_height_layout(
10112    editor: &mut Editor,
10113    min_lines: usize,
10114    max_lines: Option<usize>,
10115    max_line_number_width: Pixels,
10116    known_dimensions: Size<Option<Pixels>>,
10117    available_width: AvailableSpace,
10118    window: &mut Window,
10119    cx: &mut Context<Editor>,
10120) -> Option<Size<Pixels>> {
10121    let width = known_dimensions.width.or({
10122        if let AvailableSpace::Definite(available_width) = available_width {
10123            Some(available_width)
10124        } else {
10125            None
10126        }
10127    })?;
10128    if let Some(height) = known_dimensions.height {
10129        return Some(size(width, height));
10130    }
10131
10132    let style = editor.style.as_ref().unwrap();
10133    let font_id = window.text_system().resolve_font(&style.text.font());
10134    let font_size = style.text.font_size.to_pixels(window.rem_size());
10135    let line_height = style.text.line_height_in_pixels(window.rem_size());
10136    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
10137
10138    let mut snapshot = editor.snapshot(window, cx);
10139    let gutter_dimensions = snapshot
10140        .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
10141        .or_else(|| {
10142            editor
10143                .offset_content
10144                .then(|| GutterDimensions::default_with_margin(font_id, font_size, cx))
10145        })
10146        .unwrap_or_default();
10147
10148    editor.gutter_dimensions = gutter_dimensions;
10149    let text_width = width - gutter_dimensions.width;
10150    let overscroll = size(em_width, px(0.));
10151
10152    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
10153    if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None)
10154        && editor.set_wrap_width(Some(editor_width), cx)
10155    {
10156        snapshot = editor.snapshot(window, cx);
10157    }
10158
10159    let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
10160
10161    let min_height = line_height * min_lines as f32;
10162    let content_height = scroll_height.max(min_height);
10163
10164    let final_height = if let Some(max_lines) = max_lines {
10165        let max_height = line_height * max_lines as f32;
10166        content_height.min(max_height)
10167    } else {
10168        content_height
10169    };
10170
10171    Some(size(width, final_height))
10172}
10173
10174#[cfg(test)]
10175mod tests {
10176    use super::*;
10177    use crate::{
10178        Editor, MultiBuffer, SelectionEffects,
10179        display_map::{BlockPlacement, BlockProperties},
10180        editor_tests::{init_test, update_test_language_settings},
10181    };
10182    use gpui::{TestAppContext, VisualTestContext};
10183    use language::language_settings;
10184    use log::info;
10185    use std::num::NonZeroU32;
10186    use util::test::sample_text;
10187
10188    #[gpui::test]
10189    async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
10190        init_test(cx, |_| {});
10191
10192        let window = cx.add_window(|window, cx| {
10193            let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
10194            let mut editor = Editor::new(
10195                EditorMode::AutoHeight {
10196                    min_lines: 1,
10197                    max_lines: None,
10198                },
10199                buffer,
10200                None,
10201                window,
10202                cx,
10203            );
10204            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10205            editor
10206        });
10207        let cx = &mut VisualTestContext::from_window(*window, cx);
10208        let editor = window.root(cx).unwrap();
10209        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10210
10211        for x in 1..=100 {
10212            let (_, state) = cx.draw(
10213                Default::default(),
10214                size(px(200. + 0.13 * x as f32), px(500.)),
10215                |_, _| EditorElement::new(&editor, style.clone()),
10216            );
10217
10218            assert!(
10219                state.position_map.scroll_max.x == 0.,
10220                "Soft wrapped editor should have no horizontal scrolling!"
10221            );
10222        }
10223    }
10224
10225    #[gpui::test]
10226    async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
10227        init_test(cx, |_| {});
10228
10229        let window = cx.add_window(|window, cx| {
10230            let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
10231            let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
10232            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10233            editor
10234        });
10235        let cx = &mut VisualTestContext::from_window(*window, cx);
10236        let editor = window.root(cx).unwrap();
10237        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10238
10239        for x in 1..=100 {
10240            let (_, state) = cx.draw(
10241                Default::default(),
10242                size(px(200. + 0.13 * x as f32), px(500.)),
10243                |_, _| EditorElement::new(&editor, style.clone()),
10244            );
10245
10246            assert!(
10247                state.position_map.scroll_max.x == 0.,
10248                "Soft wrapped editor should have no horizontal scrolling!"
10249            );
10250        }
10251    }
10252
10253    #[gpui::test]
10254    fn test_shape_line_numbers(cx: &mut TestAppContext) {
10255        init_test(cx, |_| {});
10256        let window = cx.add_window(|window, cx| {
10257            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
10258            Editor::new(EditorMode::full(), buffer, None, window, cx)
10259        });
10260
10261        let editor = window.root(cx).unwrap();
10262        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
10263        let line_height = window
10264            .update(cx, |_, window, _| {
10265                style.text.line_height_in_pixels(window.rem_size())
10266            })
10267            .unwrap();
10268        let element = EditorElement::new(&editor, style);
10269        let snapshot = window
10270            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
10271            .unwrap();
10272
10273        let layouts = cx
10274            .update_window(*window, |_, window, cx| {
10275                element.layout_line_numbers(
10276                    None,
10277                    GutterDimensions {
10278                        left_padding: Pixels::ZERO,
10279                        right_padding: Pixels::ZERO,
10280                        width: px(30.0),
10281                        margin: Pixels::ZERO,
10282                        git_blame_entries_width: None,
10283                    },
10284                    line_height,
10285                    gpui::Point::default(),
10286                    DisplayRow(0)..DisplayRow(6),
10287                    &(0..6)
10288                        .map(|row| RowInfo {
10289                            buffer_row: Some(row),
10290                            ..Default::default()
10291                        })
10292                        .collect::<Vec<_>>(),
10293                    &BTreeMap::default(),
10294                    Some(DisplayPoint::new(DisplayRow(0), 0)),
10295                    &snapshot,
10296                    window,
10297                    cx,
10298                )
10299            })
10300            .unwrap();
10301        assert_eq!(layouts.len(), 6);
10302
10303        let relative_rows = window
10304            .update(cx, |editor, window, cx| {
10305                let snapshot = editor.snapshot(window, cx);
10306                element.calculate_relative_line_numbers(
10307                    &snapshot,
10308                    &(DisplayRow(0)..DisplayRow(6)),
10309                    Some(DisplayRow(3)),
10310                )
10311            })
10312            .unwrap();
10313        assert_eq!(relative_rows[&DisplayRow(0)], 3);
10314        assert_eq!(relative_rows[&DisplayRow(1)], 2);
10315        assert_eq!(relative_rows[&DisplayRow(2)], 1);
10316        // current line has no relative number
10317        assert_eq!(relative_rows[&DisplayRow(4)], 1);
10318        assert_eq!(relative_rows[&DisplayRow(5)], 2);
10319
10320        // works if cursor is before screen
10321        let relative_rows = window
10322            .update(cx, |editor, window, cx| {
10323                let snapshot = editor.snapshot(window, cx);
10324                element.calculate_relative_line_numbers(
10325                    &snapshot,
10326                    &(DisplayRow(3)..DisplayRow(6)),
10327                    Some(DisplayRow(1)),
10328                )
10329            })
10330            .unwrap();
10331        assert_eq!(relative_rows.len(), 3);
10332        assert_eq!(relative_rows[&DisplayRow(3)], 2);
10333        assert_eq!(relative_rows[&DisplayRow(4)], 3);
10334        assert_eq!(relative_rows[&DisplayRow(5)], 4);
10335
10336        // works if cursor is after screen
10337        let relative_rows = window
10338            .update(cx, |editor, window, cx| {
10339                let snapshot = editor.snapshot(window, cx);
10340                element.calculate_relative_line_numbers(
10341                    &snapshot,
10342                    &(DisplayRow(0)..DisplayRow(3)),
10343                    Some(DisplayRow(6)),
10344                )
10345            })
10346            .unwrap();
10347        assert_eq!(relative_rows.len(), 3);
10348        assert_eq!(relative_rows[&DisplayRow(0)], 5);
10349        assert_eq!(relative_rows[&DisplayRow(1)], 4);
10350        assert_eq!(relative_rows[&DisplayRow(2)], 3);
10351    }
10352
10353    #[gpui::test]
10354    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
10355        init_test(cx, |_| {});
10356
10357        let window = cx.add_window(|window, cx| {
10358            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
10359            Editor::new(EditorMode::full(), buffer, None, window, cx)
10360        });
10361        let cx = &mut VisualTestContext::from_window(*window, cx);
10362        let editor = window.root(cx).unwrap();
10363        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10364
10365        window
10366            .update(cx, |editor, window, cx| {
10367                editor.cursor_shape = CursorShape::Block;
10368                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
10369                    s.select_ranges([
10370                        Point::new(0, 0)..Point::new(1, 0),
10371                        Point::new(3, 2)..Point::new(3, 3),
10372                        Point::new(5, 6)..Point::new(6, 0),
10373                    ]);
10374                });
10375            })
10376            .unwrap();
10377
10378        let (_, state) = cx.draw(
10379            point(px(500.), px(500.)),
10380            size(px(500.), px(500.)),
10381            |_, _| EditorElement::new(&editor, style),
10382        );
10383
10384        assert_eq!(state.selections.len(), 1);
10385        let local_selections = &state.selections[0].1;
10386        assert_eq!(local_selections.len(), 3);
10387        // moves cursor back one line
10388        assert_eq!(
10389            local_selections[0].head,
10390            DisplayPoint::new(DisplayRow(0), 6)
10391        );
10392        assert_eq!(
10393            local_selections[0].range,
10394            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
10395        );
10396
10397        // moves cursor back one column
10398        assert_eq!(
10399            local_selections[1].range,
10400            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
10401        );
10402        assert_eq!(
10403            local_selections[1].head,
10404            DisplayPoint::new(DisplayRow(3), 2)
10405        );
10406
10407        // leaves cursor on the max point
10408        assert_eq!(
10409            local_selections[2].range,
10410            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
10411        );
10412        assert_eq!(
10413            local_selections[2].head,
10414            DisplayPoint::new(DisplayRow(6), 0)
10415        );
10416
10417        // active lines does not include 1 (even though the range of the selection does)
10418        assert_eq!(
10419            state.active_rows.keys().cloned().collect::<Vec<_>>(),
10420            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
10421        );
10422    }
10423
10424    #[gpui::test]
10425    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
10426        init_test(cx, |_| {});
10427
10428        let window = cx.add_window(|window, cx| {
10429            let buffer = MultiBuffer::build_simple("", cx);
10430            Editor::new(EditorMode::full(), buffer, None, window, cx)
10431        });
10432        let cx = &mut VisualTestContext::from_window(*window, cx);
10433        let editor = window.root(cx).unwrap();
10434        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10435        window
10436            .update(cx, |editor, window, cx| {
10437                editor.set_placeholder_text("hello", cx);
10438                editor.insert_blocks(
10439                    [BlockProperties {
10440                        style: BlockStyle::Fixed,
10441                        placement: BlockPlacement::Above(Anchor::min()),
10442                        height: Some(3),
10443                        render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
10444                        priority: 0,
10445                    }],
10446                    None,
10447                    cx,
10448                );
10449
10450                // Blur the editor so that it displays placeholder text.
10451                window.blur();
10452            })
10453            .unwrap();
10454
10455        let (_, state) = cx.draw(
10456            point(px(500.), px(500.)),
10457            size(px(500.), px(500.)),
10458            |_, _| EditorElement::new(&editor, style),
10459        );
10460        assert_eq!(state.position_map.line_layouts.len(), 4);
10461        assert_eq!(state.line_numbers.len(), 1);
10462        assert_eq!(
10463            state
10464                .line_numbers
10465                .get(&MultiBufferRow(0))
10466                .map(|line_number| line_number.shaped_line.text.as_ref()),
10467            Some("1")
10468        );
10469    }
10470
10471    #[gpui::test]
10472    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
10473        const TAB_SIZE: u32 = 4;
10474
10475        let input_text = "\t \t|\t| a b";
10476        let expected_invisibles = vec![
10477            Invisible::Tab {
10478                line_start_offset: 0,
10479                line_end_offset: TAB_SIZE as usize,
10480            },
10481            Invisible::Whitespace {
10482                line_offset: TAB_SIZE as usize,
10483            },
10484            Invisible::Tab {
10485                line_start_offset: TAB_SIZE as usize + 1,
10486                line_end_offset: TAB_SIZE as usize * 2,
10487            },
10488            Invisible::Tab {
10489                line_start_offset: TAB_SIZE as usize * 2 + 1,
10490                line_end_offset: TAB_SIZE as usize * 3,
10491            },
10492            Invisible::Whitespace {
10493                line_offset: TAB_SIZE as usize * 3 + 1,
10494            },
10495            Invisible::Whitespace {
10496                line_offset: TAB_SIZE as usize * 3 + 3,
10497            },
10498        ];
10499        assert_eq!(
10500            expected_invisibles.len(),
10501            input_text
10502                .chars()
10503                .filter(|initial_char| initial_char.is_whitespace())
10504                .count(),
10505            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10506        );
10507
10508        for show_line_numbers in [true, false] {
10509            init_test(cx, |s| {
10510                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10511                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
10512            });
10513
10514            let actual_invisibles = collect_invisibles_from_new_editor(
10515                cx,
10516                EditorMode::full(),
10517                input_text,
10518                px(500.0),
10519                show_line_numbers,
10520            );
10521
10522            assert_eq!(expected_invisibles, actual_invisibles);
10523        }
10524    }
10525
10526    #[gpui::test]
10527    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
10528        init_test(cx, |s| {
10529            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10530            s.defaults.tab_size = NonZeroU32::new(4);
10531        });
10532
10533        for editor_mode_without_invisibles in [
10534            EditorMode::SingleLine,
10535            EditorMode::AutoHeight {
10536                min_lines: 1,
10537                max_lines: Some(100),
10538            },
10539        ] {
10540            for show_line_numbers in [true, false] {
10541                let invisibles = collect_invisibles_from_new_editor(
10542                    cx,
10543                    editor_mode_without_invisibles.clone(),
10544                    "\t\t\t| | a b",
10545                    px(500.0),
10546                    show_line_numbers,
10547                );
10548                assert!(
10549                    invisibles.is_empty(),
10550                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
10551                );
10552            }
10553        }
10554    }
10555
10556    #[gpui::test]
10557    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
10558        let tab_size = 4;
10559        let input_text = "a\tbcd     ".repeat(9);
10560        let repeated_invisibles = [
10561            Invisible::Tab {
10562                line_start_offset: 1,
10563                line_end_offset: tab_size as usize,
10564            },
10565            Invisible::Whitespace {
10566                line_offset: tab_size as usize + 3,
10567            },
10568            Invisible::Whitespace {
10569                line_offset: tab_size as usize + 4,
10570            },
10571            Invisible::Whitespace {
10572                line_offset: tab_size as usize + 5,
10573            },
10574            Invisible::Whitespace {
10575                line_offset: tab_size as usize + 6,
10576            },
10577            Invisible::Whitespace {
10578                line_offset: tab_size as usize + 7,
10579            },
10580        ];
10581        let expected_invisibles = std::iter::once(repeated_invisibles)
10582            .cycle()
10583            .take(9)
10584            .flatten()
10585            .collect::<Vec<_>>();
10586        assert_eq!(
10587            expected_invisibles.len(),
10588            input_text
10589                .chars()
10590                .filter(|initial_char| initial_char.is_whitespace())
10591                .count(),
10592            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10593        );
10594        info!("Expected invisibles: {expected_invisibles:?}");
10595
10596        init_test(cx, |_| {});
10597
10598        // Put the same string with repeating whitespace pattern into editors of various size,
10599        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
10600        let resize_step = 10.0;
10601        let mut editor_width = 200.0;
10602        while editor_width <= 1000.0 {
10603            for show_line_numbers in [true, false] {
10604                update_test_language_settings(cx, |s| {
10605                    s.defaults.tab_size = NonZeroU32::new(tab_size);
10606                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10607                    s.defaults.preferred_line_length = Some(editor_width as u32);
10608                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
10609                });
10610
10611                let actual_invisibles = collect_invisibles_from_new_editor(
10612                    cx,
10613                    EditorMode::full(),
10614                    &input_text,
10615                    px(editor_width),
10616                    show_line_numbers,
10617                );
10618
10619                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
10620                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
10621                let mut i = 0;
10622                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
10623                    i = actual_index;
10624                    match expected_invisibles.get(i) {
10625                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
10626                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
10627                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
10628                            _ => {
10629                                panic!(
10630                                    "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
10631                                )
10632                            }
10633                        },
10634                        None => {
10635                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
10636                        }
10637                    }
10638                }
10639                let missing_expected_invisibles = &expected_invisibles[i + 1..];
10640                assert!(
10641                    missing_expected_invisibles.is_empty(),
10642                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
10643                );
10644
10645                editor_width += resize_step;
10646            }
10647        }
10648    }
10649
10650    fn collect_invisibles_from_new_editor(
10651        cx: &mut TestAppContext,
10652        editor_mode: EditorMode,
10653        input_text: &str,
10654        editor_width: Pixels,
10655        show_line_numbers: bool,
10656    ) -> Vec<Invisible> {
10657        info!(
10658            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
10659            editor_width.0
10660        );
10661        let window = cx.add_window(|window, cx| {
10662            let buffer = MultiBuffer::build_simple(input_text, cx);
10663            Editor::new(editor_mode, buffer, None, window, cx)
10664        });
10665        let cx = &mut VisualTestContext::from_window(*window, cx);
10666        let editor = window.root(cx).unwrap();
10667
10668        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10669        window
10670            .update(cx, |editor, _, cx| {
10671                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10672                editor.set_wrap_width(Some(editor_width), cx);
10673                editor.set_show_line_numbers(show_line_numbers, cx);
10674            })
10675            .unwrap();
10676        let (_, state) = cx.draw(
10677            point(px(500.), px(500.)),
10678            size(px(500.), px(500.)),
10679            |_, _| EditorElement::new(&editor, style),
10680        );
10681        state
10682            .position_map
10683            .line_layouts
10684            .iter()
10685            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
10686            .cloned()
10687            .collect()
10688    }
10689}