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