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