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