element.rs

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