element.rs

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