element.rs

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