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