element.rs

    1use crate::{
    2    ActiveDiagnostic, BlockId, CURSORS_VISIBLE_FOR, ChunkRendererContext, ChunkReplacement,
    3    CodeActionSource, ColumnarMode, ConflictsOurs, ConflictsOursMarker, ConflictsOuter,
    4    ConflictsTheirs, ConflictsTheirsMarker, ContextMenuPlacement, CursorShape, CustomBlockId,
    5    DisplayDiffHunk, DisplayPoint, DisplayRow, DocumentHighlightRead, DocumentHighlightWrite,
    6    EditDisplayMode, EditPrediction, Editor, EditorMode, EditorSettings, EditorSnapshot,
    7    EditorStyle, FILE_HEADER_HEIGHT, FocusedBlock, GutterDimensions, HalfPageDown, HalfPageUp,
    8    HandleInput, HoveredCursor, InlayHintRefreshReason, JumpData, LineDown, LineHighlight, LineUp,
    9    MAX_LINE_LEN, MINIMAP_FONT_SIZE, MULTI_BUFFER_EXCERPT_HEADER_HEIGHT, OpenExcerpts, PageDown,
   10    PageUp, PhantomBreakpointIndicator, Point, RowExt, RowRangeExt, SelectPhase,
   11    SelectedTextHighlight, Selection, SelectionDragState, SelectionEffects, SizingBehavior,
   12    SoftWrap, StickyHeaderExcerpt, ToPoint, ToggleFold, ToggleFoldAll,
   13    code_context_menus::{CodeActionsMenu, MENU_ASIDE_MAX_WIDTH, MENU_ASIDE_MIN_WIDTH, MENU_GAP},
   14    column_pixels,
   15    display_map::{
   16        Block, BlockContext, BlockStyle, ChunkRendererId, DisplaySnapshot, EditorMargins,
   17        HighlightKey, HighlightedChunk, ToDisplayPoint,
   18    },
   19    editor_settings::{
   20        CurrentLineHighlight, DocumentColorsRenderMode, DoubleClickInMultibuffer, Minimap,
   21        MinimapThumb, MinimapThumbBorder, ScrollBeyondLastLine, ScrollbarAxes,
   22        ScrollbarDiagnostics, ShowMinimap,
   23    },
   24    git::blame::{BlameRenderer, GitBlame, GlobalBlameRenderer},
   25    hover_popover::{
   26        self, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
   27        POPOVER_RIGHT_OFFSET, hover_at,
   28    },
   29    inlay_hint_settings,
   30    items::BufferSearchHighlights,
   31    mouse_context_menu::{self, MenuPosition},
   32    scroll::{
   33        ActiveScrollbarState, Autoscroll, ScrollOffset, ScrollPixelOffset, ScrollbarThumbState,
   34        scroll_amount::ScrollAmount,
   35    },
   36};
   37use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
   38use collections::{BTreeMap, HashMap};
   39use file_icons::FileIcons;
   40use git::{Oid, blame::BlameEntry, commit::ParsedCommitMessage, status::FileStatus};
   41use gpui::{
   42    Action, Along, AnyElement, App, AppContext, AvailableSpace, Axis as ScrollbarAxis, BorderStyle,
   43    Bounds, ClickEvent, ClipboardItem, ContentMask, Context, Corner, Corners, CursorStyle,
   44    DispatchPhase, Edges, Element, ElementInputHandler, Entity, Focusable as _, FontId,
   45    GlobalElementId, Hitbox, HitboxBehavior, Hsla, InteractiveElement, IntoElement, IsZero,
   46    KeybindingKeystroke, Length, Modifiers, ModifiersChangedEvent, MouseButton, MouseClickEvent,
   47    MouseDownEvent, MouseMoveEvent, MousePressureEvent, MouseUpEvent, PaintQuad, ParentElement,
   48    Pixels, PressureStage, ScrollDelta, ScrollHandle, ScrollWheelEvent, ShapedLine, SharedString,
   49    Size, StatefulInteractiveElement, Style, Styled, TextRun, TextStyleRefinement, WeakEntity,
   50    Window, anchored, deferred, div, fill, linear_color_stop, linear_gradient, outline, point, px,
   51    quad, relative, size, solid_background, transparent_black,
   52};
   53use itertools::Itertools;
   54use language::{IndentGuideSettings, language_settings::ShowWhitespaceSetting};
   55use markdown::Markdown;
   56use multi_buffer::{
   57    Anchor, ExcerptId, ExcerptInfo, ExpandExcerptDirection, ExpandInfo, MultiBufferPoint,
   58    MultiBufferRow, RowInfo,
   59};
   60
   61use edit_prediction_types::EditPredictionGranularity;
   62use project::{
   63    Entry, ProjectPath,
   64    debugger::breakpoint_store::{Breakpoint, BreakpointSessionState},
   65    project_settings::ProjectSettings,
   66};
   67use settings::{
   68    GitGutterSetting, GitHunkStyleSetting, IndentGuideBackgroundColoring, IndentGuideColoring,
   69    Settings,
   70};
   71use smallvec::{SmallVec, smallvec};
   72use std::{
   73    any::TypeId,
   74    borrow::Cow,
   75    cell::Cell,
   76    cmp::{self, Ordering},
   77    fmt::{self, Write},
   78    iter, mem,
   79    ops::{Deref, Range},
   80    path::{self, Path},
   81    rc::Rc,
   82    sync::Arc,
   83    time::{Duration, Instant},
   84};
   85use sum_tree::Bias;
   86use text::{BufferId, SelectionGoal};
   87use theme::{ActiveTheme, Appearance, BufferLineHeight, PlayerColor};
   88use ui::utils::ensure_minimum_contrast;
   89use ui::{
   90    ButtonLike, ContextMenu, Indicator, KeyBinding, POPOVER_Y_PADDING, Tooltip, prelude::*,
   91    right_click_menu, scrollbars::ShowScrollbar, text_for_keystroke,
   92};
   93use unicode_segmentation::UnicodeSegmentation;
   94use util::post_inc;
   95use util::{RangeExt, ResultExt, debug_panic};
   96use workspace::{
   97    CollaboratorId, ItemSettings, OpenInTerminal, OpenTerminal, RevealInProjectPanel, Workspace,
   98    item::{Item, ItemBufferKind},
   99    notifications::NotifyTaskExt,
  100};
  101
  102/// Determines what kinds of highlights should be applied to a lines background.
  103#[derive(Clone, Copy, Default)]
  104struct LineHighlightSpec {
  105    selection: bool,
  106    breakpoint: bool,
  107    _active_stack_frame: bool,
  108}
  109
  110#[derive(Debug)]
  111struct SelectionLayout {
  112    head: DisplayPoint,
  113    cursor_shape: CursorShape,
  114    is_newest: bool,
  115    is_local: bool,
  116    range: Range<DisplayPoint>,
  117    active_rows: Range<DisplayRow>,
  118    user_name: Option<SharedString>,
  119}
  120
  121struct InlineBlameLayout {
  122    element: AnyElement,
  123    bounds: Bounds<Pixels>,
  124    buffer_id: BufferId,
  125    entry: BlameEntry,
  126}
  127
  128impl SelectionLayout {
  129    fn new<T: ToPoint + ToDisplayPoint + Clone>(
  130        selection: Selection<T>,
  131        line_mode: bool,
  132        cursor_offset: bool,
  133        cursor_shape: CursorShape,
  134        map: &DisplaySnapshot,
  135        is_newest: bool,
  136        is_local: bool,
  137        user_name: Option<SharedString>,
  138    ) -> Self {
  139        let point_selection = selection.map(|p| p.to_point(map.buffer_snapshot()));
  140        let display_selection = point_selection.map(|p| p.to_display_point(map));
  141        let mut range = display_selection.range();
  142        let mut head = display_selection.head();
  143        let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
  144            ..map.next_line_boundary(point_selection.end).1.row();
  145
  146        // vim visual line mode
  147        if line_mode {
  148            let point_range = map.expand_to_line(point_selection.range());
  149            range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
  150        }
  151
  152        // any vim visual mode (including line mode)
  153        if cursor_offset && !range.is_empty() && !selection.reversed {
  154            if head.column() > 0 {
  155                head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left);
  156            } else if head.row().0 > 0 && head != map.max_point() {
  157                head = map.clip_point(
  158                    DisplayPoint::new(
  159                        head.row().previous_row(),
  160                        map.line_len(head.row().previous_row()),
  161                    ),
  162                    Bias::Left,
  163                );
  164                // updating range.end is a no-op unless you're cursor is
  165                // on the newline containing a multi-buffer divider
  166                // in which case the clip_point may have moved the head up
  167                // an additional row.
  168                range.end = DisplayPoint::new(head.row().next_row(), 0);
  169                active_rows.end = head.row();
  170            }
  171        }
  172
  173        Self {
  174            head,
  175            cursor_shape,
  176            is_newest,
  177            is_local,
  178            range,
  179            active_rows,
  180            user_name,
  181        }
  182    }
  183}
  184
  185#[derive(Default)]
  186struct RenderBlocksOutput {
  187    blocks: Vec<BlockLayout>,
  188    row_block_types: HashMap<DisplayRow, bool>,
  189    resized_blocks: Option<HashMap<CustomBlockId, u32>>,
  190}
  191
  192pub struct EditorElement {
  193    editor: Entity<Editor>,
  194    style: EditorStyle,
  195}
  196
  197type DisplayRowDelta = u32;
  198
  199impl EditorElement {
  200    pub(crate) const SCROLLBAR_WIDTH: Pixels = px(15.);
  201
  202    pub fn new(editor: &Entity<Editor>, style: EditorStyle) -> Self {
  203        Self {
  204            editor: editor.clone(),
  205            style,
  206        }
  207    }
  208
  209    fn register_actions(&self, window: &mut Window, cx: &mut App) {
  210        let editor = &self.editor;
  211        editor.update(cx, |editor, cx| {
  212            for action in editor.editor_actions.borrow().values() {
  213                (action)(editor, window, cx)
  214            }
  215        });
  216
  217        crate::rust_analyzer_ext::apply_related_actions(editor, window, cx);
  218        crate::clangd_ext::apply_related_actions(editor, window, cx);
  219
  220        register_action(editor, window, Editor::open_context_menu);
  221        register_action(editor, window, Editor::move_left);
  222        register_action(editor, window, Editor::move_right);
  223        register_action(editor, window, Editor::move_down);
  224        register_action(editor, window, Editor::move_down_by_lines);
  225        register_action(editor, window, Editor::select_down_by_lines);
  226        register_action(editor, window, Editor::move_up);
  227        register_action(editor, window, Editor::move_up_by_lines);
  228        register_action(editor, window, Editor::select_up_by_lines);
  229        register_action(editor, window, Editor::select_page_down);
  230        register_action(editor, window, Editor::select_page_up);
  231        register_action(editor, window, Editor::cancel);
  232        register_action(editor, window, Editor::newline);
  233        register_action(editor, window, Editor::newline_above);
  234        register_action(editor, window, Editor::newline_below);
  235        register_action(editor, window, Editor::backspace);
  236        register_action(editor, window, Editor::blame_hover);
  237        register_action(editor, window, Editor::delete);
  238        register_action(editor, window, Editor::tab);
  239        register_action(editor, window, Editor::next_snippet_tabstop);
  240        register_action(editor, window, Editor::previous_snippet_tabstop);
  241        register_action(editor, window, Editor::backtab);
  242        register_action(editor, window, Editor::indent);
  243        register_action(editor, window, Editor::outdent);
  244        register_action(editor, window, Editor::autoindent);
  245        register_action(editor, window, Editor::delete_line);
  246        register_action(editor, window, Editor::join_lines);
  247        register_action(editor, window, Editor::sort_lines_by_length);
  248        register_action(editor, window, Editor::sort_lines_case_sensitive);
  249        register_action(editor, window, Editor::sort_lines_case_insensitive);
  250        register_action(editor, window, Editor::reverse_lines);
  251        register_action(editor, window, Editor::shuffle_lines);
  252        register_action(editor, window, Editor::rotate_selections_forward);
  253        register_action(editor, window, Editor::rotate_selections_backward);
  254        register_action(editor, window, Editor::convert_indentation_to_spaces);
  255        register_action(editor, window, Editor::convert_indentation_to_tabs);
  256        register_action(editor, window, Editor::convert_to_upper_case);
  257        register_action(editor, window, Editor::convert_to_lower_case);
  258        register_action(editor, window, Editor::convert_to_title_case);
  259        register_action(editor, window, Editor::convert_to_snake_case);
  260        register_action(editor, window, Editor::convert_to_kebab_case);
  261        register_action(editor, window, Editor::convert_to_upper_camel_case);
  262        register_action(editor, window, Editor::convert_to_lower_camel_case);
  263        register_action(editor, window, Editor::convert_to_opposite_case);
  264        register_action(editor, window, Editor::convert_to_sentence_case);
  265        register_action(editor, window, Editor::toggle_case);
  266        register_action(editor, window, Editor::convert_to_rot13);
  267        register_action(editor, window, Editor::convert_to_rot47);
  268        register_action(editor, window, Editor::delete_to_previous_word_start);
  269        register_action(editor, window, Editor::delete_to_previous_subword_start);
  270        register_action(editor, window, Editor::delete_to_next_word_end);
  271        register_action(editor, window, Editor::delete_to_next_subword_end);
  272        register_action(editor, window, Editor::delete_to_beginning_of_line);
  273        register_action(editor, window, Editor::delete_to_end_of_line);
  274        register_action(editor, window, Editor::cut_to_end_of_line);
  275        register_action(editor, window, Editor::duplicate_line_up);
  276        register_action(editor, window, Editor::duplicate_line_down);
  277        register_action(editor, window, Editor::duplicate_selection);
  278        register_action(editor, window, Editor::move_line_up);
  279        register_action(editor, window, Editor::move_line_down);
  280        register_action(editor, window, Editor::transpose);
  281        register_action(editor, window, Editor::rewrap);
  282        register_action(editor, window, Editor::cut);
  283        register_action(editor, window, Editor::kill_ring_cut);
  284        register_action(editor, window, Editor::kill_ring_yank);
  285        register_action(editor, window, Editor::copy);
  286        register_action(editor, window, Editor::copy_and_trim);
  287        register_action(editor, window, Editor::diff_clipboard_with_selection);
  288        register_action(editor, window, Editor::paste);
  289        register_action(editor, window, Editor::undo);
  290        register_action(editor, window, Editor::redo);
  291        register_action(editor, window, Editor::move_page_up);
  292        register_action(editor, window, Editor::move_page_down);
  293        register_action(editor, window, Editor::next_screen);
  294        register_action(editor, window, Editor::scroll_cursor_top);
  295        register_action(editor, window, Editor::scroll_cursor_center);
  296        register_action(editor, window, Editor::scroll_cursor_bottom);
  297        register_action(editor, window, Editor::scroll_cursor_center_top_bottom);
  298        register_action(editor, window, |editor, _: &LineDown, window, cx| {
  299            editor.scroll_screen(&ScrollAmount::Line(1.), window, cx)
  300        });
  301        register_action(editor, window, |editor, _: &LineUp, window, cx| {
  302            editor.scroll_screen(&ScrollAmount::Line(-1.), window, cx)
  303        });
  304        register_action(editor, window, |editor, _: &HalfPageDown, window, cx| {
  305            editor.scroll_screen(&ScrollAmount::Page(0.5), window, cx)
  306        });
  307        register_action(
  308            editor,
  309            window,
  310            |editor, HandleInput(text): &HandleInput, window, cx| {
  311                if text.is_empty() {
  312                    return;
  313                }
  314                editor.handle_input(text, window, cx);
  315            },
  316        );
  317        register_action(editor, window, |editor, _: &HalfPageUp, window, cx| {
  318            editor.scroll_screen(&ScrollAmount::Page(-0.5), window, cx)
  319        });
  320        register_action(editor, window, |editor, _: &PageDown, window, cx| {
  321            editor.scroll_screen(&ScrollAmount::Page(1.), window, cx)
  322        });
  323        register_action(editor, window, |editor, _: &PageUp, window, cx| {
  324            editor.scroll_screen(&ScrollAmount::Page(-1.), window, cx)
  325        });
  326        register_action(editor, window, Editor::move_to_previous_word_start);
  327        register_action(editor, window, Editor::move_to_previous_subword_start);
  328        register_action(editor, window, Editor::move_to_next_word_end);
  329        register_action(editor, window, Editor::move_to_next_subword_end);
  330        register_action(editor, window, Editor::move_to_beginning_of_line);
  331        register_action(editor, window, Editor::move_to_end_of_line);
  332        register_action(editor, window, Editor::move_to_start_of_paragraph);
  333        register_action(editor, window, Editor::move_to_end_of_paragraph);
  334        register_action(editor, window, Editor::move_to_beginning);
  335        register_action(editor, window, Editor::move_to_end);
  336        register_action(editor, window, Editor::move_to_start_of_excerpt);
  337        register_action(editor, window, Editor::move_to_start_of_next_excerpt);
  338        register_action(editor, window, Editor::move_to_end_of_excerpt);
  339        register_action(editor, window, Editor::move_to_end_of_previous_excerpt);
  340        register_action(editor, window, Editor::select_up);
  341        register_action(editor, window, Editor::select_down);
  342        register_action(editor, window, Editor::select_left);
  343        register_action(editor, window, Editor::select_right);
  344        register_action(editor, window, Editor::select_to_previous_word_start);
  345        register_action(editor, window, Editor::select_to_previous_subword_start);
  346        register_action(editor, window, Editor::select_to_next_word_end);
  347        register_action(editor, window, Editor::select_to_next_subword_end);
  348        register_action(editor, window, Editor::select_to_beginning_of_line);
  349        register_action(editor, window, Editor::select_to_end_of_line);
  350        register_action(editor, window, Editor::select_to_start_of_paragraph);
  351        register_action(editor, window, Editor::select_to_end_of_paragraph);
  352        register_action(editor, window, Editor::select_to_start_of_excerpt);
  353        register_action(editor, window, Editor::select_to_start_of_next_excerpt);
  354        register_action(editor, window, Editor::select_to_end_of_excerpt);
  355        register_action(editor, window, Editor::select_to_end_of_previous_excerpt);
  356        register_action(editor, window, Editor::select_to_beginning);
  357        register_action(editor, window, Editor::select_to_end);
  358        register_action(editor, window, Editor::select_all);
  359        register_action(editor, window, |editor, action, window, cx| {
  360            editor.select_all_matches(action, window, cx).log_err();
  361        });
  362        register_action(editor, window, Editor::select_line);
  363        register_action(editor, window, Editor::split_selection_into_lines);
  364        register_action(editor, window, Editor::add_selection_above);
  365        register_action(editor, window, Editor::add_selection_below);
  366        register_action(editor, window, Editor::insert_snippet_at_selections);
  367        register_action(editor, window, |editor, action, window, cx| {
  368            editor.select_next(action, window, cx).log_err();
  369        });
  370        register_action(editor, window, |editor, action, window, cx| {
  371            editor.select_previous(action, window, cx).log_err();
  372        });
  373        register_action(editor, window, |editor, action, window, cx| {
  374            editor.find_next_match(action, window, cx).log_err();
  375        });
  376        register_action(editor, window, |editor, action, window, cx| {
  377            editor.find_previous_match(action, window, cx).log_err();
  378        });
  379        register_action(editor, window, Editor::toggle_comments);
  380        register_action(editor, window, Editor::select_larger_syntax_node);
  381        register_action(editor, window, Editor::select_smaller_syntax_node);
  382        register_action(editor, window, Editor::select_next_syntax_node);
  383        register_action(editor, window, Editor::select_prev_syntax_node);
  384        register_action(editor, window, Editor::unwrap_syntax_node);
  385        register_action(editor, window, Editor::select_enclosing_symbol);
  386        register_action(editor, window, Editor::move_to_enclosing_bracket);
  387        register_action(editor, window, Editor::undo_selection);
  388        register_action(editor, window, Editor::redo_selection);
  389        if editor.read(cx).buffer_kind(cx) == ItemBufferKind::Multibuffer {
  390            register_action(editor, window, Editor::expand_excerpts);
  391            register_action(editor, window, Editor::expand_excerpts_up);
  392            register_action(editor, window, Editor::expand_excerpts_down);
  393        }
  394        register_action(editor, window, Editor::go_to_diagnostic);
  395        register_action(editor, window, Editor::go_to_prev_diagnostic);
  396        register_action(editor, window, Editor::go_to_next_hunk);
  397        register_action(editor, window, Editor::go_to_prev_hunk);
  398        register_action(editor, window, Editor::go_to_next_document_highlight);
  399        register_action(editor, window, Editor::go_to_prev_document_highlight);
  400        register_action(editor, window, |editor, action, window, cx| {
  401            editor
  402                .go_to_definition(action, window, cx)
  403                .detach_and_log_err(cx);
  404        });
  405        register_action(editor, window, |editor, action, window, cx| {
  406            editor
  407                .go_to_definition_split(action, window, cx)
  408                .detach_and_log_err(cx);
  409        });
  410        register_action(editor, window, |editor, action, window, cx| {
  411            editor
  412                .go_to_declaration(action, window, cx)
  413                .detach_and_log_err(cx);
  414        });
  415        register_action(editor, window, |editor, action, window, cx| {
  416            editor
  417                .go_to_declaration_split(action, window, cx)
  418                .detach_and_log_err(cx);
  419        });
  420        register_action(editor, window, |editor, action, window, cx| {
  421            editor
  422                .go_to_implementation(action, window, cx)
  423                .detach_and_log_err(cx);
  424        });
  425        register_action(editor, window, |editor, action, window, cx| {
  426            editor
  427                .go_to_implementation_split(action, window, cx)
  428                .detach_and_log_err(cx);
  429        });
  430        register_action(editor, window, |editor, action, window, cx| {
  431            editor
  432                .go_to_type_definition(action, window, cx)
  433                .detach_and_log_err(cx);
  434        });
  435        register_action(editor, window, |editor, action, window, cx| {
  436            editor
  437                .go_to_type_definition_split(action, window, cx)
  438                .detach_and_log_err(cx);
  439        });
  440        register_action(editor, window, Editor::open_url);
  441        register_action(editor, window, Editor::open_selected_filename);
  442        register_action(editor, window, Editor::fold);
  443        register_action(editor, window, Editor::fold_at_level);
  444        register_action(editor, window, Editor::fold_at_level_1);
  445        register_action(editor, window, Editor::fold_at_level_2);
  446        register_action(editor, window, Editor::fold_at_level_3);
  447        register_action(editor, window, Editor::fold_at_level_4);
  448        register_action(editor, window, Editor::fold_at_level_5);
  449        register_action(editor, window, Editor::fold_at_level_6);
  450        register_action(editor, window, Editor::fold_at_level_7);
  451        register_action(editor, window, Editor::fold_at_level_8);
  452        register_action(editor, window, Editor::fold_at_level_9);
  453        register_action(editor, window, Editor::fold_all);
  454        register_action(editor, window, Editor::fold_function_bodies);
  455        register_action(editor, window, Editor::fold_recursive);
  456        register_action(editor, window, Editor::toggle_fold);
  457        register_action(editor, window, Editor::toggle_fold_recursive);
  458        register_action(editor, window, Editor::toggle_fold_all);
  459        register_action(editor, window, Editor::unfold_lines);
  460        register_action(editor, window, Editor::unfold_recursive);
  461        register_action(editor, window, Editor::unfold_all);
  462        register_action(editor, window, Editor::fold_selected_ranges);
  463        register_action(editor, window, Editor::set_mark);
  464        register_action(editor, window, Editor::swap_selection_ends);
  465        register_action(editor, window, Editor::show_completions);
  466        register_action(editor, window, Editor::show_word_completions);
  467        register_action(editor, window, Editor::toggle_code_actions);
  468        register_action(editor, window, Editor::open_excerpts);
  469        register_action(editor, window, Editor::open_excerpts_in_split);
  470        register_action(editor, window, Editor::toggle_soft_wrap);
  471        register_action(editor, window, Editor::toggle_tab_bar);
  472        register_action(editor, window, Editor::toggle_line_numbers);
  473        register_action(editor, window, Editor::toggle_relative_line_numbers);
  474        register_action(editor, window, Editor::toggle_indent_guides);
  475        register_action(editor, window, Editor::toggle_inlay_hints);
  476        register_action(editor, window, Editor::toggle_edit_predictions);
  477        if editor.read(cx).diagnostics_enabled() {
  478            register_action(editor, window, Editor::toggle_diagnostics);
  479        }
  480        if editor.read(cx).inline_diagnostics_enabled() {
  481            register_action(editor, window, Editor::toggle_inline_diagnostics);
  482        }
  483        if editor.read(cx).supports_minimap(cx) {
  484            register_action(editor, window, Editor::toggle_minimap);
  485        }
  486        register_action(editor, window, hover_popover::hover);
  487        register_action(editor, window, Editor::reveal_in_finder);
  488        register_action(editor, window, Editor::copy_path);
  489        register_action(editor, window, Editor::copy_relative_path);
  490        register_action(editor, window, Editor::copy_file_name);
  491        register_action(editor, window, Editor::copy_file_name_without_extension);
  492        register_action(editor, window, Editor::copy_highlight_json);
  493        register_action(editor, window, Editor::copy_permalink_to_line);
  494        register_action(editor, window, Editor::open_permalink_to_line);
  495        register_action(editor, window, Editor::copy_file_location);
  496        register_action(editor, window, Editor::toggle_git_blame);
  497        register_action(editor, window, Editor::toggle_git_blame_inline);
  498        register_action(editor, window, Editor::open_git_blame_commit);
  499        register_action(editor, window, Editor::toggle_selected_diff_hunks);
  500        register_action(editor, window, Editor::toggle_staged_selected_diff_hunks);
  501        register_action(editor, window, Editor::stage_and_next);
  502        register_action(editor, window, Editor::unstage_and_next);
  503        register_action(editor, window, Editor::expand_all_diff_hunks);
  504        register_action(editor, window, Editor::collapse_all_diff_hunks);
  505        register_action(editor, window, Editor::go_to_previous_change);
  506        register_action(editor, window, Editor::go_to_next_change);
  507        register_action(editor, window, Editor::go_to_prev_reference);
  508        register_action(editor, window, Editor::go_to_next_reference);
  509
  510        register_action(editor, window, |editor, action, window, cx| {
  511            if let Some(task) = editor.format(action, window, cx) {
  512                task.detach_and_notify_err(window, cx);
  513            } else {
  514                cx.propagate();
  515            }
  516        });
  517        register_action(editor, window, |editor, action, window, cx| {
  518            if let Some(task) = editor.format_selections(action, window, cx) {
  519                task.detach_and_notify_err(window, cx);
  520            } else {
  521                cx.propagate();
  522            }
  523        });
  524        register_action(editor, window, |editor, action, window, cx| {
  525            if let Some(task) = editor.organize_imports(action, window, cx) {
  526                task.detach_and_notify_err(window, cx);
  527            } else {
  528                cx.propagate();
  529            }
  530        });
  531        register_action(editor, window, Editor::restart_language_server);
  532        register_action(editor, window, Editor::stop_language_server);
  533        register_action(editor, window, Editor::show_character_palette);
  534        register_action(editor, window, |editor, action, window, cx| {
  535            if let Some(task) = editor.confirm_completion(action, window, cx) {
  536                task.detach_and_notify_err(window, cx);
  537            } else {
  538                cx.propagate();
  539            }
  540        });
  541        register_action(editor, window, |editor, action, window, cx| {
  542            if let Some(task) = editor.confirm_completion_replace(action, window, cx) {
  543                task.detach_and_notify_err(window, cx);
  544            } else {
  545                cx.propagate();
  546            }
  547        });
  548        register_action(editor, window, |editor, action, window, cx| {
  549            if let Some(task) = editor.confirm_completion_insert(action, window, cx) {
  550                task.detach_and_notify_err(window, cx);
  551            } else {
  552                cx.propagate();
  553            }
  554        });
  555        register_action(editor, window, |editor, action, window, cx| {
  556            if let Some(task) = editor.compose_completion(action, window, cx) {
  557                task.detach_and_notify_err(window, cx);
  558            } else {
  559                cx.propagate();
  560            }
  561        });
  562        register_action(editor, window, |editor, action, window, cx| {
  563            if let Some(task) = editor.confirm_code_action(action, window, cx) {
  564                task.detach_and_notify_err(window, cx);
  565            } else {
  566                cx.propagate();
  567            }
  568        });
  569        register_action(editor, window, |editor, action, window, cx| {
  570            if let Some(task) = editor.rename(action, window, cx) {
  571                task.detach_and_notify_err(window, cx);
  572            } else {
  573                cx.propagate();
  574            }
  575        });
  576        register_action(editor, window, |editor, action, window, cx| {
  577            if let Some(task) = editor.confirm_rename(action, window, cx) {
  578                task.detach_and_notify_err(window, cx);
  579            } else {
  580                cx.propagate();
  581            }
  582        });
  583        register_action(editor, window, |editor, action, window, cx| {
  584            if let Some(task) = editor.find_all_references(action, window, cx) {
  585                task.detach_and_log_err(cx);
  586            } else {
  587                cx.propagate();
  588            }
  589        });
  590        register_action(editor, window, Editor::show_signature_help);
  591        register_action(editor, window, Editor::signature_help_prev);
  592        register_action(editor, window, Editor::signature_help_next);
  593        register_action(editor, window, Editor::show_edit_prediction);
  594        register_action(editor, window, Editor::context_menu_first);
  595        register_action(editor, window, Editor::context_menu_prev);
  596        register_action(editor, window, Editor::context_menu_next);
  597        register_action(editor, window, Editor::context_menu_last);
  598        register_action(editor, window, Editor::display_cursor_names);
  599        register_action(editor, window, Editor::unique_lines_case_insensitive);
  600        register_action(editor, window, Editor::unique_lines_case_sensitive);
  601        register_action(editor, window, Editor::accept_next_word_edit_prediction);
  602        register_action(editor, window, Editor::accept_next_line_edit_prediction);
  603        register_action(editor, window, Editor::accept_edit_prediction);
  604        register_action(editor, window, Editor::restore_file);
  605        register_action(editor, window, Editor::git_restore);
  606        register_action(editor, window, Editor::apply_all_diff_hunks);
  607        register_action(editor, window, Editor::apply_selected_diff_hunks);
  608        register_action(editor, window, Editor::open_active_item_in_terminal);
  609        register_action(editor, window, Editor::reload_file);
  610        register_action(editor, window, Editor::spawn_nearest_task);
  611        register_action(editor, window, Editor::insert_uuid_v4);
  612        register_action(editor, window, Editor::insert_uuid_v7);
  613        register_action(editor, window, Editor::open_selections_in_multibuffer);
  614        register_action(editor, window, Editor::toggle_breakpoint);
  615        register_action(editor, window, Editor::edit_log_breakpoint);
  616        register_action(editor, window, Editor::enable_breakpoint);
  617        register_action(editor, window, Editor::disable_breakpoint);
  618        register_action(editor, window, Editor::toggle_read_only);
  619        if editor.read(cx).enable_wrap_selections_in_tag(cx) {
  620            register_action(editor, window, Editor::wrap_selections_in_tag);
  621        }
  622    }
  623
  624    fn register_key_listeners(&self, window: &mut Window, _: &mut App, layout: &EditorLayout) {
  625        let position_map = layout.position_map.clone();
  626        window.on_key_event({
  627            let editor = self.editor.clone();
  628            move |event: &ModifiersChangedEvent, phase, window, cx| {
  629                if phase != DispatchPhase::Bubble {
  630                    return;
  631                }
  632                editor.update(cx, |editor, cx| {
  633                    let inlay_hint_settings = inlay_hint_settings(
  634                        editor.selections.newest_anchor().head(),
  635                        &editor.buffer.read(cx).snapshot(cx),
  636                        cx,
  637                    );
  638
  639                    if let Some(inlay_modifiers) = inlay_hint_settings
  640                        .toggle_on_modifiers_press
  641                        .as_ref()
  642                        .filter(|modifiers| modifiers.modified())
  643                    {
  644                        editor.refresh_inlay_hints(
  645                            InlayHintRefreshReason::ModifiersChanged(
  646                                inlay_modifiers == &event.modifiers,
  647                            ),
  648                            cx,
  649                        );
  650                    }
  651
  652                    if editor.hover_state.focused(window, cx) {
  653                        return;
  654                    }
  655
  656                    editor.handle_modifiers_changed(event.modifiers, &position_map, window, cx);
  657                })
  658            }
  659        });
  660    }
  661
  662    fn mouse_left_down(
  663        editor: &mut Editor,
  664        event: &MouseDownEvent,
  665        position_map: &PositionMap,
  666        line_numbers: &HashMap<MultiBufferRow, LineNumberLayout>,
  667        window: &mut Window,
  668        cx: &mut Context<Editor>,
  669    ) {
  670        if window.default_prevented() {
  671            return;
  672        }
  673
  674        let text_hitbox = &position_map.text_hitbox;
  675        let gutter_hitbox = &position_map.gutter_hitbox;
  676        let point_for_position = position_map.point_for_position(event.position);
  677        let mut click_count = event.click_count;
  678        let mut modifiers = event.modifiers;
  679
  680        if let Some(hovered_hunk) =
  681            position_map
  682                .display_hunks
  683                .iter()
  684                .find_map(|(hunk, hunk_hitbox)| match hunk {
  685                    DisplayDiffHunk::Folded { .. } => None,
  686                    DisplayDiffHunk::Unfolded {
  687                        multi_buffer_range, ..
  688                    } => hunk_hitbox
  689                        .as_ref()
  690                        .is_some_and(|hitbox| hitbox.is_hovered(window))
  691                        .then(|| multi_buffer_range.clone()),
  692                })
  693        {
  694            editor.toggle_single_diff_hunk(hovered_hunk, cx);
  695            cx.notify();
  696            return;
  697        } else if gutter_hitbox.is_hovered(window) {
  698            click_count = 3; // Simulate triple-click when clicking the gutter to select lines
  699        } else if !text_hitbox.is_hovered(window) {
  700            return;
  701        }
  702
  703        if EditorSettings::get_global(cx)
  704            .drag_and_drop_selection
  705            .enabled
  706            && click_count == 1
  707            && !modifiers.shift
  708        {
  709            let newest_anchor = editor.selections.newest_anchor();
  710            let snapshot = editor.snapshot(window, cx);
  711            let selection = newest_anchor.map(|anchor| anchor.to_display_point(&snapshot));
  712            if point_for_position.intersects_selection(&selection) {
  713                editor.selection_drag_state = SelectionDragState::ReadyToDrag {
  714                    selection: newest_anchor.clone(),
  715                    click_position: event.position,
  716                    mouse_down_time: Instant::now(),
  717                };
  718                cx.stop_propagation();
  719                return;
  720            }
  721        }
  722
  723        let is_singleton = editor.buffer().read(cx).is_singleton();
  724
  725        if click_count == 2 && !is_singleton {
  726            match EditorSettings::get_global(cx).double_click_in_multibuffer {
  727                DoubleClickInMultibuffer::Select => {
  728                    // do nothing special on double click, all selection logic is below
  729                }
  730                DoubleClickInMultibuffer::Open => {
  731                    if modifiers.alt {
  732                        // if double click is made with alt, pretend it's a regular double click without opening and alt,
  733                        // and run the selection logic.
  734                        modifiers.alt = false;
  735                    } else {
  736                        let scroll_position_row = position_map.scroll_position.y;
  737                        let display_row = (((event.position - gutter_hitbox.bounds.origin).y
  738                            / position_map.line_height)
  739                            as f64
  740                            + position_map.scroll_position.y)
  741                            as u32;
  742                        let multi_buffer_row = position_map
  743                            .snapshot
  744                            .display_point_to_point(
  745                                DisplayPoint::new(DisplayRow(display_row), 0),
  746                                Bias::Right,
  747                            )
  748                            .row;
  749                        let line_offset_from_top = display_row - scroll_position_row as u32;
  750                        // if double click is made without alt, open the corresponding excerp
  751                        editor.open_excerpts_common(
  752                            Some(JumpData::MultiBufferRow {
  753                                row: MultiBufferRow(multi_buffer_row),
  754                                line_offset_from_top,
  755                            }),
  756                            false,
  757                            window,
  758                            cx,
  759                        );
  760                        return;
  761                    }
  762                }
  763            }
  764        }
  765
  766        if !is_singleton {
  767            let display_row = (ScrollPixelOffset::from(
  768                (event.position - gutter_hitbox.bounds.origin).y / position_map.line_height,
  769            ) + position_map.scroll_position.y) as u32;
  770            let multi_buffer_row = position_map
  771                .snapshot
  772                .display_point_to_point(DisplayPoint::new(DisplayRow(display_row), 0), Bias::Right)
  773                .row;
  774            if line_numbers
  775                .get(&MultiBufferRow(multi_buffer_row))
  776                .is_some_and(|line_layout| {
  777                    line_layout.segments.iter().any(|segment| {
  778                        segment
  779                            .hitbox
  780                            .as_ref()
  781                            .is_some_and(|hitbox| hitbox.contains(&event.position))
  782                    })
  783                })
  784            {
  785                let line_offset_from_top = display_row - position_map.scroll_position.y as u32;
  786
  787                editor.open_excerpts_common(
  788                    Some(JumpData::MultiBufferRow {
  789                        row: MultiBufferRow(multi_buffer_row),
  790                        line_offset_from_top,
  791                    }),
  792                    modifiers.alt,
  793                    window,
  794                    cx,
  795                );
  796                cx.stop_propagation();
  797                return;
  798            }
  799        }
  800
  801        let position = point_for_position.previous_valid;
  802        if let Some(mode) = Editor::columnar_selection_mode(&modifiers, cx) {
  803            editor.select(
  804                SelectPhase::BeginColumnar {
  805                    position,
  806                    reset: match mode {
  807                        ColumnarMode::FromMouse => true,
  808                        ColumnarMode::FromSelection => false,
  809                    },
  810                    mode,
  811                    goal_column: point_for_position.exact_unclipped.column(),
  812                },
  813                window,
  814                cx,
  815            );
  816        } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
  817        {
  818            editor.select(
  819                SelectPhase::Extend {
  820                    position,
  821                    click_count,
  822                },
  823                window,
  824                cx,
  825            );
  826        } else {
  827            editor.select(
  828                SelectPhase::Begin {
  829                    position,
  830                    add: Editor::is_alt_pressed(&modifiers, cx),
  831                    click_count,
  832                },
  833                window,
  834                cx,
  835            );
  836        }
  837        cx.stop_propagation();
  838    }
  839
  840    fn mouse_right_down(
  841        editor: &mut Editor,
  842        event: &MouseDownEvent,
  843        position_map: &PositionMap,
  844        window: &mut Window,
  845        cx: &mut Context<Editor>,
  846    ) {
  847        if position_map.gutter_hitbox.is_hovered(window) {
  848            let gutter_right_padding = editor.gutter_dimensions.right_padding;
  849            let hitbox = &position_map.gutter_hitbox;
  850
  851            if event.position.x <= hitbox.bounds.right() - gutter_right_padding {
  852                let point_for_position = position_map.point_for_position(event.position);
  853                editor.set_breakpoint_context_menu(
  854                    point_for_position.previous_valid.row(),
  855                    None,
  856                    event.position,
  857                    window,
  858                    cx,
  859                );
  860            }
  861            return;
  862        }
  863
  864        if !position_map.text_hitbox.is_hovered(window) {
  865            return;
  866        }
  867
  868        let point_for_position = position_map.point_for_position(event.position);
  869        mouse_context_menu::deploy_context_menu(
  870            editor,
  871            Some(event.position),
  872            point_for_position.previous_valid,
  873            window,
  874            cx,
  875        );
  876        cx.stop_propagation();
  877    }
  878
  879    fn mouse_middle_down(
  880        editor: &mut Editor,
  881        event: &MouseDownEvent,
  882        position_map: &PositionMap,
  883        window: &mut Window,
  884        cx: &mut Context<Editor>,
  885    ) {
  886        if !position_map.text_hitbox.is_hovered(window) || window.default_prevented() {
  887            return;
  888        }
  889
  890        let point_for_position = position_map.point_for_position(event.position);
  891        let position = point_for_position.previous_valid;
  892
  893        editor.select(
  894            SelectPhase::BeginColumnar {
  895                position,
  896                reset: true,
  897                mode: ColumnarMode::FromMouse,
  898                goal_column: point_for_position.exact_unclipped.column(),
  899            },
  900            window,
  901            cx,
  902        );
  903    }
  904
  905    fn mouse_up(
  906        editor: &mut Editor,
  907        event: &MouseUpEvent,
  908        position_map: &PositionMap,
  909        window: &mut Window,
  910        cx: &mut Context<Editor>,
  911    ) {
  912        let text_hitbox = &position_map.text_hitbox;
  913        let end_selection = editor.has_pending_selection();
  914        let pending_nonempty_selections = editor.has_pending_nonempty_selection();
  915        let point_for_position = position_map.point_for_position(event.position);
  916
  917        match editor.selection_drag_state {
  918            SelectionDragState::ReadyToDrag {
  919                selection: _,
  920                ref click_position,
  921                mouse_down_time: _,
  922            } => {
  923                if event.position == *click_position {
  924                    editor.select(
  925                        SelectPhase::Begin {
  926                            position: point_for_position.previous_valid,
  927                            add: false,
  928                            click_count: 1, // ready to drag state only occurs on click count 1
  929                        },
  930                        window,
  931                        cx,
  932                    );
  933                    editor.selection_drag_state = SelectionDragState::None;
  934                    cx.stop_propagation();
  935                    return;
  936                } else {
  937                    debug_panic!("drag state can never be in ready state after drag")
  938                }
  939            }
  940            SelectionDragState::Dragging { ref selection, .. } => {
  941                let snapshot = editor.snapshot(window, cx);
  942                let selection_display = selection.map(|anchor| anchor.to_display_point(&snapshot));
  943                if !point_for_position.intersects_selection(&selection_display)
  944                    && text_hitbox.is_hovered(window)
  945                {
  946                    let is_cut = !(cfg!(target_os = "macos") && event.modifiers.alt
  947                        || cfg!(not(target_os = "macos")) && event.modifiers.control);
  948                    editor.move_selection_on_drop(
  949                        &selection.clone(),
  950                        point_for_position.previous_valid,
  951                        is_cut,
  952                        window,
  953                        cx,
  954                    );
  955                }
  956                editor.selection_drag_state = SelectionDragState::None;
  957                cx.stop_propagation();
  958                cx.notify();
  959                return;
  960            }
  961            _ => {}
  962        }
  963
  964        if end_selection {
  965            editor.select(SelectPhase::End, window, cx);
  966        }
  967
  968        if end_selection && pending_nonempty_selections {
  969            cx.stop_propagation();
  970        } else if cfg!(any(target_os = "linux", target_os = "freebsd"))
  971            && event.button == MouseButton::Middle
  972        {
  973            #[allow(
  974                clippy::collapsible_if,
  975                clippy::needless_return,
  976                reason = "The cfg-block below makes this a false positive"
  977            )]
  978            if !text_hitbox.is_hovered(window) || editor.read_only(cx) {
  979                return;
  980            }
  981
  982            #[cfg(any(target_os = "linux", target_os = "freebsd"))]
  983            if EditorSettings::get_global(cx).middle_click_paste {
  984                if let Some(text) = cx.read_from_primary().and_then(|item| item.text()) {
  985                    let point_for_position = position_map.point_for_position(event.position);
  986                    let position = point_for_position.previous_valid;
  987
  988                    editor.select(
  989                        SelectPhase::Begin {
  990                            position,
  991                            add: false,
  992                            click_count: 1,
  993                        },
  994                        window,
  995                        cx,
  996                    );
  997                    editor.insert(&text, window, cx);
  998                }
  999                cx.stop_propagation()
 1000            }
 1001        }
 1002    }
 1003
 1004    fn click(
 1005        editor: &mut Editor,
 1006        event: &ClickEvent,
 1007        position_map: &PositionMap,
 1008        window: &mut Window,
 1009        cx: &mut Context<Editor>,
 1010    ) {
 1011        let text_hitbox = &position_map.text_hitbox;
 1012        let pending_nonempty_selections = editor.has_pending_nonempty_selection();
 1013
 1014        let hovered_link_modifier = Editor::is_cmd_or_ctrl_pressed(&event.modifiers(), cx);
 1015        let mouse_down_hovered_link_modifier = if let ClickEvent::Mouse(mouse_event) = event {
 1016            Editor::is_cmd_or_ctrl_pressed(&mouse_event.down.modifiers, cx)
 1017        } else {
 1018            true
 1019        };
 1020
 1021        if let Some(mouse_position) = event.mouse_position()
 1022            && !pending_nonempty_selections
 1023            && hovered_link_modifier
 1024            && mouse_down_hovered_link_modifier
 1025            && text_hitbox.is_hovered(window)
 1026        {
 1027            let point = position_map.point_for_position(mouse_position);
 1028            editor.handle_click_hovered_link(point, event.modifiers(), window, cx);
 1029            editor.selection_drag_state = SelectionDragState::None;
 1030
 1031            cx.stop_propagation();
 1032        }
 1033    }
 1034
 1035    fn pressure_click(
 1036        editor: &mut Editor,
 1037        event: &MousePressureEvent,
 1038        position_map: &PositionMap,
 1039        window: &mut Window,
 1040        cx: &mut Context<Editor>,
 1041    ) {
 1042        let text_hitbox = &position_map.text_hitbox;
 1043        let force_click_possible =
 1044            matches!(editor.prev_pressure_stage, Some(PressureStage::Normal))
 1045                && event.stage == PressureStage::Force;
 1046
 1047        editor.prev_pressure_stage = Some(event.stage);
 1048
 1049        if force_click_possible && text_hitbox.is_hovered(window) {
 1050            let point = position_map.point_for_position(event.position);
 1051            editor.handle_click_hovered_link(point, event.modifiers, window, cx);
 1052            editor.selection_drag_state = SelectionDragState::None;
 1053            cx.stop_propagation();
 1054        }
 1055    }
 1056
 1057    fn mouse_dragged(
 1058        editor: &mut Editor,
 1059        event: &MouseMoveEvent,
 1060        position_map: &PositionMap,
 1061        window: &mut Window,
 1062        cx: &mut Context<Editor>,
 1063    ) {
 1064        if !editor.has_pending_selection()
 1065            && matches!(editor.selection_drag_state, SelectionDragState::None)
 1066        {
 1067            return;
 1068        }
 1069
 1070        let point_for_position = position_map.point_for_position(event.position);
 1071        let text_hitbox = &position_map.text_hitbox;
 1072
 1073        let scroll_delta = {
 1074            let text_bounds = text_hitbox.bounds;
 1075            let mut scroll_delta = gpui::Point::<f32>::default();
 1076            let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
 1077            let top = text_bounds.origin.y + vertical_margin;
 1078            let bottom = text_bounds.bottom_left().y - vertical_margin;
 1079            if event.position.y < top {
 1080                scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
 1081            }
 1082            if event.position.y > bottom {
 1083                scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
 1084            }
 1085
 1086            // We need horizontal width of text
 1087            let style = editor.style.clone().unwrap_or_default();
 1088            let font_id = window.text_system().resolve_font(&style.text.font());
 1089            let font_size = style.text.font_size.to_pixels(window.rem_size());
 1090            let em_width = window.text_system().em_width(font_id, font_size).unwrap();
 1091
 1092            let scroll_margin_x = EditorSettings::get_global(cx).horizontal_scroll_margin;
 1093
 1094            let scroll_space: Pixels = scroll_margin_x * em_width;
 1095
 1096            let left = text_bounds.origin.x + scroll_space;
 1097            let right = text_bounds.top_right().x - scroll_space;
 1098
 1099            if event.position.x < left {
 1100                scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
 1101            }
 1102            if event.position.x > right {
 1103                scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
 1104            }
 1105            scroll_delta
 1106        };
 1107
 1108        if !editor.has_pending_selection() {
 1109            let drop_anchor = position_map
 1110                .snapshot
 1111                .display_point_to_anchor(point_for_position.previous_valid, Bias::Left);
 1112            match editor.selection_drag_state {
 1113                SelectionDragState::Dragging {
 1114                    ref mut drop_cursor,
 1115                    ref mut hide_drop_cursor,
 1116                    ..
 1117                } => {
 1118                    drop_cursor.start = drop_anchor;
 1119                    drop_cursor.end = drop_anchor;
 1120                    *hide_drop_cursor = !text_hitbox.is_hovered(window);
 1121                    editor.apply_scroll_delta(scroll_delta, window, cx);
 1122                    cx.notify();
 1123                }
 1124                SelectionDragState::ReadyToDrag {
 1125                    ref selection,
 1126                    ref click_position,
 1127                    ref mouse_down_time,
 1128                } => {
 1129                    let drag_and_drop_delay = Duration::from_millis(
 1130                        EditorSettings::get_global(cx)
 1131                            .drag_and_drop_selection
 1132                            .delay
 1133                            .0,
 1134                    );
 1135                    if mouse_down_time.elapsed() >= drag_and_drop_delay {
 1136                        let drop_cursor = Selection {
 1137                            id: post_inc(&mut editor.selections.next_selection_id()),
 1138                            start: drop_anchor,
 1139                            end: drop_anchor,
 1140                            reversed: false,
 1141                            goal: SelectionGoal::None,
 1142                        };
 1143                        editor.selection_drag_state = SelectionDragState::Dragging {
 1144                            selection: selection.clone(),
 1145                            drop_cursor,
 1146                            hide_drop_cursor: false,
 1147                        };
 1148                        editor.apply_scroll_delta(scroll_delta, window, cx);
 1149                        cx.notify();
 1150                    } else {
 1151                        let click_point = position_map.point_for_position(*click_position);
 1152                        editor.selection_drag_state = SelectionDragState::None;
 1153                        editor.select(
 1154                            SelectPhase::Begin {
 1155                                position: click_point.previous_valid,
 1156                                add: false,
 1157                                click_count: 1,
 1158                            },
 1159                            window,
 1160                            cx,
 1161                        );
 1162                        editor.select(
 1163                            SelectPhase::Update {
 1164                                position: point_for_position.previous_valid,
 1165                                goal_column: point_for_position.exact_unclipped.column(),
 1166                                scroll_delta,
 1167                            },
 1168                            window,
 1169                            cx,
 1170                        );
 1171                    }
 1172                }
 1173                _ => {}
 1174            }
 1175        } else {
 1176            editor.select(
 1177                SelectPhase::Update {
 1178                    position: point_for_position.previous_valid,
 1179                    goal_column: point_for_position.exact_unclipped.column(),
 1180                    scroll_delta,
 1181                },
 1182                window,
 1183                cx,
 1184            );
 1185        }
 1186    }
 1187
 1188    pub(crate) fn mouse_moved(
 1189        editor: &mut Editor,
 1190        event: &MouseMoveEvent,
 1191        position_map: &PositionMap,
 1192        window: &mut Window,
 1193        cx: &mut Context<Editor>,
 1194    ) {
 1195        let text_hitbox = &position_map.text_hitbox;
 1196        let gutter_hitbox = &position_map.gutter_hitbox;
 1197        let modifiers = event.modifiers;
 1198        let text_hovered = text_hitbox.is_hovered(window);
 1199        let gutter_hovered = gutter_hitbox.bounds.contains(&event.position);
 1200        editor.set_gutter_hovered(gutter_hovered, cx);
 1201        editor.show_mouse_cursor(cx);
 1202
 1203        let point_for_position = position_map.point_for_position(event.position);
 1204        let valid_point = point_for_position.previous_valid;
 1205
 1206        let hovered_diff_control = position_map
 1207            .diff_hunk_control_bounds
 1208            .iter()
 1209            .find(|(_, bounds)| bounds.contains(&event.position))
 1210            .map(|(row, _)| *row);
 1211
 1212        let hovered_diff_hunk_row = if let Some(control_row) = hovered_diff_control {
 1213            Some(control_row)
 1214        } else if text_hovered {
 1215            let current_row = valid_point.row();
 1216            position_map.display_hunks.iter().find_map(|(hunk, _)| {
 1217                if let DisplayDiffHunk::Unfolded {
 1218                    display_row_range, ..
 1219                } = hunk
 1220                {
 1221                    if display_row_range.contains(&current_row) {
 1222                        Some(display_row_range.start)
 1223                    } else {
 1224                        None
 1225                    }
 1226                } else {
 1227                    None
 1228                }
 1229            })
 1230        } else {
 1231            None
 1232        };
 1233
 1234        if hovered_diff_hunk_row != editor.hovered_diff_hunk_row {
 1235            editor.hovered_diff_hunk_row = hovered_diff_hunk_row;
 1236            cx.notify();
 1237        }
 1238
 1239        if let Some((bounds, buffer_id, blame_entry)) = &position_map.inline_blame_bounds {
 1240            let mouse_over_inline_blame = bounds.contains(&event.position);
 1241            let mouse_over_popover = editor
 1242                .inline_blame_popover
 1243                .as_ref()
 1244                .and_then(|state| state.popover_bounds)
 1245                .is_some_and(|bounds| bounds.contains(&event.position));
 1246            let keyboard_grace = editor
 1247                .inline_blame_popover
 1248                .as_ref()
 1249                .is_some_and(|state| state.keyboard_grace);
 1250
 1251            if mouse_over_inline_blame || mouse_over_popover {
 1252                editor.show_blame_popover(*buffer_id, blame_entry, event.position, false, cx);
 1253            } else if !keyboard_grace {
 1254                editor.hide_blame_popover(false, cx);
 1255            }
 1256        } else {
 1257            let keyboard_grace = editor
 1258                .inline_blame_popover
 1259                .as_ref()
 1260                .is_some_and(|state| state.keyboard_grace);
 1261            if !keyboard_grace {
 1262                editor.hide_blame_popover(false, cx);
 1263            }
 1264        }
 1265
 1266        let breakpoint_indicator = if gutter_hovered {
 1267            let buffer_anchor = position_map
 1268                .snapshot
 1269                .display_point_to_anchor(valid_point, Bias::Left);
 1270
 1271            if let Some((buffer_snapshot, file)) = position_map
 1272                .snapshot
 1273                .buffer_snapshot()
 1274                .buffer_for_excerpt(buffer_anchor.excerpt_id)
 1275                .and_then(|buffer| buffer.file().map(|file| (buffer, file)))
 1276            {
 1277                let as_point = text::ToPoint::to_point(&buffer_anchor.text_anchor, buffer_snapshot);
 1278
 1279                let is_visible = editor
 1280                    .gutter_breakpoint_indicator
 1281                    .0
 1282                    .is_some_and(|indicator| indicator.is_active);
 1283
 1284                let has_existing_breakpoint =
 1285                    editor.breakpoint_store.as_ref().is_some_and(|store| {
 1286                        let Some(project) = &editor.project else {
 1287                            return false;
 1288                        };
 1289                        let Some(abs_path) = project.read(cx).absolute_path(
 1290                            &ProjectPath {
 1291                                path: file.path().clone(),
 1292                                worktree_id: file.worktree_id(cx),
 1293                            },
 1294                            cx,
 1295                        ) else {
 1296                            return false;
 1297                        };
 1298                        store
 1299                            .read(cx)
 1300                            .breakpoint_at_row(&abs_path, as_point.row, cx)
 1301                            .is_some()
 1302                    });
 1303
 1304                if !is_visible {
 1305                    editor.gutter_breakpoint_indicator.1.get_or_insert_with(|| {
 1306                        cx.spawn(async move |this, cx| {
 1307                            cx.background_executor()
 1308                                .timer(Duration::from_millis(200))
 1309                                .await;
 1310
 1311                            this.update(cx, |this, cx| {
 1312                                if let Some(indicator) = this.gutter_breakpoint_indicator.0.as_mut()
 1313                                {
 1314                                    indicator.is_active = true;
 1315                                    cx.notify();
 1316                                }
 1317                            })
 1318                            .ok();
 1319                        })
 1320                    });
 1321                }
 1322
 1323                Some(PhantomBreakpointIndicator {
 1324                    display_row: valid_point.row(),
 1325                    is_active: is_visible,
 1326                    collides_with_existing_breakpoint: has_existing_breakpoint,
 1327                })
 1328            } else {
 1329                editor.gutter_breakpoint_indicator.1 = None;
 1330                None
 1331            }
 1332        } else {
 1333            editor.gutter_breakpoint_indicator.1 = None;
 1334            None
 1335        };
 1336
 1337        if &breakpoint_indicator != &editor.gutter_breakpoint_indicator.0 {
 1338            editor.gutter_breakpoint_indicator.0 = breakpoint_indicator;
 1339            cx.notify();
 1340        }
 1341
 1342        // Don't trigger hover popover if mouse is hovering over context menu
 1343        if text_hovered {
 1344            editor.update_hovered_link(
 1345                point_for_position,
 1346                &position_map.snapshot,
 1347                modifiers,
 1348                window,
 1349                cx,
 1350            );
 1351
 1352            if let Some(point) = point_for_position.as_valid() {
 1353                let anchor = position_map
 1354                    .snapshot
 1355                    .buffer_snapshot()
 1356                    .anchor_before(point.to_offset(&position_map.snapshot, Bias::Left));
 1357                hover_at(editor, Some(anchor), window, cx);
 1358                Self::update_visible_cursor(editor, point, position_map, window, cx);
 1359            } else {
 1360                editor.update_inlay_link_and_hover_points(
 1361                    &position_map.snapshot,
 1362                    point_for_position,
 1363                    modifiers.secondary(),
 1364                    modifiers.shift,
 1365                    window,
 1366                    cx,
 1367                );
 1368            }
 1369        } else {
 1370            editor.hide_hovered_link(cx);
 1371            hover_at(editor, None, window, cx);
 1372        }
 1373    }
 1374
 1375    fn update_visible_cursor(
 1376        editor: &mut Editor,
 1377        point: DisplayPoint,
 1378        position_map: &PositionMap,
 1379        window: &mut Window,
 1380        cx: &mut Context<Editor>,
 1381    ) {
 1382        let snapshot = &position_map.snapshot;
 1383        let Some(hub) = editor.collaboration_hub() else {
 1384            return;
 1385        };
 1386        let start = snapshot.display_snapshot.clip_point(
 1387            DisplayPoint::new(point.row(), point.column().saturating_sub(1)),
 1388            Bias::Left,
 1389        );
 1390        let end = snapshot.display_snapshot.clip_point(
 1391            DisplayPoint::new(
 1392                point.row(),
 1393                (point.column() + 1).min(snapshot.line_len(point.row())),
 1394            ),
 1395            Bias::Right,
 1396        );
 1397
 1398        let range = snapshot
 1399            .buffer_snapshot()
 1400            .anchor_before(start.to_point(&snapshot.display_snapshot))
 1401            ..snapshot
 1402                .buffer_snapshot()
 1403                .anchor_after(end.to_point(&snapshot.display_snapshot));
 1404
 1405        let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
 1406            return;
 1407        };
 1408        let key = crate::HoveredCursor {
 1409            replica_id: selection.replica_id,
 1410            selection_id: selection.selection.id,
 1411        };
 1412        editor.hovered_cursors.insert(
 1413            key.clone(),
 1414            cx.spawn_in(window, async move |editor, cx| {
 1415                cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 1416                editor
 1417                    .update(cx, |editor, cx| {
 1418                        editor.hovered_cursors.remove(&key);
 1419                        cx.notify();
 1420                    })
 1421                    .ok();
 1422            }),
 1423        );
 1424        cx.notify()
 1425    }
 1426
 1427    fn layout_selections(
 1428        &self,
 1429        start_anchor: Anchor,
 1430        end_anchor: Anchor,
 1431        local_selections: &[Selection<Point>],
 1432        snapshot: &EditorSnapshot,
 1433        start_row: DisplayRow,
 1434        end_row: DisplayRow,
 1435        window: &mut Window,
 1436        cx: &mut App,
 1437    ) -> (
 1438        Vec<(PlayerColor, Vec<SelectionLayout>)>,
 1439        BTreeMap<DisplayRow, LineHighlightSpec>,
 1440        Option<DisplayPoint>,
 1441    ) {
 1442        let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
 1443        let mut active_rows = BTreeMap::new();
 1444        let mut newest_selection_head = None;
 1445
 1446        let Some(editor_with_selections) = self.editor_with_selections(cx) else {
 1447            return (selections, active_rows, newest_selection_head);
 1448        };
 1449
 1450        editor_with_selections.update(cx, |editor, cx| {
 1451            if editor.show_local_selections {
 1452                let mut layouts = Vec::new();
 1453                let newest = editor.selections.newest(&editor.display_snapshot(cx));
 1454                for selection in local_selections.iter().cloned() {
 1455                    let is_empty = selection.start == selection.end;
 1456                    let is_newest = selection == newest;
 1457
 1458                    let layout = SelectionLayout::new(
 1459                        selection,
 1460                        editor.selections.line_mode(),
 1461                        editor.cursor_offset_on_selection,
 1462                        editor.cursor_shape,
 1463                        &snapshot.display_snapshot,
 1464                        is_newest,
 1465                        editor.leader_id.is_none(),
 1466                        None,
 1467                    );
 1468                    if is_newest {
 1469                        newest_selection_head = Some(layout.head);
 1470                    }
 1471
 1472                    for row in cmp::max(layout.active_rows.start.0, start_row.0)
 1473                        ..=cmp::min(layout.active_rows.end.0, end_row.0)
 1474                    {
 1475                        let contains_non_empty_selection = active_rows
 1476                            .entry(DisplayRow(row))
 1477                            .or_insert_with(LineHighlightSpec::default);
 1478                        contains_non_empty_selection.selection |= !is_empty;
 1479                    }
 1480                    layouts.push(layout);
 1481                }
 1482
 1483                let mut player = editor.current_user_player_color(cx);
 1484                if !editor.is_focused(window) {
 1485                    const UNFOCUS_EDITOR_SELECTION_OPACITY: f32 = 0.5;
 1486                    player.selection = player.selection.opacity(UNFOCUS_EDITOR_SELECTION_OPACITY);
 1487                }
 1488                selections.push((player, layouts));
 1489
 1490                if let SelectionDragState::Dragging {
 1491                    ref selection,
 1492                    ref drop_cursor,
 1493                    ref hide_drop_cursor,
 1494                } = editor.selection_drag_state
 1495                    && !hide_drop_cursor
 1496                    && (drop_cursor
 1497                        .start
 1498                        .cmp(&selection.start, &snapshot.buffer_snapshot())
 1499                        .eq(&Ordering::Less)
 1500                        || drop_cursor
 1501                            .end
 1502                            .cmp(&selection.end, &snapshot.buffer_snapshot())
 1503                            .eq(&Ordering::Greater))
 1504                {
 1505                    let drag_cursor_layout = SelectionLayout::new(
 1506                        drop_cursor.clone(),
 1507                        false,
 1508                        editor.cursor_offset_on_selection,
 1509                        CursorShape::Bar,
 1510                        &snapshot.display_snapshot,
 1511                        false,
 1512                        false,
 1513                        None,
 1514                    );
 1515                    let absent_color = cx.theme().players().absent();
 1516                    selections.push((absent_color, vec![drag_cursor_layout]));
 1517                }
 1518            }
 1519
 1520            if let Some(collaboration_hub) = &editor.collaboration_hub {
 1521                // When following someone, render the local selections in their color.
 1522                if let Some(leader_id) = editor.leader_id {
 1523                    match leader_id {
 1524                        CollaboratorId::PeerId(peer_id) => {
 1525                            if let Some(collaborator) =
 1526                                collaboration_hub.collaborators(cx).get(&peer_id)
 1527                                && let Some(participant_index) = collaboration_hub
 1528                                    .user_participant_indices(cx)
 1529                                    .get(&collaborator.user_id)
 1530                                && let Some((local_selection_style, _)) = selections.first_mut()
 1531                            {
 1532                                *local_selection_style = cx
 1533                                    .theme()
 1534                                    .players()
 1535                                    .color_for_participant(participant_index.0);
 1536                            }
 1537                        }
 1538                        CollaboratorId::Agent => {
 1539                            if let Some((local_selection_style, _)) = selections.first_mut() {
 1540                                *local_selection_style = cx.theme().players().agent();
 1541                            }
 1542                        }
 1543                    }
 1544                }
 1545
 1546                let mut remote_selections = HashMap::default();
 1547                for selection in snapshot.remote_selections_in_range(
 1548                    &(start_anchor..end_anchor),
 1549                    collaboration_hub.as_ref(),
 1550                    cx,
 1551                ) {
 1552                    // Don't re-render the leader's selections, since the local selections
 1553                    // match theirs.
 1554                    if Some(selection.collaborator_id) == editor.leader_id {
 1555                        continue;
 1556                    }
 1557                    let key = HoveredCursor {
 1558                        replica_id: selection.replica_id,
 1559                        selection_id: selection.selection.id,
 1560                    };
 1561
 1562                    let is_shown =
 1563                        editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
 1564
 1565                    remote_selections
 1566                        .entry(selection.replica_id)
 1567                        .or_insert((selection.color, Vec::new()))
 1568                        .1
 1569                        .push(SelectionLayout::new(
 1570                            selection.selection,
 1571                            selection.line_mode,
 1572                            editor.cursor_offset_on_selection,
 1573                            selection.cursor_shape,
 1574                            &snapshot.display_snapshot,
 1575                            false,
 1576                            false,
 1577                            if is_shown { selection.user_name } else { None },
 1578                        ));
 1579                }
 1580
 1581                selections.extend(remote_selections.into_values());
 1582            } else if !editor.is_focused(window) && editor.show_cursor_when_unfocused {
 1583                let cursor_offset_on_selection = editor.cursor_offset_on_selection;
 1584
 1585                let layouts = snapshot
 1586                    .buffer_snapshot()
 1587                    .selections_in_range(&(start_anchor..end_anchor), true)
 1588                    .map(move |(_, line_mode, cursor_shape, selection)| {
 1589                        SelectionLayout::new(
 1590                            selection,
 1591                            line_mode,
 1592                            cursor_offset_on_selection,
 1593                            cursor_shape,
 1594                            &snapshot.display_snapshot,
 1595                            false,
 1596                            false,
 1597                            None,
 1598                        )
 1599                    })
 1600                    .collect::<Vec<_>>();
 1601                let player = editor.current_user_player_color(cx);
 1602                selections.push((player, layouts));
 1603            }
 1604        });
 1605
 1606        #[cfg(debug_assertions)]
 1607        Self::layout_debug_ranges(
 1608            &mut selections,
 1609            start_anchor..end_anchor,
 1610            &snapshot.display_snapshot,
 1611            cx,
 1612        );
 1613
 1614        (selections, active_rows, newest_selection_head)
 1615    }
 1616
 1617    fn collect_cursors(
 1618        &self,
 1619        snapshot: &EditorSnapshot,
 1620        cx: &mut App,
 1621    ) -> Vec<(DisplayPoint, Hsla)> {
 1622        let editor = self.editor.read(cx);
 1623        let mut cursors = Vec::new();
 1624        let mut skip_local = false;
 1625        let mut add_cursor = |anchor: Anchor, color| {
 1626            cursors.push((anchor.to_display_point(&snapshot.display_snapshot), color));
 1627        };
 1628        // Remote cursors
 1629        if let Some(collaboration_hub) = &editor.collaboration_hub {
 1630            for remote_selection in snapshot.remote_selections_in_range(
 1631                &(Anchor::min()..Anchor::max()),
 1632                collaboration_hub.deref(),
 1633                cx,
 1634            ) {
 1635                add_cursor(
 1636                    remote_selection.selection.head(),
 1637                    remote_selection.color.cursor,
 1638                );
 1639                if Some(remote_selection.collaborator_id) == editor.leader_id {
 1640                    skip_local = true;
 1641                }
 1642            }
 1643        }
 1644        // Local cursors
 1645        if !skip_local {
 1646            let color = cx.theme().players().local().cursor;
 1647            editor
 1648                .selections
 1649                .disjoint_anchors()
 1650                .iter()
 1651                .for_each(|selection| {
 1652                    add_cursor(selection.head(), color);
 1653                });
 1654            if let Some(ref selection) = editor.selections.pending_anchor() {
 1655                add_cursor(selection.head(), color);
 1656            }
 1657        }
 1658        cursors
 1659    }
 1660
 1661    fn layout_visible_cursors(
 1662        &self,
 1663        snapshot: &EditorSnapshot,
 1664        selections: &[(PlayerColor, Vec<SelectionLayout>)],
 1665        row_block_types: &HashMap<DisplayRow, bool>,
 1666        visible_display_row_range: Range<DisplayRow>,
 1667        line_layouts: &[LineWithInvisibles],
 1668        text_hitbox: &Hitbox,
 1669        content_origin: gpui::Point<Pixels>,
 1670        scroll_position: gpui::Point<ScrollOffset>,
 1671        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 1672        line_height: Pixels,
 1673        em_width: Pixels,
 1674        em_advance: Pixels,
 1675        autoscroll_containing_element: bool,
 1676        window: &mut Window,
 1677        cx: &mut App,
 1678    ) -> Vec<CursorLayout> {
 1679        let mut autoscroll_bounds = None;
 1680        let cursor_layouts = self.editor.update(cx, |editor, cx| {
 1681            let mut cursors = Vec::new();
 1682
 1683            let show_local_cursors = editor.show_local_cursors(window, cx);
 1684
 1685            for (player_color, selections) in selections {
 1686                for selection in selections {
 1687                    let cursor_position = selection.head;
 1688
 1689                    let in_range = visible_display_row_range.contains(&cursor_position.row());
 1690                    if (selection.is_local && !show_local_cursors)
 1691                        || !in_range
 1692                        || row_block_types.get(&cursor_position.row()) == Some(&true)
 1693                    {
 1694                        continue;
 1695                    }
 1696
 1697                    let cursor_row_layout = &line_layouts
 1698                        [cursor_position.row().minus(visible_display_row_range.start) as usize];
 1699                    let cursor_column = cursor_position.column() as usize;
 1700
 1701                    let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 1702                    let mut block_width =
 1703                        cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
 1704                    if block_width == Pixels::ZERO {
 1705                        block_width = em_advance;
 1706                    }
 1707                    let block_text = if let CursorShape::Block = selection.cursor_shape {
 1708                        snapshot
 1709                            .grapheme_at(cursor_position)
 1710                            .or_else(|| {
 1711                                if snapshot.is_empty() {
 1712                                    snapshot.placeholder_text().and_then(|s| {
 1713                                        s.graphemes(true).next().map(|s| s.to_string().into())
 1714                                    })
 1715                                } else {
 1716                                    None
 1717                                }
 1718                            })
 1719                            .map(|text| {
 1720                                let len = text.len();
 1721
 1722                                let mut font = cursor_row_layout
 1723                                    .font_id_for_index(cursor_column)
 1724                                    .and_then(|cursor_font_id| {
 1725                                        window.text_system().get_font_for_id(cursor_font_id)
 1726                                    })
 1727                                    .unwrap_or(self.style.text.font());
 1728                                font.features = self.style.text.font_features.clone();
 1729
 1730                                // Invert the text color for the block cursor. Ensure that the text
 1731                                // color is opaque enough to be visible against the background color.
 1732                                //
 1733                                // 0.75 is an arbitrary threshold to determine if the background color is
 1734                                // opaque enough to use as a text color.
 1735                                //
 1736                                // TODO: In the future we should ensure themes have a `text_inverse` color.
 1737                                let color = if cx.theme().colors().editor_background.a < 0.75 {
 1738                                    match cx.theme().appearance {
 1739                                        Appearance::Dark => Hsla::black(),
 1740                                        Appearance::Light => Hsla::white(),
 1741                                    }
 1742                                } else {
 1743                                    cx.theme().colors().editor_background
 1744                                };
 1745
 1746                                window.text_system().shape_line(
 1747                                    text,
 1748                                    cursor_row_layout.font_size,
 1749                                    &[TextRun {
 1750                                        len,
 1751                                        font,
 1752                                        color,
 1753                                        ..Default::default()
 1754                                    }],
 1755                                    None,
 1756                                )
 1757                            })
 1758                    } else {
 1759                        None
 1760                    };
 1761
 1762                    let x = cursor_character_x - scroll_pixel_position.x.into();
 1763                    let y = ((cursor_position.row().as_f64() - scroll_position.y)
 1764                        * ScrollPixelOffset::from(line_height))
 1765                    .into();
 1766                    if selection.is_newest {
 1767                        editor.pixel_position_of_newest_cursor = Some(point(
 1768                            text_hitbox.origin.x + x + block_width / 2.,
 1769                            text_hitbox.origin.y + y + line_height / 2.,
 1770                        ));
 1771
 1772                        if autoscroll_containing_element {
 1773                            let top = text_hitbox.origin.y
 1774                                + ((cursor_position.row().as_f64() - scroll_position.y - 3.)
 1775                                    .max(0.)
 1776                                    * ScrollPixelOffset::from(line_height))
 1777                                .into();
 1778                            let left = text_hitbox.origin.x
 1779                                + ((cursor_position.column() as ScrollOffset
 1780                                    - scroll_position.x
 1781                                    - 3.)
 1782                                    .max(0.)
 1783                                    * ScrollPixelOffset::from(em_width))
 1784                                .into();
 1785
 1786                            let bottom = text_hitbox.origin.y
 1787                                + ((cursor_position.row().as_f64() - scroll_position.y + 4.)
 1788                                    * ScrollPixelOffset::from(line_height))
 1789                                .into();
 1790                            let right = text_hitbox.origin.x
 1791                                + ((cursor_position.column() as ScrollOffset - scroll_position.x
 1792                                    + 4.)
 1793                                    * ScrollPixelOffset::from(em_width))
 1794                                .into();
 1795
 1796                            autoscroll_bounds =
 1797                                Some(Bounds::from_corners(point(left, top), point(right, bottom)))
 1798                        }
 1799                    }
 1800
 1801                    let mut cursor = CursorLayout {
 1802                        color: player_color.cursor,
 1803                        block_width,
 1804                        origin: point(x, y),
 1805                        line_height,
 1806                        shape: selection.cursor_shape,
 1807                        block_text,
 1808                        cursor_name: None,
 1809                    };
 1810                    let cursor_name = selection.user_name.clone().map(|name| CursorName {
 1811                        string: name,
 1812                        color: self.style.background,
 1813                        is_top_row: cursor_position.row().0 == 0,
 1814                    });
 1815                    cursor.layout(content_origin, cursor_name, window, cx);
 1816                    cursors.push(cursor);
 1817                }
 1818            }
 1819
 1820            cursors
 1821        });
 1822
 1823        if let Some(bounds) = autoscroll_bounds {
 1824            window.request_autoscroll(bounds);
 1825        }
 1826
 1827        cursor_layouts
 1828    }
 1829
 1830    fn layout_scrollbars(
 1831        &self,
 1832        snapshot: &EditorSnapshot,
 1833        scrollbar_layout_information: &ScrollbarLayoutInformation,
 1834        content_offset: gpui::Point<Pixels>,
 1835        scroll_position: gpui::Point<ScrollOffset>,
 1836        non_visible_cursors: bool,
 1837        right_margin: Pixels,
 1838        editor_width: Pixels,
 1839        window: &mut Window,
 1840        cx: &mut App,
 1841    ) -> Option<EditorScrollbars> {
 1842        let show_scrollbars = self.editor.read(cx).show_scrollbars;
 1843        if (!show_scrollbars.horizontal && !show_scrollbars.vertical)
 1844            || self.style.scrollbar_width.is_zero()
 1845        {
 1846            return None;
 1847        }
 1848
 1849        // If a drag took place after we started dragging the scrollbar,
 1850        // cancel the scrollbar drag.
 1851        if cx.has_active_drag() {
 1852            self.editor.update(cx, |editor, cx| {
 1853                editor.scroll_manager.reset_scrollbar_state(cx)
 1854            });
 1855        }
 1856
 1857        let editor_settings = EditorSettings::get_global(cx);
 1858        let scrollbar_settings = editor_settings.scrollbar;
 1859        let show_scrollbars = match scrollbar_settings.show {
 1860            ShowScrollbar::Auto => {
 1861                let editor = self.editor.read(cx);
 1862                let is_singleton = editor.buffer_kind(cx) == ItemBufferKind::Singleton;
 1863                // Git
 1864                (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot().has_diff_hunks())
 1865                ||
 1866                // Buffer Search Results
 1867                (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights::<BufferSearchHighlights>())
 1868                ||
 1869                // Selected Text Occurrences
 1870                (is_singleton && scrollbar_settings.selected_text && editor.has_background_highlights::<SelectedTextHighlight>())
 1871                ||
 1872                // Selected Symbol Occurrences
 1873                (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
 1874                ||
 1875                // Diagnostics
 1876                (is_singleton && scrollbar_settings.diagnostics != ScrollbarDiagnostics::None && snapshot.buffer_snapshot().has_diagnostics())
 1877                ||
 1878                // Cursors out of sight
 1879                non_visible_cursors
 1880                ||
 1881                // Scrollmanager
 1882                editor.scroll_manager.scrollbars_visible()
 1883            }
 1884            ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
 1885            ShowScrollbar::Always => true,
 1886            ShowScrollbar::Never => return None,
 1887        };
 1888
 1889        // The horizontal scrollbar is usually slightly offset to align nicely with
 1890        // indent guides. However, this offset is not needed if indent guides are
 1891        // disabled for the current editor.
 1892        let content_offset = self
 1893            .editor
 1894            .read(cx)
 1895            .show_indent_guides
 1896            .is_none_or(|should_show| should_show)
 1897            .then_some(content_offset)
 1898            .unwrap_or_default();
 1899
 1900        Some(EditorScrollbars::from_scrollbar_axes(
 1901            ScrollbarAxes {
 1902                horizontal: scrollbar_settings.axes.horizontal
 1903                    && self.editor.read(cx).show_scrollbars.horizontal,
 1904                vertical: scrollbar_settings.axes.vertical
 1905                    && self.editor.read(cx).show_scrollbars.vertical,
 1906            },
 1907            scrollbar_layout_information,
 1908            content_offset,
 1909            scroll_position,
 1910            self.style.scrollbar_width,
 1911            right_margin,
 1912            editor_width,
 1913            show_scrollbars,
 1914            self.editor.read(cx).scroll_manager.active_scrollbar_state(),
 1915            window,
 1916        ))
 1917    }
 1918
 1919    fn layout_minimap(
 1920        &self,
 1921        snapshot: &EditorSnapshot,
 1922        minimap_width: Pixels,
 1923        scroll_position: gpui::Point<f64>,
 1924        scrollbar_layout_information: &ScrollbarLayoutInformation,
 1925        scrollbar_layout: Option<&EditorScrollbars>,
 1926        window: &mut Window,
 1927        cx: &mut App,
 1928    ) -> Option<MinimapLayout> {
 1929        let minimap_editor = self.editor.read(cx).minimap().cloned()?;
 1930
 1931        let minimap_settings = EditorSettings::get_global(cx).minimap;
 1932
 1933        if minimap_settings.on_active_editor() {
 1934            let active_editor = self.editor.read(cx).workspace().and_then(|ws| {
 1935                ws.read(cx)
 1936                    .active_pane()
 1937                    .read(cx)
 1938                    .active_item()
 1939                    .and_then(|i| i.act_as::<Editor>(cx))
 1940            });
 1941            if active_editor.is_some_and(|e| e != self.editor) {
 1942                return None;
 1943            }
 1944        }
 1945
 1946        if !snapshot.mode.is_full()
 1947            || minimap_width.is_zero()
 1948            || matches!(
 1949                minimap_settings.show,
 1950                ShowMinimap::Auto if scrollbar_layout.is_none_or(|layout| !layout.visible)
 1951            )
 1952        {
 1953            return None;
 1954        }
 1955
 1956        const MINIMAP_AXIS: ScrollbarAxis = ScrollbarAxis::Vertical;
 1957
 1958        let ScrollbarLayoutInformation {
 1959            editor_bounds,
 1960            scroll_range,
 1961            glyph_grid_cell,
 1962        } = scrollbar_layout_information;
 1963
 1964        let line_height = glyph_grid_cell.height;
 1965        let scroll_position = scroll_position.along(MINIMAP_AXIS);
 1966
 1967        let top_right_anchor = scrollbar_layout
 1968            .and_then(|layout| layout.vertical.as_ref())
 1969            .map(|vertical_scrollbar| vertical_scrollbar.hitbox.origin)
 1970            .unwrap_or_else(|| editor_bounds.top_right());
 1971
 1972        let thumb_state = self
 1973            .editor
 1974            .read_with(cx, |editor, _| editor.scroll_manager.minimap_thumb_state());
 1975
 1976        let show_thumb = match minimap_settings.thumb {
 1977            MinimapThumb::Always => true,
 1978            MinimapThumb::Hover => thumb_state.is_some(),
 1979        };
 1980
 1981        let minimap_bounds = Bounds::from_corner_and_size(
 1982            Corner::TopRight,
 1983            top_right_anchor,
 1984            size(minimap_width, editor_bounds.size.height),
 1985        );
 1986        let minimap_line_height = self.get_minimap_line_height(
 1987            minimap_editor
 1988                .read(cx)
 1989                .text_style_refinement
 1990                .as_ref()
 1991                .and_then(|refinement| refinement.font_size)
 1992                .unwrap_or(MINIMAP_FONT_SIZE),
 1993            window,
 1994            cx,
 1995        );
 1996        let minimap_height = minimap_bounds.size.height;
 1997
 1998        let visible_editor_lines = (editor_bounds.size.height / line_height) as f64;
 1999        let total_editor_lines = (scroll_range.height / line_height) as f64;
 2000        let minimap_lines = (minimap_height / minimap_line_height) as f64;
 2001
 2002        let minimap_scroll_top = MinimapLayout::calculate_minimap_top_offset(
 2003            total_editor_lines,
 2004            visible_editor_lines,
 2005            minimap_lines,
 2006            scroll_position,
 2007        );
 2008
 2009        let layout = ScrollbarLayout::for_minimap(
 2010            window.insert_hitbox(minimap_bounds, HitboxBehavior::Normal),
 2011            visible_editor_lines,
 2012            total_editor_lines,
 2013            minimap_line_height,
 2014            scroll_position,
 2015            minimap_scroll_top,
 2016            show_thumb,
 2017        )
 2018        .with_thumb_state(thumb_state);
 2019
 2020        minimap_editor.update(cx, |editor, cx| {
 2021            editor.set_scroll_position(point(0., minimap_scroll_top), window, cx)
 2022        });
 2023
 2024        // Required for the drop shadow to be visible
 2025        const PADDING_OFFSET: Pixels = px(4.);
 2026
 2027        let mut minimap = div()
 2028            .size_full()
 2029            .shadow_xs()
 2030            .px(PADDING_OFFSET)
 2031            .child(minimap_editor)
 2032            .into_any_element();
 2033
 2034        let extended_bounds = minimap_bounds.extend(Edges {
 2035            right: PADDING_OFFSET,
 2036            left: PADDING_OFFSET,
 2037            ..Default::default()
 2038        });
 2039        minimap.layout_as_root(extended_bounds.size.into(), window, cx);
 2040        window.with_absolute_element_offset(extended_bounds.origin, |window| {
 2041            minimap.prepaint(window, cx)
 2042        });
 2043
 2044        Some(MinimapLayout {
 2045            minimap,
 2046            thumb_layout: layout,
 2047            thumb_border_style: minimap_settings.thumb_border,
 2048            minimap_line_height,
 2049            minimap_scroll_top,
 2050            max_scroll_top: total_editor_lines,
 2051        })
 2052    }
 2053
 2054    fn get_minimap_line_height(
 2055        &self,
 2056        font_size: AbsoluteLength,
 2057        window: &mut Window,
 2058        cx: &mut App,
 2059    ) -> Pixels {
 2060        let rem_size = self.rem_size(cx).unwrap_or(window.rem_size());
 2061        let mut text_style = self.style.text.clone();
 2062        text_style.font_size = font_size;
 2063        text_style.line_height_in_pixels(rem_size)
 2064    }
 2065
 2066    fn get_minimap_width(
 2067        &self,
 2068        minimap_settings: &Minimap,
 2069        scrollbars_shown: bool,
 2070        text_width: Pixels,
 2071        em_width: Pixels,
 2072        font_size: Pixels,
 2073        rem_size: Pixels,
 2074        cx: &App,
 2075    ) -> Option<Pixels> {
 2076        if minimap_settings.show == ShowMinimap::Auto && !scrollbars_shown {
 2077            return None;
 2078        }
 2079
 2080        let minimap_font_size = self.editor.read_with(cx, |editor, cx| {
 2081            editor.minimap().map(|minimap_editor| {
 2082                minimap_editor
 2083                    .read(cx)
 2084                    .text_style_refinement
 2085                    .as_ref()
 2086                    .and_then(|refinement| refinement.font_size)
 2087                    .unwrap_or(MINIMAP_FONT_SIZE)
 2088            })
 2089        })?;
 2090
 2091        let minimap_em_width = em_width * (minimap_font_size.to_pixels(rem_size) / font_size);
 2092
 2093        let minimap_width = (text_width * MinimapLayout::MINIMAP_WIDTH_PCT)
 2094            .min(minimap_em_width * minimap_settings.max_width_columns.get() as f32);
 2095
 2096        (minimap_width >= minimap_em_width * MinimapLayout::MINIMAP_MIN_WIDTH_COLUMNS)
 2097            .then_some(minimap_width)
 2098    }
 2099
 2100    fn prepaint_crease_toggles(
 2101        &self,
 2102        crease_toggles: &mut [Option<AnyElement>],
 2103        line_height: Pixels,
 2104        gutter_dimensions: &GutterDimensions,
 2105        gutter_settings: crate::editor_settings::Gutter,
 2106        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 2107        gutter_hitbox: &Hitbox,
 2108        window: &mut Window,
 2109        cx: &mut App,
 2110    ) {
 2111        for (ix, crease_toggle) in crease_toggles.iter_mut().enumerate() {
 2112            if let Some(crease_toggle) = crease_toggle {
 2113                debug_assert!(gutter_settings.folds);
 2114                let available_space = size(
 2115                    AvailableSpace::MinContent,
 2116                    AvailableSpace::Definite(line_height * 0.55),
 2117                );
 2118                let crease_toggle_size = crease_toggle.layout_as_root(available_space, window, cx);
 2119
 2120                let position = point(
 2121                    gutter_dimensions.width - gutter_dimensions.right_padding,
 2122                    ix as f32 * line_height
 2123                        - (scroll_pixel_position.y % ScrollPixelOffset::from(line_height)).into(),
 2124                );
 2125                let centering_offset = point(
 2126                    (gutter_dimensions.fold_area_width() - crease_toggle_size.width) / 2.,
 2127                    (line_height - crease_toggle_size.height) / 2.,
 2128                );
 2129                let origin = gutter_hitbox.origin + position + centering_offset;
 2130                crease_toggle.prepaint_as_root(origin, available_space, window, cx);
 2131            }
 2132        }
 2133    }
 2134
 2135    fn prepaint_expand_toggles(
 2136        &self,
 2137        expand_toggles: &mut [Option<(AnyElement, gpui::Point<Pixels>)>],
 2138        window: &mut Window,
 2139        cx: &mut App,
 2140    ) {
 2141        for (expand_toggle, origin) in expand_toggles.iter_mut().flatten() {
 2142            let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
 2143            expand_toggle.layout_as_root(available_space, window, cx);
 2144            expand_toggle.prepaint_as_root(*origin, available_space, window, cx);
 2145        }
 2146    }
 2147
 2148    fn prepaint_crease_trailers(
 2149        &self,
 2150        trailers: Vec<Option<AnyElement>>,
 2151        lines: &[LineWithInvisibles],
 2152        line_height: Pixels,
 2153        content_origin: gpui::Point<Pixels>,
 2154        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 2155        em_width: Pixels,
 2156        window: &mut Window,
 2157        cx: &mut App,
 2158    ) -> Vec<Option<CreaseTrailerLayout>> {
 2159        trailers
 2160            .into_iter()
 2161            .enumerate()
 2162            .map(|(ix, element)| {
 2163                let mut element = element?;
 2164                let available_space = size(
 2165                    AvailableSpace::MinContent,
 2166                    AvailableSpace::Definite(line_height),
 2167                );
 2168                let size = element.layout_as_root(available_space, window, cx);
 2169
 2170                let line = &lines[ix];
 2171                let padding = if line.width == Pixels::ZERO {
 2172                    Pixels::ZERO
 2173                } else {
 2174                    4. * em_width
 2175                };
 2176                let position = point(
 2177                    Pixels::from(scroll_pixel_position.x) + line.width + padding,
 2178                    ix as f32 * line_height
 2179                        - (scroll_pixel_position.y % ScrollPixelOffset::from(line_height)).into(),
 2180                );
 2181                let centering_offset = point(px(0.), (line_height - size.height) / 2.);
 2182                let origin = content_origin + position + centering_offset;
 2183                element.prepaint_as_root(origin, available_space, window, cx);
 2184                Some(CreaseTrailerLayout {
 2185                    element,
 2186                    bounds: Bounds::new(origin, size),
 2187                })
 2188            })
 2189            .collect()
 2190    }
 2191
 2192    // Folds contained in a hunk are ignored apart from shrinking visual size
 2193    // If a fold contains any hunks then that fold line is marked as modified
 2194    fn layout_gutter_diff_hunks(
 2195        &self,
 2196        line_height: Pixels,
 2197        gutter_hitbox: &Hitbox,
 2198        display_rows: Range<DisplayRow>,
 2199        snapshot: &EditorSnapshot,
 2200        window: &mut Window,
 2201        cx: &mut App,
 2202    ) -> Vec<(DisplayDiffHunk, Option<Hitbox>)> {
 2203        let folded_buffers = self.editor.read(cx).folded_buffers(cx);
 2204        let mut display_hunks = snapshot
 2205            .display_diff_hunks_for_rows(display_rows, folded_buffers)
 2206            .map(|hunk| (hunk, None))
 2207            .collect::<Vec<_>>();
 2208        let git_gutter_setting = ProjectSettings::get_global(cx).git.git_gutter;
 2209        if let GitGutterSetting::TrackedFiles = git_gutter_setting {
 2210            for (hunk, hitbox) in &mut display_hunks {
 2211                if matches!(hunk, DisplayDiffHunk::Unfolded { .. }) {
 2212                    let hunk_bounds =
 2213                        Self::diff_hunk_bounds(snapshot, line_height, gutter_hitbox.bounds, hunk);
 2214                    *hitbox = Some(window.insert_hitbox(hunk_bounds, HitboxBehavior::BlockMouse));
 2215                }
 2216            }
 2217        }
 2218
 2219        display_hunks
 2220    }
 2221
 2222    fn layout_inline_diagnostics(
 2223        &self,
 2224        line_layouts: &[LineWithInvisibles],
 2225        crease_trailers: &[Option<CreaseTrailerLayout>],
 2226        row_block_types: &HashMap<DisplayRow, bool>,
 2227        content_origin: gpui::Point<Pixels>,
 2228        scroll_position: gpui::Point<ScrollOffset>,
 2229        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 2230        edit_prediction_popover_origin: Option<gpui::Point<Pixels>>,
 2231        start_row: DisplayRow,
 2232        end_row: DisplayRow,
 2233        line_height: Pixels,
 2234        em_width: Pixels,
 2235        style: &EditorStyle,
 2236        window: &mut Window,
 2237        cx: &mut App,
 2238    ) -> HashMap<DisplayRow, AnyElement> {
 2239        let max_severity = match self
 2240            .editor
 2241            .read(cx)
 2242            .inline_diagnostics_enabled()
 2243            .then(|| {
 2244                ProjectSettings::get_global(cx)
 2245                    .diagnostics
 2246                    .inline
 2247                    .max_severity
 2248                    .unwrap_or_else(|| self.editor.read(cx).diagnostics_max_severity)
 2249                    .into_lsp()
 2250            })
 2251            .flatten()
 2252        {
 2253            Some(max_severity) => max_severity,
 2254            None => return HashMap::default(),
 2255        };
 2256
 2257        let active_diagnostics_group =
 2258            if let ActiveDiagnostic::Group(group) = &self.editor.read(cx).active_diagnostics {
 2259                Some(group.group_id)
 2260            } else {
 2261                None
 2262            };
 2263
 2264        let diagnostics_by_rows = self.editor.update(cx, |editor, cx| {
 2265            let snapshot = editor.snapshot(window, cx);
 2266            editor
 2267                .inline_diagnostics
 2268                .iter()
 2269                .filter(|(_, diagnostic)| diagnostic.severity <= max_severity)
 2270                .filter(|(_, diagnostic)| match active_diagnostics_group {
 2271                    Some(active_diagnostics_group) => {
 2272                        // Active diagnostics are all shown in the editor already, no need to display them inline
 2273                        diagnostic.group_id != active_diagnostics_group
 2274                    }
 2275                    None => true,
 2276                })
 2277                .map(|(point, diag)| (point.to_display_point(&snapshot), diag.clone()))
 2278                .skip_while(|(point, _)| point.row() < start_row)
 2279                .take_while(|(point, _)| point.row() < end_row)
 2280                .filter(|(point, _)| !row_block_types.contains_key(&point.row()))
 2281                .fold(HashMap::default(), |mut acc, (point, diagnostic)| {
 2282                    acc.entry(point.row())
 2283                        .or_insert_with(Vec::new)
 2284                        .push(diagnostic);
 2285                    acc
 2286                })
 2287        });
 2288
 2289        if diagnostics_by_rows.is_empty() {
 2290            return HashMap::default();
 2291        }
 2292
 2293        let severity_to_color = |sev: &lsp::DiagnosticSeverity| match sev {
 2294            &lsp::DiagnosticSeverity::ERROR => Color::Error,
 2295            &lsp::DiagnosticSeverity::WARNING => Color::Warning,
 2296            &lsp::DiagnosticSeverity::INFORMATION => Color::Info,
 2297            &lsp::DiagnosticSeverity::HINT => Color::Hint,
 2298            _ => Color::Error,
 2299        };
 2300
 2301        let padding = ProjectSettings::get_global(cx).diagnostics.inline.padding as f32 * em_width;
 2302        let min_x = column_pixels(
 2303            &self.style,
 2304            ProjectSettings::get_global(cx)
 2305                .diagnostics
 2306                .inline
 2307                .min_column as usize,
 2308            window,
 2309        );
 2310
 2311        let mut elements = HashMap::default();
 2312        for (row, mut diagnostics) in diagnostics_by_rows {
 2313            diagnostics.sort_by_key(|diagnostic| {
 2314                (
 2315                    diagnostic.severity,
 2316                    std::cmp::Reverse(diagnostic.is_primary),
 2317                    diagnostic.start.row,
 2318                    diagnostic.start.column,
 2319                )
 2320            });
 2321
 2322            let Some(diagnostic_to_render) = diagnostics
 2323                .iter()
 2324                .find(|diagnostic| diagnostic.is_primary)
 2325                .or_else(|| diagnostics.first())
 2326            else {
 2327                continue;
 2328            };
 2329
 2330            let pos_y = content_origin.y + line_height * (row.0 as f64 - scroll_position.y) as f32;
 2331
 2332            let window_ix = row.0.saturating_sub(start_row.0) as usize;
 2333            let pos_x = {
 2334                let crease_trailer_layout = &crease_trailers[window_ix];
 2335                let line_layout = &line_layouts[window_ix];
 2336
 2337                let line_end = if let Some(crease_trailer) = crease_trailer_layout {
 2338                    crease_trailer.bounds.right()
 2339                } else {
 2340                    Pixels::from(
 2341                        ScrollPixelOffset::from(content_origin.x + line_layout.width)
 2342                            - scroll_pixel_position.x,
 2343                    )
 2344                };
 2345
 2346                let padded_line = line_end + padding;
 2347                let min_start = Pixels::from(
 2348                    ScrollPixelOffset::from(content_origin.x + min_x) - scroll_pixel_position.x,
 2349                );
 2350
 2351                cmp::max(padded_line, min_start)
 2352            };
 2353
 2354            let behind_edit_prediction_popover = edit_prediction_popover_origin
 2355                .as_ref()
 2356                .is_some_and(|edit_prediction_popover_origin| {
 2357                    (pos_y..pos_y + line_height).contains(&edit_prediction_popover_origin.y)
 2358                });
 2359            let opacity = if behind_edit_prediction_popover {
 2360                0.5
 2361            } else {
 2362                1.0
 2363            };
 2364
 2365            let mut element = h_flex()
 2366                .id(("diagnostic", row.0))
 2367                .h(line_height)
 2368                .w_full()
 2369                .px_1()
 2370                .rounded_xs()
 2371                .opacity(opacity)
 2372                .bg(severity_to_color(&diagnostic_to_render.severity)
 2373                    .color(cx)
 2374                    .opacity(0.05))
 2375                .text_color(severity_to_color(&diagnostic_to_render.severity).color(cx))
 2376                .text_sm()
 2377                .font(style.text.font())
 2378                .child(diagnostic_to_render.message.clone())
 2379                .into_any();
 2380
 2381            element.prepaint_as_root(point(pos_x, pos_y), AvailableSpace::min_size(), window, cx);
 2382
 2383            elements.insert(row, element);
 2384        }
 2385
 2386        elements
 2387    }
 2388
 2389    fn layout_inline_code_actions(
 2390        &self,
 2391        display_point: DisplayPoint,
 2392        content_origin: gpui::Point<Pixels>,
 2393        scroll_position: gpui::Point<ScrollOffset>,
 2394        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 2395        line_height: Pixels,
 2396        snapshot: &EditorSnapshot,
 2397        window: &mut Window,
 2398        cx: &mut App,
 2399    ) -> Option<AnyElement> {
 2400        if !snapshot
 2401            .show_code_actions
 2402            .unwrap_or(EditorSettings::get_global(cx).inline_code_actions)
 2403        {
 2404            return None;
 2405        }
 2406
 2407        let icon_size = ui::IconSize::XSmall;
 2408        let mut button = self.editor.update(cx, |editor, cx| {
 2409            editor.available_code_actions.as_ref()?;
 2410            let active = editor
 2411                .context_menu
 2412                .borrow()
 2413                .as_ref()
 2414                .and_then(|menu| {
 2415                    if let crate::CodeContextMenu::CodeActions(CodeActionsMenu {
 2416                        deployed_from,
 2417                        ..
 2418                    }) = menu
 2419                    {
 2420                        deployed_from.as_ref()
 2421                    } else {
 2422                        None
 2423                    }
 2424                })
 2425                .is_some_and(|source| matches!(source, CodeActionSource::Indicator(..)));
 2426            Some(editor.render_inline_code_actions(icon_size, display_point.row(), active, cx))
 2427        })?;
 2428
 2429        let buffer_point = display_point.to_point(&snapshot.display_snapshot);
 2430
 2431        // do not show code action for folded line
 2432        if snapshot.is_line_folded(MultiBufferRow(buffer_point.row)) {
 2433            return None;
 2434        }
 2435
 2436        // do not show code action for blank line with cursor
 2437        let line_indent = snapshot
 2438            .display_snapshot
 2439            .buffer_snapshot()
 2440            .line_indent_for_row(MultiBufferRow(buffer_point.row));
 2441        if line_indent.is_line_blank() {
 2442            return None;
 2443        }
 2444
 2445        const INLINE_SLOT_CHAR_LIMIT: u32 = 4;
 2446        const MAX_ALTERNATE_DISTANCE: u32 = 8;
 2447
 2448        let excerpt_id = snapshot
 2449            .display_snapshot
 2450            .buffer_snapshot()
 2451            .excerpt_containing(buffer_point..buffer_point)
 2452            .map(|excerpt| excerpt.id());
 2453
 2454        let is_valid_row = |row_candidate: u32| -> bool {
 2455            // move to other row if folded row
 2456            if snapshot.is_line_folded(MultiBufferRow(row_candidate)) {
 2457                return false;
 2458            }
 2459            if buffer_point.row == row_candidate {
 2460                // move to other row if cursor is in slot
 2461                if buffer_point.column < INLINE_SLOT_CHAR_LIMIT {
 2462                    return false;
 2463                }
 2464            } else {
 2465                let candidate_point = MultiBufferPoint {
 2466                    row: row_candidate,
 2467                    column: 0,
 2468                };
 2469                let candidate_excerpt_id = snapshot
 2470                    .display_snapshot
 2471                    .buffer_snapshot()
 2472                    .excerpt_containing(candidate_point..candidate_point)
 2473                    .map(|excerpt| excerpt.id());
 2474                // move to other row if different excerpt
 2475                if excerpt_id != candidate_excerpt_id {
 2476                    return false;
 2477                }
 2478            }
 2479            let line_indent = snapshot
 2480                .display_snapshot
 2481                .buffer_snapshot()
 2482                .line_indent_for_row(MultiBufferRow(row_candidate));
 2483            // use this row if it's blank
 2484            if line_indent.is_line_blank() {
 2485                true
 2486            } else {
 2487                // use this row if code starts after slot
 2488                let indent_size = snapshot
 2489                    .display_snapshot
 2490                    .buffer_snapshot()
 2491                    .indent_size_for_line(MultiBufferRow(row_candidate));
 2492                indent_size.len >= INLINE_SLOT_CHAR_LIMIT
 2493            }
 2494        };
 2495
 2496        let new_buffer_row = if is_valid_row(buffer_point.row) {
 2497            Some(buffer_point.row)
 2498        } else {
 2499            let max_row = snapshot.display_snapshot.buffer_snapshot().max_point().row;
 2500            (1..=MAX_ALTERNATE_DISTANCE).find_map(|offset| {
 2501                let row_above = buffer_point.row.saturating_sub(offset);
 2502                let row_below = buffer_point.row + offset;
 2503                if row_above != buffer_point.row && is_valid_row(row_above) {
 2504                    Some(row_above)
 2505                } else if row_below <= max_row && is_valid_row(row_below) {
 2506                    Some(row_below)
 2507                } else {
 2508                    None
 2509                }
 2510            })
 2511        }?;
 2512
 2513        let new_display_row = snapshot
 2514            .display_snapshot
 2515            .point_to_display_point(
 2516                Point {
 2517                    row: new_buffer_row,
 2518                    column: buffer_point.column,
 2519                },
 2520                text::Bias::Left,
 2521            )
 2522            .row();
 2523
 2524        let start_y = content_origin.y
 2525            + (((new_display_row.as_f64() - scroll_position.y) as f32) * line_height)
 2526            + (line_height / 2.0)
 2527            - (icon_size.square(window, cx) / 2.);
 2528        let start_x = (ScrollPixelOffset::from(content_origin.x) - scroll_pixel_position.x
 2529            + ScrollPixelOffset::from(window.rem_size() * 0.1))
 2530        .into();
 2531
 2532        let absolute_offset = gpui::point(start_x, start_y);
 2533        button.layout_as_root(gpui::AvailableSpace::min_size(), window, cx);
 2534        button.prepaint_as_root(
 2535            absolute_offset,
 2536            gpui::AvailableSpace::min_size(),
 2537            window,
 2538            cx,
 2539        );
 2540        Some(button)
 2541    }
 2542
 2543    fn layout_inline_blame(
 2544        &self,
 2545        display_row: DisplayRow,
 2546        row_info: &RowInfo,
 2547        line_layout: &LineWithInvisibles,
 2548        crease_trailer: Option<&CreaseTrailerLayout>,
 2549        em_width: Pixels,
 2550        content_origin: gpui::Point<Pixels>,
 2551        scroll_position: gpui::Point<ScrollOffset>,
 2552        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 2553        line_height: Pixels,
 2554        window: &mut Window,
 2555        cx: &mut App,
 2556    ) -> Option<InlineBlameLayout> {
 2557        if !self
 2558            .editor
 2559            .update(cx, |editor, cx| editor.render_git_blame_inline(window, cx))
 2560        {
 2561            return None;
 2562        }
 2563
 2564        let editor = self.editor.read(cx);
 2565        let blame = editor.blame.clone()?;
 2566        let padding = {
 2567            const INLINE_ACCEPT_SUGGESTION_EM_WIDTHS: f32 = 14.;
 2568
 2569            let mut padding = ProjectSettings::get_global(cx).git.inline_blame.padding as f32;
 2570
 2571            if let Some(edit_prediction) = editor.active_edit_prediction.as_ref()
 2572                && let EditPrediction::Edit {
 2573                    display_mode: EditDisplayMode::TabAccept,
 2574                    ..
 2575                } = &edit_prediction.completion
 2576            {
 2577                padding += INLINE_ACCEPT_SUGGESTION_EM_WIDTHS
 2578            }
 2579
 2580            padding * em_width
 2581        };
 2582
 2583        let (buffer_id, entry) = blame
 2584            .update(cx, |blame, cx| {
 2585                blame.blame_for_rows(&[*row_info], cx).next()
 2586            })
 2587            .flatten()?;
 2588
 2589        let mut element = render_inline_blame_entry(entry.clone(), &self.style, cx)?;
 2590
 2591        let start_y =
 2592            content_origin.y + line_height * ((display_row.as_f64() - scroll_position.y) as f32);
 2593
 2594        let start_x = {
 2595            let line_end = if let Some(crease_trailer) = crease_trailer {
 2596                crease_trailer.bounds.right()
 2597            } else {
 2598                Pixels::from(
 2599                    ScrollPixelOffset::from(content_origin.x + line_layout.width)
 2600                        - scroll_pixel_position.x,
 2601                )
 2602            };
 2603
 2604            let padded_line_end = line_end + padding;
 2605
 2606            let min_column_in_pixels = column_pixels(
 2607                &self.style,
 2608                ProjectSettings::get_global(cx).git.inline_blame.min_column as usize,
 2609                window,
 2610            );
 2611            let min_start = Pixels::from(
 2612                ScrollPixelOffset::from(content_origin.x + min_column_in_pixels)
 2613                    - scroll_pixel_position.x,
 2614            );
 2615
 2616            cmp::max(padded_line_end, min_start)
 2617        };
 2618
 2619        let absolute_offset = point(start_x, start_y);
 2620        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 2621        let bounds = Bounds::new(absolute_offset, size);
 2622
 2623        element.prepaint_as_root(absolute_offset, AvailableSpace::min_size(), window, cx);
 2624
 2625        Some(InlineBlameLayout {
 2626            element,
 2627            bounds,
 2628            buffer_id,
 2629            entry,
 2630        })
 2631    }
 2632
 2633    fn layout_blame_popover(
 2634        &self,
 2635        editor_snapshot: &EditorSnapshot,
 2636        text_hitbox: &Hitbox,
 2637        line_height: Pixels,
 2638        window: &mut Window,
 2639        cx: &mut App,
 2640    ) {
 2641        if !self.editor.read(cx).inline_blame_popover.is_some() {
 2642            return;
 2643        }
 2644
 2645        let Some(blame) = self.editor.read(cx).blame.clone() else {
 2646            return;
 2647        };
 2648        let cursor_point = self
 2649            .editor
 2650            .read(cx)
 2651            .selections
 2652            .newest::<language::Point>(&editor_snapshot.display_snapshot)
 2653            .head();
 2654
 2655        let Some((buffer, buffer_point, _)) = editor_snapshot
 2656            .buffer_snapshot()
 2657            .point_to_buffer_point(cursor_point)
 2658        else {
 2659            return;
 2660        };
 2661
 2662        let row_info = RowInfo {
 2663            buffer_id: Some(buffer.remote_id()),
 2664            buffer_row: Some(buffer_point.row),
 2665            ..Default::default()
 2666        };
 2667
 2668        let Some((buffer_id, blame_entry)) = blame
 2669            .update(cx, |blame, cx| blame.blame_for_rows(&[row_info], cx).next())
 2670            .flatten()
 2671        else {
 2672            return;
 2673        };
 2674
 2675        let Some((popover_state, target_point)) = self.editor.read_with(cx, |editor, _| {
 2676            editor
 2677                .inline_blame_popover
 2678                .as_ref()
 2679                .map(|state| (state.popover_state.clone(), state.position))
 2680        }) else {
 2681            return;
 2682        };
 2683
 2684        let workspace = self
 2685            .editor
 2686            .read_with(cx, |editor, _| editor.workspace().map(|w| w.downgrade()));
 2687
 2688        let maybe_element = workspace.and_then(|workspace| {
 2689            render_blame_entry_popover(
 2690                blame_entry,
 2691                popover_state.scroll_handle,
 2692                popover_state.commit_message,
 2693                popover_state.markdown,
 2694                workspace,
 2695                &blame,
 2696                buffer_id,
 2697                window,
 2698                cx,
 2699            )
 2700        });
 2701
 2702        if let Some(mut element) = maybe_element {
 2703            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 2704            let overall_height = size.height + HOVER_POPOVER_GAP;
 2705            let popover_origin = if target_point.y > overall_height {
 2706                point(target_point.x, target_point.y - size.height)
 2707            } else {
 2708                point(
 2709                    target_point.x,
 2710                    target_point.y + line_height + HOVER_POPOVER_GAP,
 2711                )
 2712            };
 2713
 2714            let horizontal_offset = (text_hitbox.top_right().x
 2715                - POPOVER_RIGHT_OFFSET
 2716                - (popover_origin.x + size.width))
 2717                .min(Pixels::ZERO);
 2718
 2719            let origin = point(popover_origin.x + horizontal_offset, popover_origin.y);
 2720            let popover_bounds = Bounds::new(origin, size);
 2721
 2722            self.editor.update(cx, |editor, _| {
 2723                if let Some(state) = &mut editor.inline_blame_popover {
 2724                    state.popover_bounds = Some(popover_bounds);
 2725                }
 2726            });
 2727
 2728            window.defer_draw(element, origin, 2);
 2729        }
 2730    }
 2731
 2732    fn layout_blame_entries(
 2733        &self,
 2734        buffer_rows: &[RowInfo],
 2735        em_width: Pixels,
 2736        scroll_position: gpui::Point<ScrollOffset>,
 2737        line_height: Pixels,
 2738        gutter_hitbox: &Hitbox,
 2739        max_width: Option<Pixels>,
 2740        window: &mut Window,
 2741        cx: &mut App,
 2742    ) -> Option<Vec<AnyElement>> {
 2743        if !self
 2744            .editor
 2745            .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
 2746        {
 2747            return None;
 2748        }
 2749
 2750        let blame = self.editor.read(cx).blame.clone()?;
 2751        let workspace = self.editor.read(cx).workspace()?;
 2752        let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
 2753            blame.blame_for_rows(buffer_rows, cx).collect()
 2754        });
 2755
 2756        let width = if let Some(max_width) = max_width {
 2757            AvailableSpace::Definite(max_width)
 2758        } else {
 2759            AvailableSpace::MaxContent
 2760        };
 2761        let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
 2762        let start_x = em_width;
 2763
 2764        let mut last_used_color: Option<(Hsla, Oid)> = None;
 2765        let blame_renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 2766
 2767        let shaped_lines = blamed_rows
 2768            .into_iter()
 2769            .enumerate()
 2770            .flat_map(|(ix, blame_entry)| {
 2771                let (buffer_id, blame_entry) = blame_entry?;
 2772                let mut element = render_blame_entry(
 2773                    ix,
 2774                    &blame,
 2775                    blame_entry,
 2776                    &self.style,
 2777                    &mut last_used_color,
 2778                    self.editor.clone(),
 2779                    workspace.clone(),
 2780                    buffer_id,
 2781                    &*blame_renderer,
 2782                    window,
 2783                    cx,
 2784                )?;
 2785
 2786                let start_y = ix as f32 * line_height
 2787                    - Pixels::from(scroll_top % ScrollPixelOffset::from(line_height));
 2788                let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
 2789
 2790                element.prepaint_as_root(
 2791                    absolute_offset,
 2792                    size(width, AvailableSpace::MinContent),
 2793                    window,
 2794                    cx,
 2795                );
 2796
 2797                Some(element)
 2798            })
 2799            .collect();
 2800
 2801        Some(shaped_lines)
 2802    }
 2803
 2804    fn layout_indent_guides(
 2805        &self,
 2806        content_origin: gpui::Point<Pixels>,
 2807        text_origin: gpui::Point<Pixels>,
 2808        visible_buffer_range: Range<MultiBufferRow>,
 2809        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 2810        line_height: Pixels,
 2811        snapshot: &DisplaySnapshot,
 2812        window: &mut Window,
 2813        cx: &mut App,
 2814    ) -> Option<Vec<IndentGuideLayout>> {
 2815        let indent_guides = self.editor.update(cx, |editor, cx| {
 2816            editor.indent_guides(visible_buffer_range, snapshot, cx)
 2817        })?;
 2818
 2819        let active_indent_guide_indices = self.editor.update(cx, |editor, cx| {
 2820            editor
 2821                .find_active_indent_guide_indices(&indent_guides, snapshot, window, cx)
 2822                .unwrap_or_default()
 2823        });
 2824
 2825        Some(
 2826            indent_guides
 2827                .into_iter()
 2828                .enumerate()
 2829                .filter_map(|(i, indent_guide)| {
 2830                    let single_indent_width =
 2831                        column_pixels(&self.style, indent_guide.tab_size as usize, window);
 2832                    let total_width = single_indent_width * indent_guide.depth as f32;
 2833                    let start_x = Pixels::from(
 2834                        ScrollOffset::from(content_origin.x + total_width)
 2835                            - scroll_pixel_position.x,
 2836                    );
 2837                    if start_x >= text_origin.x {
 2838                        let (offset_y, length) = Self::calculate_indent_guide_bounds(
 2839                            indent_guide.start_row..indent_guide.end_row,
 2840                            line_height,
 2841                            snapshot,
 2842                        );
 2843
 2844                        let start_y = Pixels::from(
 2845                            ScrollOffset::from(content_origin.y) + offset_y
 2846                                - scroll_pixel_position.y,
 2847                        );
 2848
 2849                        Some(IndentGuideLayout {
 2850                            origin: point(start_x, start_y),
 2851                            length,
 2852                            single_indent_width,
 2853                            depth: indent_guide.depth,
 2854                            active: active_indent_guide_indices.contains(&i),
 2855                            settings: indent_guide.settings,
 2856                        })
 2857                    } else {
 2858                        None
 2859                    }
 2860                })
 2861                .collect(),
 2862        )
 2863    }
 2864
 2865    fn layout_wrap_guides(
 2866        &self,
 2867        em_advance: Pixels,
 2868        scroll_position: gpui::Point<f64>,
 2869        content_origin: gpui::Point<Pixels>,
 2870        scrollbar_layout: Option<&EditorScrollbars>,
 2871        vertical_scrollbar_width: Pixels,
 2872        hitbox: &Hitbox,
 2873        window: &Window,
 2874        cx: &App,
 2875    ) -> SmallVec<[(Pixels, bool); 2]> {
 2876        let scroll_left = scroll_position.x as f32 * em_advance;
 2877        let content_origin = content_origin.x;
 2878        let horizontal_offset = content_origin - scroll_left;
 2879        let vertical_scrollbar_width = scrollbar_layout
 2880            .and_then(|layout| layout.visible.then_some(vertical_scrollbar_width))
 2881            .unwrap_or_default();
 2882
 2883        self.editor
 2884            .read(cx)
 2885            .wrap_guides(cx)
 2886            .into_iter()
 2887            .flat_map(|(guide, active)| {
 2888                let wrap_position = column_pixels(&self.style, guide, window);
 2889                let wrap_guide_x = wrap_position + horizontal_offset;
 2890                let display_wrap_guide = wrap_guide_x >= content_origin
 2891                    && wrap_guide_x <= hitbox.bounds.right() - vertical_scrollbar_width;
 2892
 2893                display_wrap_guide.then_some((wrap_guide_x, active))
 2894            })
 2895            .collect()
 2896    }
 2897
 2898    fn calculate_indent_guide_bounds(
 2899        row_range: Range<MultiBufferRow>,
 2900        line_height: Pixels,
 2901        snapshot: &DisplaySnapshot,
 2902    ) -> (f64, gpui::Pixels) {
 2903        let start_point = Point::new(row_range.start.0, 0);
 2904        let end_point = Point::new(row_range.end.0, 0);
 2905
 2906        let row_range = start_point.to_display_point(snapshot).row()
 2907            ..end_point.to_display_point(snapshot).row();
 2908
 2909        let mut prev_line = start_point;
 2910        prev_line.row = prev_line.row.saturating_sub(1);
 2911        let prev_line = prev_line.to_display_point(snapshot).row();
 2912
 2913        let mut cons_line = end_point;
 2914        cons_line.row += 1;
 2915        let cons_line = cons_line.to_display_point(snapshot).row();
 2916
 2917        let mut offset_y = row_range.start.as_f64() * f64::from(line_height);
 2918        let mut length = (cons_line.0.saturating_sub(row_range.start.0)) as f32 * line_height;
 2919
 2920        // If we are at the end of the buffer, ensure that the indent guide extends to the end of the line.
 2921        if row_range.end == cons_line {
 2922            length += line_height;
 2923        }
 2924
 2925        // If there is a block (e.g. diagnostic) in between the start of the indent guide and the line above,
 2926        // we want to extend the indent guide to the start of the block.
 2927        let mut block_height = 0;
 2928        let mut block_offset = 0;
 2929        let mut found_excerpt_header = false;
 2930        for (_, block) in snapshot.blocks_in_range(prev_line..row_range.start) {
 2931            if matches!(
 2932                block,
 2933                Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
 2934            ) {
 2935                found_excerpt_header = true;
 2936                break;
 2937            }
 2938            block_offset += block.height();
 2939            block_height += block.height();
 2940        }
 2941        if !found_excerpt_header {
 2942            offset_y -= block_offset as f64 * f64::from(line_height);
 2943            length += block_height as f32 * line_height;
 2944        }
 2945
 2946        // If there is a block (e.g. diagnostic) at the end of an multibuffer excerpt,
 2947        // we want to ensure that the indent guide stops before the excerpt header.
 2948        let mut block_height = 0;
 2949        let mut found_excerpt_header = false;
 2950        for (_, block) in snapshot.blocks_in_range(row_range.end..cons_line) {
 2951            if matches!(
 2952                block,
 2953                Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
 2954            ) {
 2955                found_excerpt_header = true;
 2956            }
 2957            block_height += block.height();
 2958        }
 2959        if found_excerpt_header {
 2960            length -= block_height as f32 * line_height;
 2961        }
 2962
 2963        (offset_y, length)
 2964    }
 2965
 2966    fn layout_breakpoints(
 2967        &self,
 2968        line_height: Pixels,
 2969        range: Range<DisplayRow>,
 2970        scroll_position: gpui::Point<ScrollOffset>,
 2971        gutter_dimensions: &GutterDimensions,
 2972        gutter_hitbox: &Hitbox,
 2973        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 2974        snapshot: &EditorSnapshot,
 2975        breakpoints: HashMap<DisplayRow, (Anchor, Breakpoint, Option<BreakpointSessionState>)>,
 2976        row_infos: &[RowInfo],
 2977        window: &mut Window,
 2978        cx: &mut App,
 2979    ) -> Vec<AnyElement> {
 2980        self.editor.update(cx, |editor, cx| {
 2981            breakpoints
 2982                .into_iter()
 2983                .filter_map(|(display_row, (text_anchor, bp, state))| {
 2984                    if row_infos
 2985                        .get((display_row.0.saturating_sub(range.start.0)) as usize)
 2986                        .is_some_and(|row_info| {
 2987                            row_info.expand_info.is_some()
 2988                                || row_info
 2989                                    .diff_status
 2990                                    .is_some_and(|status| status.is_deleted())
 2991                        })
 2992                    {
 2993                        return None;
 2994                    }
 2995
 2996                    if range.start > display_row || range.end < display_row {
 2997                        return None;
 2998                    }
 2999
 3000                    let row =
 3001                        MultiBufferRow(DisplayPoint::new(display_row, 0).to_point(snapshot).row);
 3002                    if snapshot.is_line_folded(row) {
 3003                        return None;
 3004                    }
 3005
 3006                    let button = editor.render_breakpoint(text_anchor, display_row, &bp, state, cx);
 3007
 3008                    let button = prepaint_gutter_button(
 3009                        button,
 3010                        display_row,
 3011                        line_height,
 3012                        gutter_dimensions,
 3013                        scroll_position,
 3014                        gutter_hitbox,
 3015                        display_hunks,
 3016                        window,
 3017                        cx,
 3018                    );
 3019                    Some(button)
 3020                })
 3021                .collect_vec()
 3022        })
 3023    }
 3024
 3025    #[allow(clippy::too_many_arguments)]
 3026    fn layout_run_indicators(
 3027        &self,
 3028        line_height: Pixels,
 3029        range: Range<DisplayRow>,
 3030        row_infos: &[RowInfo],
 3031        scroll_position: gpui::Point<ScrollOffset>,
 3032        gutter_dimensions: &GutterDimensions,
 3033        gutter_hitbox: &Hitbox,
 3034        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 3035        snapshot: &EditorSnapshot,
 3036        breakpoints: &mut HashMap<DisplayRow, (Anchor, Breakpoint, Option<BreakpointSessionState>)>,
 3037        window: &mut Window,
 3038        cx: &mut App,
 3039    ) -> Vec<AnyElement> {
 3040        self.editor.update(cx, |editor, cx| {
 3041            let active_task_indicator_row =
 3042                // TODO: add edit button on the right side of each row in the context menu
 3043                if let Some(crate::CodeContextMenu::CodeActions(CodeActionsMenu {
 3044                    deployed_from,
 3045                    actions,
 3046                    ..
 3047                })) = editor.context_menu.borrow().as_ref()
 3048                {
 3049                    actions
 3050                        .tasks()
 3051                        .map(|tasks| tasks.position.to_display_point(snapshot).row())
 3052                        .or_else(|| match deployed_from {
 3053                            Some(CodeActionSource::Indicator(row)) => Some(*row),
 3054                            _ => None,
 3055                        })
 3056                } else {
 3057                    None
 3058                };
 3059
 3060            let offset_range_start =
 3061                snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left);
 3062
 3063            let offset_range_end =
 3064                snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 3065
 3066            editor
 3067                .tasks
 3068                .iter()
 3069                .filter_map(|(_, tasks)| {
 3070                    let multibuffer_point = tasks.offset.to_point(&snapshot.buffer_snapshot());
 3071                    if multibuffer_point < offset_range_start
 3072                        || multibuffer_point > offset_range_end
 3073                    {
 3074                        return None;
 3075                    }
 3076                    let multibuffer_row = MultiBufferRow(multibuffer_point.row);
 3077                    let buffer_folded = snapshot
 3078                        .buffer_snapshot()
 3079                        .buffer_line_for_row(multibuffer_row)
 3080                        .map(|(buffer_snapshot, _)| buffer_snapshot.remote_id())
 3081                        .map(|buffer_id| editor.is_buffer_folded(buffer_id, cx))
 3082                        .unwrap_or(false);
 3083                    if buffer_folded {
 3084                        return None;
 3085                    }
 3086
 3087                    if snapshot.is_line_folded(multibuffer_row) {
 3088                        // Skip folded indicators, unless it's the starting line of a fold.
 3089                        if multibuffer_row
 3090                            .0
 3091                            .checked_sub(1)
 3092                            .is_some_and(|previous_row| {
 3093                                snapshot.is_line_folded(MultiBufferRow(previous_row))
 3094                            })
 3095                        {
 3096                            return None;
 3097                        }
 3098                    }
 3099
 3100                    let display_row = multibuffer_point.to_display_point(snapshot).row();
 3101                    if !range.contains(&display_row) {
 3102                        return None;
 3103                    }
 3104                    if row_infos
 3105                        .get((display_row - range.start).0 as usize)
 3106                        .is_some_and(|row_info| row_info.expand_info.is_some())
 3107                    {
 3108                        return None;
 3109                    }
 3110
 3111                    let button = editor.render_run_indicator(
 3112                        &self.style,
 3113                        Some(display_row) == active_task_indicator_row,
 3114                        display_row,
 3115                        breakpoints.remove(&display_row),
 3116                        cx,
 3117                    );
 3118
 3119                    let button = prepaint_gutter_button(
 3120                        button,
 3121                        display_row,
 3122                        line_height,
 3123                        gutter_dimensions,
 3124                        scroll_position,
 3125                        gutter_hitbox,
 3126                        display_hunks,
 3127                        window,
 3128                        cx,
 3129                    );
 3130                    Some(button)
 3131                })
 3132                .collect_vec()
 3133        })
 3134    }
 3135
 3136    fn layout_expand_toggles(
 3137        &self,
 3138        gutter_hitbox: &Hitbox,
 3139        gutter_dimensions: GutterDimensions,
 3140        em_width: Pixels,
 3141        line_height: Pixels,
 3142        scroll_position: gpui::Point<ScrollOffset>,
 3143        buffer_rows: &[RowInfo],
 3144        window: &mut Window,
 3145        cx: &mut App,
 3146    ) -> Vec<Option<(AnyElement, gpui::Point<Pixels>)>> {
 3147        if self.editor.read(cx).disable_expand_excerpt_buttons {
 3148            return vec![];
 3149        }
 3150
 3151        let editor_font_size = self.style.text.font_size.to_pixels(window.rem_size()) * 1.2;
 3152
 3153        let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
 3154
 3155        let max_line_number_length = self
 3156            .editor
 3157            .read(cx)
 3158            .buffer()
 3159            .read(cx)
 3160            .snapshot(cx)
 3161            .widest_line_number()
 3162            .ilog10()
 3163            + 1;
 3164
 3165        let git_gutter_width = Self::gutter_strip_width(line_height)
 3166            + gutter_dimensions
 3167                .git_blame_entries_width
 3168                .unwrap_or_default();
 3169        let available_width = gutter_dimensions.left_padding - git_gutter_width;
 3170
 3171        buffer_rows
 3172            .iter()
 3173            .enumerate()
 3174            .map(|(ix, row_info)| {
 3175                let ExpandInfo {
 3176                    excerpt_id,
 3177                    direction,
 3178                } = row_info.expand_info?;
 3179
 3180                let icon_name = match direction {
 3181                    ExpandExcerptDirection::Up => IconName::ExpandUp,
 3182                    ExpandExcerptDirection::Down => IconName::ExpandDown,
 3183                    ExpandExcerptDirection::UpAndDown => IconName::ExpandVertical,
 3184                };
 3185
 3186                let editor = self.editor.clone();
 3187                let is_wide = max_line_number_length
 3188                    >= EditorSettings::get_global(cx).gutter.min_line_number_digits as u32
 3189                    && row_info
 3190                        .buffer_row
 3191                        .is_some_and(|row| (row + 1).ilog10() + 1 == max_line_number_length)
 3192                    || gutter_dimensions.right_padding == px(0.);
 3193
 3194                let width = if is_wide {
 3195                    available_width - px(2.)
 3196                } else {
 3197                    available_width + em_width - px(2.)
 3198                };
 3199
 3200                let toggle = IconButton::new(("expand", ix), icon_name)
 3201                    .icon_color(Color::Custom(cx.theme().colors().editor_line_number))
 3202                    .selected_icon_color(Color::Custom(cx.theme().colors().editor_foreground))
 3203                    .icon_size(IconSize::Custom(rems(editor_font_size / window.rem_size())))
 3204                    .width(width)
 3205                    .on_click(move |_, window, cx| {
 3206                        editor.update(cx, |editor, cx| {
 3207                            editor.expand_excerpt(excerpt_id, direction, window, cx);
 3208                        });
 3209                    })
 3210                    .tooltip(Tooltip::for_action_title(
 3211                        "Expand Excerpt",
 3212                        &crate::actions::ExpandExcerpts::default(),
 3213                    ))
 3214                    .into_any_element();
 3215
 3216                let position = point(
 3217                    git_gutter_width + px(1.),
 3218                    ix as f32 * line_height
 3219                        - Pixels::from(scroll_top % ScrollPixelOffset::from(line_height))
 3220                        + px(1.),
 3221                );
 3222                let origin = gutter_hitbox.origin + position;
 3223
 3224                Some((toggle, origin))
 3225            })
 3226            .collect()
 3227    }
 3228
 3229    fn calculate_relative_line_numbers(
 3230        &self,
 3231        snapshot: &EditorSnapshot,
 3232        rows: &Range<DisplayRow>,
 3233        relative_to: Option<DisplayRow>,
 3234        count_wrapped_lines: bool,
 3235    ) -> HashMap<DisplayRow, DisplayRowDelta> {
 3236        let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
 3237        let Some(relative_to) = relative_to else {
 3238            return relative_rows;
 3239        };
 3240
 3241        let start = rows.start.min(relative_to);
 3242        let end = rows.end.max(relative_to);
 3243
 3244        let buffer_rows = snapshot
 3245            .row_infos(start)
 3246            .take(1 + end.minus(start) as usize)
 3247            .collect::<Vec<_>>();
 3248
 3249        let head_idx = relative_to.minus(start);
 3250        let mut delta = 1;
 3251        let mut i = head_idx + 1;
 3252        let should_count_line = |row_info: &RowInfo| {
 3253            if count_wrapped_lines {
 3254                row_info.buffer_row.is_some() || row_info.wrapped_buffer_row.is_some()
 3255            } else {
 3256                row_info.buffer_row.is_some()
 3257            }
 3258        };
 3259        while i < buffer_rows.len() as u32 {
 3260            if should_count_line(&buffer_rows[i as usize]) {
 3261                if rows.contains(&DisplayRow(i + start.0)) {
 3262                    relative_rows.insert(DisplayRow(i + start.0), delta);
 3263                }
 3264                delta += 1;
 3265            }
 3266            i += 1;
 3267        }
 3268        delta = 1;
 3269        i = head_idx.min(buffer_rows.len().saturating_sub(1) as u32);
 3270        while i > 0 && buffer_rows[i as usize].buffer_row.is_none() && !count_wrapped_lines {
 3271            i -= 1;
 3272        }
 3273
 3274        while i > 0 {
 3275            i -= 1;
 3276            if should_count_line(&buffer_rows[i as usize]) {
 3277                if rows.contains(&DisplayRow(i + start.0)) {
 3278                    relative_rows.insert(DisplayRow(i + start.0), delta);
 3279                }
 3280                delta += 1;
 3281            }
 3282        }
 3283
 3284        relative_rows
 3285    }
 3286
 3287    fn layout_line_numbers(
 3288        &self,
 3289        gutter_hitbox: Option<&Hitbox>,
 3290        gutter_dimensions: GutterDimensions,
 3291        line_height: Pixels,
 3292        scroll_position: gpui::Point<ScrollOffset>,
 3293        rows: Range<DisplayRow>,
 3294        buffer_rows: &[RowInfo],
 3295        active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
 3296        newest_selection_head: Option<DisplayPoint>,
 3297        snapshot: &EditorSnapshot,
 3298        window: &mut Window,
 3299        cx: &mut App,
 3300    ) -> Arc<HashMap<MultiBufferRow, LineNumberLayout>> {
 3301        let include_line_numbers = snapshot
 3302            .show_line_numbers
 3303            .unwrap_or_else(|| EditorSettings::get_global(cx).gutter.line_numbers);
 3304        if !include_line_numbers {
 3305            return Arc::default();
 3306        }
 3307
 3308        let (newest_selection_head, relative) = self.editor.update(cx, |editor, cx| {
 3309            let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
 3310                let newest = editor
 3311                    .selections
 3312                    .newest::<Point>(&editor.display_snapshot(cx));
 3313                SelectionLayout::new(
 3314                    newest,
 3315                    editor.selections.line_mode(),
 3316                    editor.cursor_offset_on_selection,
 3317                    editor.cursor_shape,
 3318                    &snapshot.display_snapshot,
 3319                    true,
 3320                    true,
 3321                    None,
 3322                )
 3323                .head
 3324            });
 3325            let relative = editor.relative_line_numbers(cx);
 3326            (newest_selection_head, relative)
 3327        });
 3328
 3329        let relative_line_numbers_enabled = relative.enabled();
 3330        let relative_to = relative_line_numbers_enabled.then(|| newest_selection_head.row());
 3331
 3332        let relative_rows =
 3333            self.calculate_relative_line_numbers(snapshot, &rows, relative_to, relative.wrapped());
 3334        let mut line_number = String::new();
 3335        let segments = buffer_rows.iter().enumerate().flat_map(|(ix, row_info)| {
 3336            let display_row = DisplayRow(rows.start.0 + ix as u32);
 3337            line_number.clear();
 3338            let non_relative_number = if relative.wrapped() {
 3339                row_info.buffer_row.or(row_info.wrapped_buffer_row)? + 1
 3340            } else if self.editor.read(cx).use_base_text_line_numbers {
 3341                row_info.base_text_row?.0 + 1
 3342            } else {
 3343                row_info.buffer_row? + 1
 3344            };
 3345            let relative_number = relative_rows.get(&display_row);
 3346            if !(relative_line_numbers_enabled && relative_number.is_some())
 3347                && row_info
 3348                    .diff_status
 3349                    .is_some_and(|status| status.is_deleted())
 3350                && !self.editor.read(cx).use_base_text_line_numbers
 3351            {
 3352                return None;
 3353            }
 3354
 3355            let number = relative_number.unwrap_or(&non_relative_number);
 3356            write!(&mut line_number, "{number}").unwrap();
 3357
 3358            let color = active_rows
 3359                .get(&display_row)
 3360                .map(|spec| {
 3361                    if spec.breakpoint {
 3362                        cx.theme().colors().debugger_accent
 3363                    } else {
 3364                        cx.theme().colors().editor_active_line_number
 3365                    }
 3366                })
 3367                .unwrap_or_else(|| cx.theme().colors().editor_line_number);
 3368            let shaped_line =
 3369                self.shape_line_number(SharedString::from(&line_number), color, window);
 3370            let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
 3371            let line_origin = gutter_hitbox.map(|hitbox| {
 3372                hitbox.origin
 3373                    + point(
 3374                        hitbox.size.width - shaped_line.width - gutter_dimensions.right_padding,
 3375                        ix as f32 * line_height
 3376                            - Pixels::from(scroll_top % ScrollPixelOffset::from(line_height)),
 3377                    )
 3378            });
 3379
 3380            #[cfg(not(test))]
 3381            let hitbox = line_origin.map(|line_origin| {
 3382                window.insert_hitbox(
 3383                    Bounds::new(line_origin, size(shaped_line.width, line_height)),
 3384                    HitboxBehavior::Normal,
 3385                )
 3386            });
 3387            #[cfg(test)]
 3388            let hitbox = {
 3389                let _ = line_origin;
 3390                None
 3391            };
 3392
 3393            let segment = LineNumberSegment {
 3394                shaped_line,
 3395                hitbox,
 3396            };
 3397
 3398            let buffer_row = DisplayPoint::new(display_row, 0).to_point(snapshot).row;
 3399            let multi_buffer_row = MultiBufferRow(buffer_row);
 3400
 3401            Some((multi_buffer_row, segment))
 3402        });
 3403
 3404        let mut line_numbers: HashMap<MultiBufferRow, LineNumberLayout> = HashMap::default();
 3405        for (buffer_row, segment) in segments {
 3406            line_numbers
 3407                .entry(buffer_row)
 3408                .or_insert_with(|| LineNumberLayout {
 3409                    segments: Default::default(),
 3410                })
 3411                .segments
 3412                .push(segment);
 3413        }
 3414        Arc::new(line_numbers)
 3415    }
 3416
 3417    fn layout_crease_toggles(
 3418        &self,
 3419        rows: Range<DisplayRow>,
 3420        row_infos: &[RowInfo],
 3421        active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
 3422        snapshot: &EditorSnapshot,
 3423        window: &mut Window,
 3424        cx: &mut App,
 3425    ) -> Vec<Option<AnyElement>> {
 3426        let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
 3427            && snapshot.mode.is_full()
 3428            && self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
 3429        if include_fold_statuses {
 3430            row_infos
 3431                .iter()
 3432                .enumerate()
 3433                .map(|(ix, info)| {
 3434                    if info.expand_info.is_some() {
 3435                        return None;
 3436                    }
 3437                    let row = info.multibuffer_row?;
 3438                    let display_row = DisplayRow(rows.start.0 + ix as u32);
 3439                    let active = active_rows.contains_key(&display_row);
 3440
 3441                    snapshot.render_crease_toggle(row, active, self.editor.clone(), window, cx)
 3442                })
 3443                .collect()
 3444        } else {
 3445            Vec::new()
 3446        }
 3447    }
 3448
 3449    fn layout_crease_trailers(
 3450        &self,
 3451        buffer_rows: impl IntoIterator<Item = RowInfo>,
 3452        snapshot: &EditorSnapshot,
 3453        window: &mut Window,
 3454        cx: &mut App,
 3455    ) -> Vec<Option<AnyElement>> {
 3456        buffer_rows
 3457            .into_iter()
 3458            .map(|row_info| {
 3459                if row_info.expand_info.is_some() {
 3460                    return None;
 3461                }
 3462                if let Some(row) = row_info.multibuffer_row {
 3463                    snapshot.render_crease_trailer(row, window, cx)
 3464                } else {
 3465                    None
 3466                }
 3467            })
 3468            .collect()
 3469    }
 3470
 3471    fn bg_segments_per_row(
 3472        rows: Range<DisplayRow>,
 3473        selections: &[(PlayerColor, Vec<SelectionLayout>)],
 3474        highlight_ranges: &[(Range<DisplayPoint>, Hsla)],
 3475        base_background: Hsla,
 3476    ) -> Vec<Vec<(Range<DisplayPoint>, Hsla)>> {
 3477        if rows.start >= rows.end {
 3478            return Vec::new();
 3479        }
 3480        if !base_background.is_opaque() {
 3481            // We don't actually know what color is behind this editor.
 3482            return Vec::new();
 3483        }
 3484        let highlight_iter = highlight_ranges.iter().cloned();
 3485        let selection_iter = selections.iter().flat_map(|(player_color, layouts)| {
 3486            let color = player_color.selection;
 3487            layouts.iter().filter_map(move |selection_layout| {
 3488                if selection_layout.range.start != selection_layout.range.end {
 3489                    Some((selection_layout.range.clone(), color))
 3490                } else {
 3491                    None
 3492                }
 3493            })
 3494        });
 3495        let mut per_row_map = vec![Vec::new(); rows.len()];
 3496        for (range, color) in highlight_iter.chain(selection_iter) {
 3497            let covered_rows = if range.end.column() == 0 {
 3498                cmp::max(range.start.row(), rows.start)..cmp::min(range.end.row(), rows.end)
 3499            } else {
 3500                cmp::max(range.start.row(), rows.start)
 3501                    ..cmp::min(range.end.row().next_row(), rows.end)
 3502            };
 3503            for row in covered_rows.iter_rows() {
 3504                let seg_start = if row == range.start.row() {
 3505                    range.start
 3506                } else {
 3507                    DisplayPoint::new(row, 0)
 3508                };
 3509                let seg_end = if row == range.end.row() && range.end.column() != 0 {
 3510                    range.end
 3511                } else {
 3512                    DisplayPoint::new(row, u32::MAX)
 3513                };
 3514                let ix = row.minus(rows.start) as usize;
 3515                debug_assert!(row >= rows.start && row < rows.end);
 3516                debug_assert!(ix < per_row_map.len());
 3517                per_row_map[ix].push((seg_start..seg_end, color));
 3518            }
 3519        }
 3520        for row_segments in per_row_map.iter_mut() {
 3521            if row_segments.is_empty() {
 3522                continue;
 3523            }
 3524            let segments = mem::take(row_segments);
 3525            let merged = Self::merge_overlapping_ranges(segments, base_background);
 3526            *row_segments = merged;
 3527        }
 3528        per_row_map
 3529    }
 3530
 3531    /// Merge overlapping ranges by splitting at all range boundaries and blending colors where
 3532    /// multiple ranges overlap. The result contains non-overlapping ranges ordered from left to right.
 3533    ///
 3534    /// Expects `start.row() == end.row()` for each range.
 3535    fn merge_overlapping_ranges(
 3536        ranges: Vec<(Range<DisplayPoint>, Hsla)>,
 3537        base_background: Hsla,
 3538    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
 3539        struct Boundary {
 3540            pos: DisplayPoint,
 3541            is_start: bool,
 3542            index: usize,
 3543            color: Hsla,
 3544        }
 3545
 3546        let mut boundaries: SmallVec<[Boundary; 16]> = SmallVec::with_capacity(ranges.len() * 2);
 3547        for (index, (range, color)) in ranges.iter().enumerate() {
 3548            debug_assert!(
 3549                range.start.row() == range.end.row(),
 3550                "expects single-row ranges"
 3551            );
 3552            if range.start < range.end {
 3553                boundaries.push(Boundary {
 3554                    pos: range.start,
 3555                    is_start: true,
 3556                    index,
 3557                    color: *color,
 3558                });
 3559                boundaries.push(Boundary {
 3560                    pos: range.end,
 3561                    is_start: false,
 3562                    index,
 3563                    color: *color,
 3564                });
 3565            }
 3566        }
 3567
 3568        if boundaries.is_empty() {
 3569            return Vec::new();
 3570        }
 3571
 3572        boundaries
 3573            .sort_unstable_by(|a, b| a.pos.cmp(&b.pos).then_with(|| a.is_start.cmp(&b.is_start)));
 3574
 3575        let mut processed_ranges: Vec<(Range<DisplayPoint>, Hsla)> = Vec::new();
 3576        let mut active_ranges: SmallVec<[(usize, Hsla); 8]> = SmallVec::new();
 3577
 3578        let mut i = 0;
 3579        let mut start_pos = boundaries[0].pos;
 3580
 3581        let boundaries_len = boundaries.len();
 3582        while i < boundaries_len {
 3583            let current_boundary_pos = boundaries[i].pos;
 3584            if start_pos < current_boundary_pos {
 3585                if !active_ranges.is_empty() {
 3586                    let mut color = base_background;
 3587                    for &(_, c) in &active_ranges {
 3588                        color = Hsla::blend(color, c);
 3589                    }
 3590                    if let Some((last_range, last_color)) = processed_ranges.last_mut() {
 3591                        if *last_color == color && last_range.end == start_pos {
 3592                            last_range.end = current_boundary_pos;
 3593                        } else {
 3594                            processed_ranges.push((start_pos..current_boundary_pos, color));
 3595                        }
 3596                    } else {
 3597                        processed_ranges.push((start_pos..current_boundary_pos, color));
 3598                    }
 3599                }
 3600            }
 3601            while i < boundaries_len && boundaries[i].pos == current_boundary_pos {
 3602                let active_range = &boundaries[i];
 3603                if active_range.is_start {
 3604                    let idx = active_range.index;
 3605                    let pos = active_ranges
 3606                        .binary_search_by_key(&idx, |(i, _)| *i)
 3607                        .unwrap_or_else(|p| p);
 3608                    active_ranges.insert(pos, (idx, active_range.color));
 3609                } else {
 3610                    let idx = active_range.index;
 3611                    if let Ok(pos) = active_ranges.binary_search_by_key(&idx, |(i, _)| *i) {
 3612                        active_ranges.remove(pos);
 3613                    }
 3614                }
 3615                i += 1;
 3616            }
 3617            start_pos = current_boundary_pos;
 3618        }
 3619
 3620        processed_ranges
 3621    }
 3622
 3623    fn layout_lines(
 3624        rows: Range<DisplayRow>,
 3625        snapshot: &EditorSnapshot,
 3626        style: &EditorStyle,
 3627        editor_width: Pixels,
 3628        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 3629        bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
 3630        window: &mut Window,
 3631        cx: &mut App,
 3632    ) -> Vec<LineWithInvisibles> {
 3633        if rows.start >= rows.end {
 3634            return Vec::new();
 3635        }
 3636
 3637        // Show the placeholder when the editor is empty
 3638        if snapshot.is_empty() {
 3639            let font_size = style.text.font_size.to_pixels(window.rem_size());
 3640            let placeholder_color = cx.theme().colors().text_placeholder;
 3641            let placeholder_text = snapshot.placeholder_text();
 3642
 3643            let placeholder_lines = placeholder_text
 3644                .as_ref()
 3645                .map_or(Vec::new(), |text| text.split('\n').collect::<Vec<_>>());
 3646
 3647            let placeholder_line_count = placeholder_lines.len();
 3648
 3649            placeholder_lines
 3650                .into_iter()
 3651                .skip(rows.start.0 as usize)
 3652                .chain(iter::repeat(""))
 3653                .take(cmp::max(rows.len(), placeholder_line_count))
 3654                .map(move |line| {
 3655                    let run = TextRun {
 3656                        len: line.len(),
 3657                        font: style.text.font(),
 3658                        color: placeholder_color,
 3659                        ..Default::default()
 3660                    };
 3661                    let line = window.text_system().shape_line(
 3662                        line.to_string().into(),
 3663                        font_size,
 3664                        &[run],
 3665                        None,
 3666                    );
 3667                    LineWithInvisibles {
 3668                        width: line.width,
 3669                        len: line.len,
 3670                        fragments: smallvec![LineFragment::Text(line)],
 3671                        invisibles: Vec::new(),
 3672                        font_size,
 3673                    }
 3674                })
 3675                .collect()
 3676        } else {
 3677            let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
 3678            LineWithInvisibles::from_chunks(
 3679                chunks,
 3680                style,
 3681                MAX_LINE_LEN,
 3682                rows.len(),
 3683                &snapshot.mode,
 3684                editor_width,
 3685                is_row_soft_wrapped,
 3686                bg_segments_per_row,
 3687                window,
 3688                cx,
 3689            )
 3690        }
 3691    }
 3692
 3693    fn prepaint_lines(
 3694        &self,
 3695        start_row: DisplayRow,
 3696        line_layouts: &mut [LineWithInvisibles],
 3697        line_height: Pixels,
 3698        scroll_position: gpui::Point<ScrollOffset>,
 3699        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 3700        content_origin: gpui::Point<Pixels>,
 3701        window: &mut Window,
 3702        cx: &mut App,
 3703    ) -> SmallVec<[AnyElement; 1]> {
 3704        let mut line_elements = SmallVec::new();
 3705        for (ix, line) in line_layouts.iter_mut().enumerate() {
 3706            let row = start_row + DisplayRow(ix as u32);
 3707            line.prepaint(
 3708                line_height,
 3709                scroll_position,
 3710                scroll_pixel_position,
 3711                row,
 3712                content_origin,
 3713                &mut line_elements,
 3714                window,
 3715                cx,
 3716            );
 3717        }
 3718        line_elements
 3719    }
 3720
 3721    fn render_block(
 3722        &self,
 3723        block: &Block,
 3724        available_width: AvailableSpace,
 3725        block_id: BlockId,
 3726        block_row_start: DisplayRow,
 3727        snapshot: &EditorSnapshot,
 3728        text_x: Pixels,
 3729        rows: &Range<DisplayRow>,
 3730        line_layouts: &[LineWithInvisibles],
 3731        editor_margins: &EditorMargins,
 3732        line_height: Pixels,
 3733        em_width: Pixels,
 3734        text_hitbox: &Hitbox,
 3735        editor_width: Pixels,
 3736        scroll_width: &mut Pixels,
 3737        resized_blocks: &mut HashMap<CustomBlockId, u32>,
 3738        row_block_types: &mut HashMap<DisplayRow, bool>,
 3739        selections: &[Selection<Point>],
 3740        selected_buffer_ids: &Vec<BufferId>,
 3741        latest_selection_anchors: &HashMap<BufferId, Anchor>,
 3742        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 3743        sticky_header_excerpt_id: Option<ExcerptId>,
 3744        block_resize_offset: &mut i32,
 3745        window: &mut Window,
 3746        cx: &mut App,
 3747    ) -> Option<(AnyElement, Size<Pixels>, DisplayRow, Pixels)> {
 3748        let mut x_position = None;
 3749        let mut element = match block {
 3750            Block::Custom(custom) => {
 3751                let block_start = custom.start().to_point(&snapshot.buffer_snapshot());
 3752                let block_end = custom.end().to_point(&snapshot.buffer_snapshot());
 3753                if block.place_near() && snapshot.is_line_folded(MultiBufferRow(block_start.row)) {
 3754                    return None;
 3755                }
 3756                let align_to = block_start.to_display_point(snapshot);
 3757                let x_and_width = |layout: &LineWithInvisibles| {
 3758                    Some((
 3759                        text_x + layout.x_for_index(align_to.column() as usize),
 3760                        text_x + layout.width,
 3761                    ))
 3762                };
 3763                let line_ix = align_to.row().0.checked_sub(rows.start.0);
 3764                x_position =
 3765                    if let Some(layout) = line_ix.and_then(|ix| line_layouts.get(ix as usize)) {
 3766                        x_and_width(layout)
 3767                    } else {
 3768                        x_and_width(&layout_line(
 3769                            align_to.row(),
 3770                            snapshot,
 3771                            &self.style,
 3772                            editor_width,
 3773                            is_row_soft_wrapped,
 3774                            window,
 3775                            cx,
 3776                        ))
 3777                    };
 3778
 3779                let anchor_x = x_position.unwrap().0;
 3780
 3781                let selected = selections
 3782                    .binary_search_by(|selection| {
 3783                        if selection.end <= block_start {
 3784                            Ordering::Less
 3785                        } else if selection.start >= block_end {
 3786                            Ordering::Greater
 3787                        } else {
 3788                            Ordering::Equal
 3789                        }
 3790                    })
 3791                    .is_ok();
 3792
 3793                div()
 3794                    .size_full()
 3795                    .child(custom.render(&mut BlockContext {
 3796                        window,
 3797                        app: cx,
 3798                        anchor_x,
 3799                        margins: editor_margins,
 3800                        line_height,
 3801                        em_width,
 3802                        block_id,
 3803                        selected,
 3804                        max_width: text_hitbox.size.width.max(*scroll_width),
 3805                        editor_style: &self.style,
 3806                    }))
 3807                    .into_any()
 3808            }
 3809
 3810            Block::FoldedBuffer {
 3811                first_excerpt,
 3812                height,
 3813                ..
 3814            } => {
 3815                let selected = selected_buffer_ids.contains(&first_excerpt.buffer_id);
 3816                let result = v_flex().id(block_id).w_full().pr(editor_margins.right);
 3817
 3818                let jump_data = header_jump_data(
 3819                    snapshot,
 3820                    block_row_start,
 3821                    *height,
 3822                    first_excerpt,
 3823                    latest_selection_anchors,
 3824                );
 3825                result
 3826                    .child(self.render_buffer_header(
 3827                        first_excerpt,
 3828                        true,
 3829                        selected,
 3830                        false,
 3831                        jump_data,
 3832                        window,
 3833                        cx,
 3834                    ))
 3835                    .into_any_element()
 3836            }
 3837
 3838            Block::ExcerptBoundary { .. } => {
 3839                let color = cx.theme().colors().clone();
 3840                let mut result = v_flex().id(block_id).w_full();
 3841
 3842                result = result.child(
 3843                    h_flex().relative().child(
 3844                        div()
 3845                            .top(line_height / 2.)
 3846                            .absolute()
 3847                            .w_full()
 3848                            .h_px()
 3849                            .bg(color.border_variant),
 3850                    ),
 3851                );
 3852
 3853                result.into_any()
 3854            }
 3855
 3856            Block::BufferHeader { excerpt, height } => {
 3857                let mut result = v_flex().id(block_id).w_full();
 3858
 3859                let jump_data = header_jump_data(
 3860                    snapshot,
 3861                    block_row_start,
 3862                    *height,
 3863                    excerpt,
 3864                    latest_selection_anchors,
 3865                );
 3866
 3867                if sticky_header_excerpt_id != Some(excerpt.id) {
 3868                    let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
 3869
 3870                    result = result.child(div().pr(editor_margins.right).child(
 3871                        self.render_buffer_header(
 3872                            excerpt, false, selected, false, jump_data, window, cx,
 3873                        ),
 3874                    ));
 3875                } else {
 3876                    result =
 3877                        result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
 3878                }
 3879
 3880                result.into_any()
 3881            }
 3882        };
 3883
 3884        // Discover the element's content height, then round up to the nearest multiple of line height.
 3885        let preliminary_size = element.layout_as_root(
 3886            size(available_width, AvailableSpace::MinContent),
 3887            window,
 3888            cx,
 3889        );
 3890        let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
 3891        let final_size = if preliminary_size.height == quantized_height {
 3892            preliminary_size
 3893        } else {
 3894            element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
 3895        };
 3896        let mut element_height_in_lines = ((final_size.height / line_height).ceil() as u32).max(1);
 3897
 3898        let effective_row_start = block_row_start.0 as i32 + *block_resize_offset;
 3899        debug_assert!(effective_row_start >= 0);
 3900        let mut row = DisplayRow(effective_row_start.max(0) as u32);
 3901
 3902        let mut x_offset = px(0.);
 3903        let mut is_block = true;
 3904
 3905        if let BlockId::Custom(custom_block_id) = block_id
 3906            && block.has_height()
 3907        {
 3908            if block.place_near()
 3909                && let Some((x_target, line_width)) = x_position
 3910            {
 3911                let margin = em_width * 2;
 3912                if line_width + final_size.width + margin
 3913                    < editor_width + editor_margins.gutter.full_width()
 3914                    && !row_block_types.contains_key(&(row - 1))
 3915                    && element_height_in_lines == 1
 3916                {
 3917                    x_offset = line_width + margin;
 3918                    row = row - 1;
 3919                    is_block = false;
 3920                    element_height_in_lines = 0;
 3921                    row_block_types.insert(row, is_block);
 3922                } else {
 3923                    let max_offset =
 3924                        editor_width + editor_margins.gutter.full_width() - final_size.width;
 3925                    let min_offset = (x_target + em_width - final_size.width)
 3926                        .max(editor_margins.gutter.full_width());
 3927                    x_offset = x_target.min(max_offset).max(min_offset);
 3928                }
 3929            };
 3930            if element_height_in_lines != block.height() {
 3931                *block_resize_offset += element_height_in_lines as i32 - block.height() as i32;
 3932                resized_blocks.insert(custom_block_id, element_height_in_lines);
 3933            }
 3934        }
 3935        for i in 0..element_height_in_lines {
 3936            row_block_types.insert(row + i, is_block);
 3937        }
 3938
 3939        Some((element, final_size, row, x_offset))
 3940    }
 3941
 3942    fn render_buffer_header(
 3943        &self,
 3944        for_excerpt: &ExcerptInfo,
 3945        is_folded: bool,
 3946        is_selected: bool,
 3947        is_sticky: bool,
 3948        jump_data: JumpData,
 3949        window: &mut Window,
 3950        cx: &mut App,
 3951    ) -> impl IntoElement {
 3952        let editor = self.editor.read(cx);
 3953        let multi_buffer = editor.buffer.read(cx);
 3954        let is_read_only = self.editor.read(cx).read_only(cx);
 3955
 3956        let file_status = multi_buffer
 3957            .all_diff_hunks_expanded()
 3958            .then(|| editor.status_for_buffer_id(for_excerpt.buffer_id, cx))
 3959            .flatten();
 3960        let indicator = multi_buffer
 3961            .buffer(for_excerpt.buffer_id)
 3962            .and_then(|buffer| {
 3963                let buffer = buffer.read(cx);
 3964                let indicator_color = match (buffer.has_conflict(), buffer.is_dirty()) {
 3965                    (true, _) => Some(Color::Warning),
 3966                    (_, true) => Some(Color::Accent),
 3967                    (false, false) => None,
 3968                };
 3969                indicator_color.map(|indicator_color| Indicator::dot().color(indicator_color))
 3970            });
 3971
 3972        let include_root = editor
 3973            .project
 3974            .as_ref()
 3975            .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 3976            .unwrap_or_default();
 3977        let file = for_excerpt.buffer.file();
 3978        let can_open_excerpts = Editor::can_open_excerpts_in_file(file);
 3979        let path_style = file.map(|file| file.path_style(cx));
 3980        let relative_path = for_excerpt.buffer.resolve_file_path(include_root, cx);
 3981        let (parent_path, filename) = if let Some(path) = &relative_path {
 3982            if let Some(path_style) = path_style {
 3983                let (dir, file_name) = path_style.split(path);
 3984                (dir.map(|dir| dir.to_owned()), Some(file_name.to_owned()))
 3985            } else {
 3986                (None, Some(path.clone()))
 3987            }
 3988        } else {
 3989            (None, None)
 3990        };
 3991        let focus_handle = editor.focus_handle(cx);
 3992        let colors = cx.theme().colors();
 3993
 3994        let header = div()
 3995            .p_1()
 3996            .w_full()
 3997            .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
 3998            .child(
 3999                h_flex()
 4000                    .size_full()
 4001                    .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
 4002                    .pl_1()
 4003                    .pr_2()
 4004                    .rounded_sm()
 4005                    .gap_1p5()
 4006                    .when(is_sticky, |el| el.shadow_md())
 4007                    .border_1()
 4008                    .map(|border| {
 4009                        let border_color = if is_selected
 4010                            && is_folded
 4011                            && focus_handle.contains_focused(window, cx)
 4012                        {
 4013                            colors.border_focused
 4014                        } else {
 4015                            colors.border
 4016                        };
 4017                        border.border_color(border_color)
 4018                    })
 4019                    .bg(colors.editor_subheader_background)
 4020                    .hover(|style| style.bg(colors.element_hover))
 4021                    .map(|header| {
 4022                        let editor = self.editor.clone();
 4023                        let buffer_id = for_excerpt.buffer_id;
 4024                        let toggle_chevron_icon =
 4025                            FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
 4026                        let button_size = rems_from_px(28.);
 4027
 4028                        header.child(
 4029                            div()
 4030                                .hover(|style| style.bg(colors.element_selected))
 4031                                .rounded_xs()
 4032                                .child(
 4033                                    ButtonLike::new("toggle-buffer-fold")
 4034                                        .style(ButtonStyle::Transparent)
 4035                                        .height(button_size.into())
 4036                                        .width(button_size)
 4037                                        .children(toggle_chevron_icon)
 4038                                        .tooltip({
 4039                                            let focus_handle = focus_handle.clone();
 4040                                            let is_folded_for_tooltip = is_folded;
 4041                                            move |_window, cx| {
 4042                                                Tooltip::with_meta_in(
 4043                                                    if is_folded_for_tooltip {
 4044                                                        "Unfold Excerpt"
 4045                                                    } else {
 4046                                                        "Fold Excerpt"
 4047                                                    },
 4048                                                    Some(&ToggleFold),
 4049                                                    format!(
 4050                                                        "{} to toggle all",
 4051                                                        text_for_keystroke(
 4052                                                            &Modifiers::alt(),
 4053                                                            "click",
 4054                                                            cx
 4055                                                        )
 4056                                                    ),
 4057                                                    &focus_handle,
 4058                                                    cx,
 4059                                                )
 4060                                            }
 4061                                        })
 4062                                        .on_click(move |event, window, cx| {
 4063                                            if event.modifiers().alt {
 4064                                                // Alt+click toggles all buffers
 4065                                                editor.update(cx, |editor, cx| {
 4066                                                    editor.toggle_fold_all(
 4067                                                        &ToggleFoldAll,
 4068                                                        window,
 4069                                                        cx,
 4070                                                    );
 4071                                                });
 4072                                            } else {
 4073                                                // Regular click toggles single buffer
 4074                                                if is_folded {
 4075                                                    editor.update(cx, |editor, cx| {
 4076                                                        editor.unfold_buffer(buffer_id, cx);
 4077                                                    });
 4078                                                } else {
 4079                                                    editor.update(cx, |editor, cx| {
 4080                                                        editor.fold_buffer(buffer_id, cx);
 4081                                                    });
 4082                                                }
 4083                                            }
 4084                                        }),
 4085                                ),
 4086                        )
 4087                    })
 4088                    .children(
 4089                        editor
 4090                            .addons
 4091                            .values()
 4092                            .filter_map(|addon| {
 4093                                addon.render_buffer_header_controls(for_excerpt, window, cx)
 4094                            })
 4095                            .take(1),
 4096                    )
 4097                    .when(!is_read_only, |this| {
 4098                        this.child(
 4099                            h_flex()
 4100                                .size_3()
 4101                                .justify_center()
 4102                                .flex_shrink_0()
 4103                                .children(indicator),
 4104                        )
 4105                    })
 4106                    .child(
 4107                        h_flex()
 4108                            .cursor_pointer()
 4109                            .id("path_header_block")
 4110                            .min_w_0()
 4111                            .size_full()
 4112                            .justify_between()
 4113                            .overflow_hidden()
 4114                            .child(h_flex().min_w_0().flex_1().gap_0p5().map(|path_header| {
 4115                                let filename = filename
 4116                                    .map(SharedString::from)
 4117                                    .unwrap_or_else(|| "untitled".into());
 4118
 4119                                path_header
 4120                                    .when(ItemSettings::get_global(cx).file_icons, |el| {
 4121                                        let path = path::Path::new(filename.as_str());
 4122                                        let icon =
 4123                                            FileIcons::get_icon(path, cx).unwrap_or_default();
 4124
 4125                                        el.child(Icon::from_path(icon).color(Color::Muted))
 4126                                    })
 4127                                    .child(
 4128                                        ButtonLike::new("filename-button")
 4129                                            .child(
 4130                                                Label::new(filename)
 4131                                                    .single_line()
 4132                                                    .color(file_status_label_color(file_status))
 4133                                                    .when(
 4134                                                        file_status.is_some_and(|s| s.is_deleted()),
 4135                                                        |label| label.strikethrough(),
 4136                                                    ),
 4137                                            )
 4138                                            .on_click(window.listener_for(&self.editor, {
 4139                                                let jump_data = jump_data.clone();
 4140                                                move |editor, e: &ClickEvent, window, cx| {
 4141                                                    editor.open_excerpts_common(
 4142                                                        Some(jump_data.clone()),
 4143                                                        e.modifiers().secondary(),
 4144                                                        window,
 4145                                                        cx,
 4146                                                    );
 4147                                                }
 4148                                            })),
 4149                                    )
 4150                                    .when(!for_excerpt.buffer.capability.editable(), |el| {
 4151                                        el.child(Icon::new(IconName::FileLock).color(Color::Muted))
 4152                                    })
 4153                                    .when_some(parent_path, |then, path| {
 4154                                        then.child(Label::new(path).truncate().color(
 4155                                            if file_status.is_some_and(FileStatus::is_deleted) {
 4156                                                Color::Custom(colors.text_disabled)
 4157                                            } else {
 4158                                                Color::Custom(colors.text_muted)
 4159                                            },
 4160                                        ))
 4161                                    })
 4162                            }))
 4163                            .when(
 4164                                can_open_excerpts && is_selected && relative_path.is_some(),
 4165                                |el| {
 4166                                    el.child(
 4167                                        Button::new("open-file-button", "Open File")
 4168                                            .style(ButtonStyle::OutlinedGhost)
 4169                                            .key_binding(KeyBinding::for_action_in(
 4170                                                &OpenExcerpts,
 4171                                                &focus_handle,
 4172                                                cx,
 4173                                            ))
 4174                                            .on_click(window.listener_for(&self.editor, {
 4175                                                let jump_data = jump_data.clone();
 4176                                                move |editor, e: &ClickEvent, window, cx| {
 4177                                                    editor.open_excerpts_common(
 4178                                                        Some(jump_data.clone()),
 4179                                                        e.modifiers().secondary(),
 4180                                                        window,
 4181                                                        cx,
 4182                                                    );
 4183                                                }
 4184                                            })),
 4185                                    )
 4186                                },
 4187                            )
 4188                            .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 4189                            .on_click(window.listener_for(&self.editor, {
 4190                                let buffer_id = for_excerpt.buffer_id;
 4191                                move |editor, e: &ClickEvent, window, cx| {
 4192                                    if e.modifiers().alt {
 4193                                        editor.open_excerpts_common(
 4194                                            Some(jump_data.clone()),
 4195                                            e.modifiers().secondary(),
 4196                                            window,
 4197                                            cx,
 4198                                        );
 4199                                        return;
 4200                                    }
 4201
 4202                                    if is_folded {
 4203                                        editor.unfold_buffer(buffer_id, cx);
 4204                                    } else {
 4205                                        editor.fold_buffer(buffer_id, cx);
 4206                                    }
 4207                                }
 4208                            })),
 4209                    ),
 4210            );
 4211
 4212        let file = for_excerpt.buffer.file().cloned();
 4213        let editor = self.editor.clone();
 4214
 4215        right_click_menu("buffer-header-context-menu")
 4216            .trigger(move |_, _, _| header)
 4217            .menu(move |window, cx| {
 4218                let menu_context = focus_handle.clone();
 4219                let editor = editor.clone();
 4220                let file = file.clone();
 4221                ContextMenu::build(window, cx, move |mut menu, window, cx| {
 4222                    if let Some(file) = file
 4223                        && let Some(project) = editor.read(cx).project()
 4224                        && let Some(worktree) =
 4225                            project.read(cx).worktree_for_id(file.worktree_id(cx), cx)
 4226                    {
 4227                        let path_style = file.path_style(cx);
 4228                        let worktree = worktree.read(cx);
 4229                        let relative_path = file.path();
 4230                        let entry_for_path = worktree.entry_for_path(relative_path);
 4231                        let abs_path = entry_for_path.map(|e| {
 4232                            e.canonical_path.as_deref().map_or_else(
 4233                                || worktree.absolutize(relative_path),
 4234                                Path::to_path_buf,
 4235                            )
 4236                        });
 4237                        let has_relative_path = worktree.root_entry().is_some_and(Entry::is_dir);
 4238
 4239                        let parent_abs_path = abs_path
 4240                            .as_ref()
 4241                            .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
 4242                        let relative_path = has_relative_path
 4243                            .then_some(relative_path)
 4244                            .map(ToOwned::to_owned);
 4245
 4246                        let visible_in_project_panel =
 4247                            relative_path.is_some() && worktree.is_visible();
 4248                        let reveal_in_project_panel = entry_for_path
 4249                            .filter(|_| visible_in_project_panel)
 4250                            .map(|entry| entry.id);
 4251                        menu = menu
 4252                            .when_some(abs_path, |menu, abs_path| {
 4253                                menu.entry(
 4254                                    "Copy Path",
 4255                                    Some(Box::new(zed_actions::workspace::CopyPath)),
 4256                                    window.handler_for(&editor, move |_, _, cx| {
 4257                                        cx.write_to_clipboard(ClipboardItem::new_string(
 4258                                            abs_path.to_string_lossy().into_owned(),
 4259                                        ));
 4260                                    }),
 4261                                )
 4262                            })
 4263                            .when_some(relative_path, |menu, relative_path| {
 4264                                menu.entry(
 4265                                    "Copy Relative Path",
 4266                                    Some(Box::new(zed_actions::workspace::CopyRelativePath)),
 4267                                    window.handler_for(&editor, move |_, _, cx| {
 4268                                        cx.write_to_clipboard(ClipboardItem::new_string(
 4269                                            relative_path.display(path_style).to_string(),
 4270                                        ));
 4271                                    }),
 4272                                )
 4273                            })
 4274                            .when(
 4275                                reveal_in_project_panel.is_some() || parent_abs_path.is_some(),
 4276                                |menu| menu.separator(),
 4277                            )
 4278                            .when_some(reveal_in_project_panel, |menu, entry_id| {
 4279                                menu.entry(
 4280                                    "Reveal In Project Panel",
 4281                                    Some(Box::new(RevealInProjectPanel::default())),
 4282                                    window.handler_for(&editor, move |editor, _, cx| {
 4283                                        if let Some(project) = &mut editor.project {
 4284                                            project.update(cx, |_, cx| {
 4285                                                cx.emit(project::Event::RevealInProjectPanel(
 4286                                                    entry_id,
 4287                                                ))
 4288                                            });
 4289                                        }
 4290                                    }),
 4291                                )
 4292                            })
 4293                            .when_some(parent_abs_path, |menu, parent_abs_path| {
 4294                                menu.entry(
 4295                                    "Open in Terminal",
 4296                                    Some(Box::new(OpenInTerminal)),
 4297                                    window.handler_for(&editor, move |_, window, cx| {
 4298                                        window.dispatch_action(
 4299                                            OpenTerminal {
 4300                                                working_directory: parent_abs_path.clone(),
 4301                                            }
 4302                                            .boxed_clone(),
 4303                                            cx,
 4304                                        );
 4305                                    }),
 4306                                )
 4307                            });
 4308                    }
 4309
 4310                    menu.context(menu_context)
 4311                })
 4312            })
 4313    }
 4314
 4315    fn render_blocks(
 4316        &self,
 4317        rows: Range<DisplayRow>,
 4318        snapshot: &EditorSnapshot,
 4319        hitbox: &Hitbox,
 4320        text_hitbox: &Hitbox,
 4321        editor_width: Pixels,
 4322        scroll_width: &mut Pixels,
 4323        editor_margins: &EditorMargins,
 4324        em_width: Pixels,
 4325        text_x: Pixels,
 4326        line_height: Pixels,
 4327        line_layouts: &mut [LineWithInvisibles],
 4328        selections: &[Selection<Point>],
 4329        selected_buffer_ids: &Vec<BufferId>,
 4330        latest_selection_anchors: &HashMap<BufferId, Anchor>,
 4331        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 4332        sticky_header_excerpt_id: Option<ExcerptId>,
 4333        window: &mut Window,
 4334        cx: &mut App,
 4335    ) -> RenderBlocksOutput {
 4336        let (fixed_blocks, non_fixed_blocks) = snapshot
 4337            .blocks_in_range(rows.clone())
 4338            .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
 4339
 4340        let mut focused_block = self
 4341            .editor
 4342            .update(cx, |editor, _| editor.take_focused_block());
 4343        let mut fixed_block_max_width = Pixels::ZERO;
 4344        let mut blocks = Vec::new();
 4345        let mut resized_blocks = HashMap::default();
 4346        let mut row_block_types = HashMap::default();
 4347        let mut block_resize_offset: i32 = 0;
 4348
 4349        for (row, block) in fixed_blocks {
 4350            let block_id = block.id();
 4351
 4352            if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
 4353                focused_block = None;
 4354            }
 4355
 4356            if let Some((element, element_size, row, x_offset)) = self.render_block(
 4357                block,
 4358                AvailableSpace::MinContent,
 4359                block_id,
 4360                row,
 4361                snapshot,
 4362                text_x,
 4363                &rows,
 4364                line_layouts,
 4365                editor_margins,
 4366                line_height,
 4367                em_width,
 4368                text_hitbox,
 4369                editor_width,
 4370                scroll_width,
 4371                &mut resized_blocks,
 4372                &mut row_block_types,
 4373                selections,
 4374                selected_buffer_ids,
 4375                latest_selection_anchors,
 4376                is_row_soft_wrapped,
 4377                sticky_header_excerpt_id,
 4378                &mut block_resize_offset,
 4379                window,
 4380                cx,
 4381            ) {
 4382                fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
 4383                blocks.push(BlockLayout {
 4384                    id: block_id,
 4385                    x_offset,
 4386                    row: Some(row),
 4387                    element,
 4388                    available_space: size(AvailableSpace::MinContent, element_size.height.into()),
 4389                    style: BlockStyle::Fixed,
 4390                    overlaps_gutter: true,
 4391                    is_buffer_header: block.is_buffer_header(),
 4392                });
 4393            }
 4394        }
 4395
 4396        for (row, block) in non_fixed_blocks {
 4397            let style = block.style();
 4398            let width = match (style, block.place_near()) {
 4399                (_, true) => AvailableSpace::MinContent,
 4400                (BlockStyle::Sticky, _) => hitbox.size.width.into(),
 4401                (BlockStyle::Flex, _) => hitbox
 4402                    .size
 4403                    .width
 4404                    .max(fixed_block_max_width)
 4405                    .max(editor_margins.gutter.width + *scroll_width)
 4406                    .into(),
 4407                (BlockStyle::Fixed, _) => unreachable!(),
 4408            };
 4409            let block_id = block.id();
 4410
 4411            if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
 4412                focused_block = None;
 4413            }
 4414
 4415            if let Some((element, element_size, row, x_offset)) = self.render_block(
 4416                block,
 4417                width,
 4418                block_id,
 4419                row,
 4420                snapshot,
 4421                text_x,
 4422                &rows,
 4423                line_layouts,
 4424                editor_margins,
 4425                line_height,
 4426                em_width,
 4427                text_hitbox,
 4428                editor_width,
 4429                scroll_width,
 4430                &mut resized_blocks,
 4431                &mut row_block_types,
 4432                selections,
 4433                selected_buffer_ids,
 4434                latest_selection_anchors,
 4435                is_row_soft_wrapped,
 4436                sticky_header_excerpt_id,
 4437                &mut block_resize_offset,
 4438                window,
 4439                cx,
 4440            ) {
 4441                blocks.push(BlockLayout {
 4442                    id: block_id,
 4443                    x_offset,
 4444                    row: Some(row),
 4445                    element,
 4446                    available_space: size(width, element_size.height.into()),
 4447                    style,
 4448                    overlaps_gutter: !block.place_near(),
 4449                    is_buffer_header: block.is_buffer_header(),
 4450                });
 4451            }
 4452        }
 4453
 4454        if let Some(focused_block) = focused_block
 4455            && let Some(focus_handle) = focused_block.focus_handle.upgrade()
 4456            && focus_handle.is_focused(window)
 4457            && let Some(block) = snapshot.block_for_id(focused_block.id)
 4458        {
 4459            let style = block.style();
 4460            let width = match style {
 4461                BlockStyle::Fixed => AvailableSpace::MinContent,
 4462                BlockStyle::Flex => AvailableSpace::Definite(
 4463                    hitbox
 4464                        .size
 4465                        .width
 4466                        .max(fixed_block_max_width)
 4467                        .max(editor_margins.gutter.width + *scroll_width),
 4468                ),
 4469                BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
 4470            };
 4471
 4472            if let Some((element, element_size, _, x_offset)) = self.render_block(
 4473                &block,
 4474                width,
 4475                focused_block.id,
 4476                rows.end,
 4477                snapshot,
 4478                text_x,
 4479                &rows,
 4480                line_layouts,
 4481                editor_margins,
 4482                line_height,
 4483                em_width,
 4484                text_hitbox,
 4485                editor_width,
 4486                scroll_width,
 4487                &mut resized_blocks,
 4488                &mut row_block_types,
 4489                selections,
 4490                selected_buffer_ids,
 4491                latest_selection_anchors,
 4492                is_row_soft_wrapped,
 4493                sticky_header_excerpt_id,
 4494                &mut block_resize_offset,
 4495                window,
 4496                cx,
 4497            ) {
 4498                blocks.push(BlockLayout {
 4499                    id: block.id(),
 4500                    x_offset,
 4501                    row: None,
 4502                    element,
 4503                    available_space: size(width, element_size.height.into()),
 4504                    style,
 4505                    overlaps_gutter: true,
 4506                    is_buffer_header: block.is_buffer_header(),
 4507                });
 4508            }
 4509        }
 4510
 4511        if resized_blocks.is_empty() {
 4512            *scroll_width =
 4513                (*scroll_width).max(fixed_block_max_width - editor_margins.gutter.width);
 4514        }
 4515
 4516        RenderBlocksOutput {
 4517            blocks,
 4518            row_block_types,
 4519            resized_blocks: (!resized_blocks.is_empty()).then_some(resized_blocks),
 4520        }
 4521    }
 4522
 4523    fn layout_blocks(
 4524        &self,
 4525        blocks: &mut Vec<BlockLayout>,
 4526        hitbox: &Hitbox,
 4527        line_height: Pixels,
 4528        scroll_position: gpui::Point<ScrollOffset>,
 4529        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 4530        window: &mut Window,
 4531        cx: &mut App,
 4532    ) {
 4533        for block in blocks {
 4534            let mut origin = if let Some(row) = block.row {
 4535                hitbox.origin
 4536                    + point(
 4537                        block.x_offset,
 4538                        Pixels::from(
 4539                            (row.as_f64() - scroll_position.y)
 4540                                * ScrollPixelOffset::from(line_height),
 4541                        ),
 4542                    )
 4543            } else {
 4544                // Position the block outside the visible area
 4545                hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
 4546            };
 4547
 4548            if !matches!(block.style, BlockStyle::Sticky) {
 4549                origin += point(Pixels::from(-scroll_pixel_position.x), Pixels::ZERO);
 4550            }
 4551
 4552            let focus_handle =
 4553                block
 4554                    .element
 4555                    .prepaint_as_root(origin, block.available_space, window, cx);
 4556
 4557            if let Some(focus_handle) = focus_handle {
 4558                self.editor.update(cx, |editor, _cx| {
 4559                    editor.set_focused_block(FocusedBlock {
 4560                        id: block.id,
 4561                        focus_handle: focus_handle.downgrade(),
 4562                    });
 4563                });
 4564            }
 4565        }
 4566    }
 4567
 4568    fn layout_sticky_buffer_header(
 4569        &self,
 4570        StickyHeaderExcerpt { excerpt }: StickyHeaderExcerpt<'_>,
 4571        scroll_position: gpui::Point<ScrollOffset>,
 4572        line_height: Pixels,
 4573        right_margin: Pixels,
 4574        snapshot: &EditorSnapshot,
 4575        hitbox: &Hitbox,
 4576        selected_buffer_ids: &Vec<BufferId>,
 4577        blocks: &[BlockLayout],
 4578        latest_selection_anchors: &HashMap<BufferId, Anchor>,
 4579        window: &mut Window,
 4580        cx: &mut App,
 4581    ) -> AnyElement {
 4582        let jump_data = header_jump_data(
 4583            snapshot,
 4584            DisplayRow(scroll_position.y as u32),
 4585            FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 4586            excerpt,
 4587            latest_selection_anchors,
 4588        );
 4589
 4590        let editor_bg_color = cx.theme().colors().editor_background;
 4591
 4592        let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
 4593
 4594        let available_width = hitbox.bounds.size.width - right_margin;
 4595
 4596        let mut header = v_flex()
 4597            .w_full()
 4598            .relative()
 4599            .child(
 4600                div()
 4601                    .w(available_width)
 4602                    .h(FILE_HEADER_HEIGHT as f32 * line_height)
 4603                    .bg(linear_gradient(
 4604                        0.,
 4605                        linear_color_stop(editor_bg_color.opacity(0.), 0.),
 4606                        linear_color_stop(editor_bg_color, 0.6),
 4607                    ))
 4608                    .absolute()
 4609                    .top_0(),
 4610            )
 4611            .child(
 4612                self.render_buffer_header(excerpt, false, selected, true, jump_data, window, cx)
 4613                    .into_any_element(),
 4614            )
 4615            .into_any_element();
 4616
 4617        let mut origin = hitbox.origin;
 4618        // Move floating header up to avoid colliding with the next buffer header.
 4619        for block in blocks.iter() {
 4620            if !block.is_buffer_header {
 4621                continue;
 4622            }
 4623
 4624            let Some(display_row) = block.row.filter(|row| row.0 > scroll_position.y as u32) else {
 4625                continue;
 4626            };
 4627
 4628            let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
 4629            let offset = scroll_position.y - max_row as f64;
 4630
 4631            if offset > 0.0 {
 4632                origin.y -= Pixels::from(offset * ScrollPixelOffset::from(line_height));
 4633            }
 4634            break;
 4635        }
 4636
 4637        let size = size(
 4638            AvailableSpace::Definite(available_width),
 4639            AvailableSpace::MinContent,
 4640        );
 4641
 4642        header.prepaint_as_root(origin, size, window, cx);
 4643
 4644        header
 4645    }
 4646
 4647    fn layout_sticky_headers(
 4648        &self,
 4649        snapshot: &EditorSnapshot,
 4650        editor_width: Pixels,
 4651        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 4652        line_height: Pixels,
 4653        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 4654        content_origin: gpui::Point<Pixels>,
 4655        gutter_dimensions: &GutterDimensions,
 4656        gutter_hitbox: &Hitbox,
 4657        text_hitbox: &Hitbox,
 4658        style: &EditorStyle,
 4659        window: &mut Window,
 4660        cx: &mut App,
 4661    ) -> Option<StickyHeaders> {
 4662        let show_line_numbers = snapshot
 4663            .show_line_numbers
 4664            .unwrap_or_else(|| EditorSettings::get_global(cx).gutter.line_numbers);
 4665
 4666        let rows = Self::sticky_headers(self.editor.read(cx), snapshot, style, cx);
 4667
 4668        let mut lines = Vec::<StickyHeaderLine>::new();
 4669
 4670        for StickyHeader {
 4671            item,
 4672            sticky_row,
 4673            start_point,
 4674            offset,
 4675        } in rows.into_iter().rev()
 4676        {
 4677            let line = layout_line(
 4678                sticky_row,
 4679                snapshot,
 4680                &self.style,
 4681                editor_width,
 4682                is_row_soft_wrapped,
 4683                window,
 4684                cx,
 4685            );
 4686
 4687            let line_number = show_line_numbers.then(|| {
 4688                let number = (start_point.row + 1).to_string();
 4689                let color = cx.theme().colors().editor_line_number;
 4690                self.shape_line_number(SharedString::from(number), color, window)
 4691            });
 4692
 4693            lines.push(StickyHeaderLine::new(
 4694                sticky_row,
 4695                line_height * offset as f32,
 4696                line,
 4697                line_number,
 4698                item.range.start,
 4699                line_height,
 4700                scroll_pixel_position,
 4701                content_origin,
 4702                gutter_hitbox,
 4703                text_hitbox,
 4704                window,
 4705                cx,
 4706            ));
 4707        }
 4708
 4709        lines.reverse();
 4710        if lines.is_empty() {
 4711            return None;
 4712        }
 4713
 4714        Some(StickyHeaders {
 4715            lines,
 4716            gutter_background: cx.theme().colors().editor_gutter_background,
 4717            content_background: self.style.background,
 4718            gutter_right_padding: gutter_dimensions.right_padding,
 4719        })
 4720    }
 4721
 4722    pub(crate) fn sticky_headers(
 4723        editor: &Editor,
 4724        snapshot: &EditorSnapshot,
 4725        style: &EditorStyle,
 4726        cx: &App,
 4727    ) -> Vec<StickyHeader> {
 4728        let scroll_top = snapshot.scroll_position().y;
 4729
 4730        let mut end_rows = Vec::<DisplayRow>::new();
 4731        let mut rows = Vec::<StickyHeader>::new();
 4732
 4733        let items = editor.sticky_headers(style, cx).unwrap_or_default();
 4734
 4735        for item in items {
 4736            let start_point = item.range.start.to_point(snapshot.buffer_snapshot());
 4737            let end_point = item.range.end.to_point(snapshot.buffer_snapshot());
 4738
 4739            let sticky_row = snapshot
 4740                .display_snapshot
 4741                .point_to_display_point(start_point, Bias::Left)
 4742                .row();
 4743            let end_row = snapshot
 4744                .display_snapshot
 4745                .point_to_display_point(end_point, Bias::Left)
 4746                .row();
 4747            let max_sticky_row = end_row.previous_row();
 4748            if max_sticky_row <= sticky_row {
 4749                continue;
 4750            }
 4751
 4752            while end_rows
 4753                .last()
 4754                .is_some_and(|&last_end| last_end < sticky_row)
 4755            {
 4756                end_rows.pop();
 4757            }
 4758            let depth = end_rows.len();
 4759            let adjusted_scroll_top = scroll_top + depth as f64;
 4760
 4761            if sticky_row.as_f64() >= adjusted_scroll_top || end_row.as_f64() <= adjusted_scroll_top
 4762            {
 4763                continue;
 4764            }
 4765
 4766            let max_scroll_offset = max_sticky_row.as_f64() - scroll_top;
 4767            let offset = (depth as f64).min(max_scroll_offset);
 4768
 4769            end_rows.push(end_row);
 4770            rows.push(StickyHeader {
 4771                item,
 4772                sticky_row,
 4773                start_point,
 4774                offset,
 4775            });
 4776        }
 4777
 4778        rows
 4779    }
 4780
 4781    fn layout_cursor_popovers(
 4782        &self,
 4783        line_height: Pixels,
 4784        text_hitbox: &Hitbox,
 4785        content_origin: gpui::Point<Pixels>,
 4786        right_margin: Pixels,
 4787        start_row: DisplayRow,
 4788        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 4789        line_layouts: &[LineWithInvisibles],
 4790        cursor: DisplayPoint,
 4791        cursor_point: Point,
 4792        style: &EditorStyle,
 4793        window: &mut Window,
 4794        cx: &mut App,
 4795    ) -> Option<ContextMenuLayout> {
 4796        let mut min_menu_height = Pixels::ZERO;
 4797        let mut max_menu_height = Pixels::ZERO;
 4798        let mut height_above_menu = Pixels::ZERO;
 4799        let height_below_menu = Pixels::ZERO;
 4800        let mut edit_prediction_popover_visible = false;
 4801        let mut context_menu_visible = false;
 4802        let context_menu_placement;
 4803
 4804        {
 4805            let editor = self.editor.read(cx);
 4806            if editor.edit_prediction_visible_in_cursor_popover(editor.has_active_edit_prediction())
 4807            {
 4808                height_above_menu +=
 4809                    editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
 4810                edit_prediction_popover_visible = true;
 4811            }
 4812
 4813            if editor.context_menu_visible()
 4814                && let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin()
 4815            {
 4816                let (min_height_in_lines, max_height_in_lines) = editor
 4817                    .context_menu_options
 4818                    .as_ref()
 4819                    .map_or((3, 12), |options| {
 4820                        (options.min_entries_visible, options.max_entries_visible)
 4821                    });
 4822
 4823                min_menu_height += line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
 4824                max_menu_height += line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
 4825                context_menu_visible = true;
 4826            }
 4827            context_menu_placement = editor
 4828                .context_menu_options
 4829                .as_ref()
 4830                .and_then(|options| options.placement.clone());
 4831        }
 4832
 4833        let visible = edit_prediction_popover_visible || context_menu_visible;
 4834        if !visible {
 4835            return None;
 4836        }
 4837
 4838        let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
 4839        let target_position = content_origin
 4840            + gpui::Point {
 4841                x: cmp::max(
 4842                    px(0.),
 4843                    Pixels::from(
 4844                        ScrollPixelOffset::from(
 4845                            cursor_row_layout.x_for_index(cursor.column() as usize),
 4846                        ) - scroll_pixel_position.x,
 4847                    ),
 4848                ),
 4849                y: cmp::max(
 4850                    px(0.),
 4851                    Pixels::from(
 4852                        cursor.row().next_row().as_f64() * ScrollPixelOffset::from(line_height)
 4853                            - scroll_pixel_position.y,
 4854                    ),
 4855                ),
 4856            };
 4857
 4858        let viewport_bounds =
 4859            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 4860                right: -right_margin - MENU_GAP,
 4861                ..Default::default()
 4862            });
 4863
 4864        let min_height = height_above_menu + min_menu_height + height_below_menu;
 4865        let max_height = height_above_menu + max_menu_height + height_below_menu;
 4866        let (laid_out_popovers, y_flipped) = self.layout_popovers_above_or_below_line(
 4867            target_position,
 4868            line_height,
 4869            min_height,
 4870            max_height,
 4871            context_menu_placement,
 4872            text_hitbox,
 4873            viewport_bounds,
 4874            window,
 4875            cx,
 4876            |height, max_width_for_stable_x, y_flipped, window, cx| {
 4877                // First layout the menu to get its size - others can be at least this wide.
 4878                let context_menu = if context_menu_visible {
 4879                    let menu_height = if y_flipped {
 4880                        height - height_below_menu
 4881                    } else {
 4882                        height - height_above_menu
 4883                    };
 4884                    let mut element = self
 4885                        .render_context_menu(line_height, menu_height, window, cx)
 4886                        .expect("Visible context menu should always render.");
 4887                    let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 4888                    Some((CursorPopoverType::CodeContextMenu, element, size))
 4889                } else {
 4890                    None
 4891                };
 4892                let min_width = context_menu
 4893                    .as_ref()
 4894                    .map_or(px(0.), |(_, _, size)| size.width);
 4895                let max_width = max_width_for_stable_x.max(
 4896                    context_menu
 4897                        .as_ref()
 4898                        .map_or(px(0.), |(_, _, size)| size.width),
 4899                );
 4900
 4901                let edit_prediction = if edit_prediction_popover_visible {
 4902                    self.editor.update(cx, move |editor, cx| {
 4903                        let accept_binding = editor.accept_edit_prediction_keybind(
 4904                            EditPredictionGranularity::Full,
 4905                            window,
 4906                            cx,
 4907                        );
 4908                        let mut element = editor.render_edit_prediction_cursor_popover(
 4909                            min_width,
 4910                            max_width,
 4911                            cursor_point,
 4912                            style,
 4913                            accept_binding.keystroke(),
 4914                            window,
 4915                            cx,
 4916                        )?;
 4917                        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 4918                        Some((CursorPopoverType::EditPrediction, element, size))
 4919                    })
 4920                } else {
 4921                    None
 4922                };
 4923                vec![edit_prediction, context_menu]
 4924                    .into_iter()
 4925                    .flatten()
 4926                    .collect::<Vec<_>>()
 4927            },
 4928        )?;
 4929
 4930        let (menu_ix, (_, menu_bounds)) = laid_out_popovers
 4931            .iter()
 4932            .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))?;
 4933        let last_ix = laid_out_popovers.len() - 1;
 4934        let menu_is_last = menu_ix == last_ix;
 4935        let first_popover_bounds = laid_out_popovers[0].1;
 4936        let last_popover_bounds = laid_out_popovers[last_ix].1;
 4937
 4938        // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
 4939        // right, and otherwise it goes below or to the right.
 4940        let mut target_bounds = Bounds::from_corners(
 4941            first_popover_bounds.origin,
 4942            last_popover_bounds.bottom_right(),
 4943        );
 4944        target_bounds.size.width = menu_bounds.size.width;
 4945
 4946        // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
 4947        // based on this is preferred for layout stability.
 4948        let mut max_target_bounds = target_bounds;
 4949        max_target_bounds.size.height = max_height;
 4950        if y_flipped {
 4951            max_target_bounds.origin.y -= max_height - target_bounds.size.height;
 4952        }
 4953
 4954        // Add spacing around `target_bounds` and `max_target_bounds`.
 4955        let mut extend_amount = Edges::all(MENU_GAP);
 4956        if y_flipped {
 4957            extend_amount.bottom = line_height;
 4958        } else {
 4959            extend_amount.top = line_height;
 4960        }
 4961        let target_bounds = target_bounds.extend(extend_amount);
 4962        let max_target_bounds = max_target_bounds.extend(extend_amount);
 4963
 4964        let must_place_above_or_below =
 4965            if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
 4966                laid_out_popovers[menu_ix + 1..]
 4967                    .iter()
 4968                    .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
 4969            } else {
 4970                false
 4971            };
 4972
 4973        let aside_bounds = self.layout_context_menu_aside(
 4974            y_flipped,
 4975            *menu_bounds,
 4976            target_bounds,
 4977            max_target_bounds,
 4978            max_menu_height,
 4979            must_place_above_or_below,
 4980            text_hitbox,
 4981            viewport_bounds,
 4982            window,
 4983            cx,
 4984        );
 4985
 4986        if let Some(menu_bounds) = laid_out_popovers.iter().find_map(|(popover_type, bounds)| {
 4987            if matches!(popover_type, CursorPopoverType::CodeContextMenu) {
 4988                Some(*bounds)
 4989            } else {
 4990                None
 4991            }
 4992        }) {
 4993            let bounds = if let Some(aside_bounds) = aside_bounds {
 4994                menu_bounds.union(&aside_bounds)
 4995            } else {
 4996                menu_bounds
 4997            };
 4998            return Some(ContextMenuLayout { y_flipped, bounds });
 4999        }
 5000
 5001        None
 5002    }
 5003
 5004    fn layout_gutter_menu(
 5005        &self,
 5006        line_height: Pixels,
 5007        text_hitbox: &Hitbox,
 5008        content_origin: gpui::Point<Pixels>,
 5009        right_margin: Pixels,
 5010        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 5011        gutter_overshoot: Pixels,
 5012        window: &mut Window,
 5013        cx: &mut App,
 5014    ) {
 5015        let editor = self.editor.read(cx);
 5016        if !editor.context_menu_visible() {
 5017            return;
 5018        }
 5019        let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
 5020            editor.context_menu_origin()
 5021        else {
 5022            return;
 5023        };
 5024        // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
 5025        // indicator than just a plain first column of the text field.
 5026        let target_position = content_origin
 5027            + gpui::Point {
 5028                x: -gutter_overshoot,
 5029                y: Pixels::from(
 5030                    gutter_row.next_row().as_f64() * ScrollPixelOffset::from(line_height)
 5031                        - scroll_pixel_position.y,
 5032                ),
 5033            };
 5034
 5035        let (min_height_in_lines, max_height_in_lines) = editor
 5036            .context_menu_options
 5037            .as_ref()
 5038            .map_or((3, 12), |options| {
 5039                (options.min_entries_visible, options.max_entries_visible)
 5040            });
 5041
 5042        let min_height = line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
 5043        let max_height = line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
 5044        let viewport_bounds =
 5045            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 5046                right: -right_margin - MENU_GAP,
 5047                ..Default::default()
 5048            });
 5049        self.layout_popovers_above_or_below_line(
 5050            target_position,
 5051            line_height,
 5052            min_height,
 5053            max_height,
 5054            editor
 5055                .context_menu_options
 5056                .as_ref()
 5057                .and_then(|options| options.placement.clone()),
 5058            text_hitbox,
 5059            viewport_bounds,
 5060            window,
 5061            cx,
 5062            move |height, _max_width_for_stable_x, _, window, cx| {
 5063                let mut element = self
 5064                    .render_context_menu(line_height, height, window, cx)
 5065                    .expect("Visible context menu should always render.");
 5066                let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 5067                vec![(CursorPopoverType::CodeContextMenu, element, size)]
 5068            },
 5069        );
 5070    }
 5071
 5072    fn layout_popovers_above_or_below_line(
 5073        &self,
 5074        target_position: gpui::Point<Pixels>,
 5075        line_height: Pixels,
 5076        min_height: Pixels,
 5077        max_height: Pixels,
 5078        placement: Option<ContextMenuPlacement>,
 5079        text_hitbox: &Hitbox,
 5080        viewport_bounds: Bounds<Pixels>,
 5081        window: &mut Window,
 5082        cx: &mut App,
 5083        make_sized_popovers: impl FnOnce(
 5084            Pixels,
 5085            Pixels,
 5086            bool,
 5087            &mut Window,
 5088            &mut App,
 5089        ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
 5090    ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
 5091        let text_style = TextStyleRefinement {
 5092            line_height: Some(DefiniteLength::Fraction(
 5093                BufferLineHeight::Comfortable.value(),
 5094            )),
 5095            ..Default::default()
 5096        };
 5097        window.with_text_style(Some(text_style), |window| {
 5098            // If the max height won't fit below and there is more space above, put it above the line.
 5099            let bottom_y_when_flipped = target_position.y - line_height;
 5100            let available_above = bottom_y_when_flipped - text_hitbox.top();
 5101            let available_below = text_hitbox.bottom() - target_position.y;
 5102            let y_overflows_below = max_height > available_below;
 5103            let mut y_flipped = match placement {
 5104                Some(ContextMenuPlacement::Above) => true,
 5105                Some(ContextMenuPlacement::Below) => false,
 5106                None => y_overflows_below && available_above > available_below,
 5107            };
 5108            let mut height = cmp::min(
 5109                max_height,
 5110                if y_flipped {
 5111                    available_above
 5112                } else {
 5113                    available_below
 5114                },
 5115            );
 5116
 5117            // If the min height doesn't fit within text bounds, instead fit within the window.
 5118            if height < min_height {
 5119                let available_above = bottom_y_when_flipped;
 5120                let available_below = viewport_bounds.bottom() - target_position.y;
 5121                let (y_flipped_override, height_override) = match placement {
 5122                    Some(ContextMenuPlacement::Above) => {
 5123                        (true, cmp::min(available_above, min_height))
 5124                    }
 5125                    Some(ContextMenuPlacement::Below) => {
 5126                        (false, cmp::min(available_below, min_height))
 5127                    }
 5128                    None => {
 5129                        if available_below > min_height {
 5130                            (false, min_height)
 5131                        } else if available_above > min_height {
 5132                            (true, min_height)
 5133                        } else if available_above > available_below {
 5134                            (true, available_above)
 5135                        } else {
 5136                            (false, available_below)
 5137                        }
 5138                    }
 5139                };
 5140                y_flipped = y_flipped_override;
 5141                height = height_override;
 5142            }
 5143
 5144            let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
 5145
 5146            // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
 5147            // for very narrow windows.
 5148            let popovers =
 5149                make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
 5150            if popovers.is_empty() {
 5151                return None;
 5152            }
 5153
 5154            let max_width = popovers
 5155                .iter()
 5156                .map(|(_, _, size)| size.width)
 5157                .max()
 5158                .unwrap_or_default();
 5159
 5160            let mut current_position = gpui::Point {
 5161                // Snap the right edge of the list to the right edge of the window if its horizontal bounds
 5162                // overflow. Include space for the scrollbar.
 5163                x: target_position
 5164                    .x
 5165                    .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
 5166                y: if y_flipped {
 5167                    bottom_y_when_flipped
 5168                } else {
 5169                    target_position.y
 5170                },
 5171            };
 5172
 5173            let mut laid_out_popovers = popovers
 5174                .into_iter()
 5175                .map(|(popover_type, element, size)| {
 5176                    if y_flipped {
 5177                        current_position.y -= size.height;
 5178                    }
 5179                    let position = current_position;
 5180                    window.defer_draw(element, current_position, 1);
 5181                    if !y_flipped {
 5182                        current_position.y += size.height + MENU_GAP;
 5183                    } else {
 5184                        current_position.y -= MENU_GAP;
 5185                    }
 5186                    (popover_type, Bounds::new(position, size))
 5187                })
 5188                .collect::<Vec<_>>();
 5189
 5190            if y_flipped {
 5191                laid_out_popovers.reverse();
 5192            }
 5193
 5194            Some((laid_out_popovers, y_flipped))
 5195        })
 5196    }
 5197
 5198    fn layout_context_menu_aside(
 5199        &self,
 5200        y_flipped: bool,
 5201        menu_bounds: Bounds<Pixels>,
 5202        target_bounds: Bounds<Pixels>,
 5203        max_target_bounds: Bounds<Pixels>,
 5204        max_height: Pixels,
 5205        must_place_above_or_below: bool,
 5206        text_hitbox: &Hitbox,
 5207        viewport_bounds: Bounds<Pixels>,
 5208        window: &mut Window,
 5209        cx: &mut App,
 5210    ) -> Option<Bounds<Pixels>> {
 5211        let available_within_viewport = target_bounds.space_within(&viewport_bounds);
 5212        let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
 5213            && !must_place_above_or_below
 5214        {
 5215            let max_width = cmp::min(
 5216                available_within_viewport.right - px(1.),
 5217                MENU_ASIDE_MAX_WIDTH,
 5218            );
 5219            let mut aside = self.render_context_menu_aside(
 5220                size(max_width, max_height - POPOVER_Y_PADDING),
 5221                window,
 5222                cx,
 5223            )?;
 5224            let size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
 5225            let right_position = point(target_bounds.right(), menu_bounds.origin.y);
 5226            Some((aside, right_position, size))
 5227        } else {
 5228            let max_size = size(
 5229                // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
 5230                // won't be needed here.
 5231                cmp::min(
 5232                    cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
 5233                    viewport_bounds.right(),
 5234                ),
 5235                cmp::min(
 5236                    max_height,
 5237                    cmp::max(
 5238                        available_within_viewport.top,
 5239                        available_within_viewport.bottom,
 5240                    ),
 5241                ) - POPOVER_Y_PADDING,
 5242            );
 5243            let mut aside = self.render_context_menu_aside(max_size, window, cx)?;
 5244            let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
 5245
 5246            let top_position = point(
 5247                menu_bounds.origin.x,
 5248                target_bounds.top() - actual_size.height,
 5249            );
 5250            let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
 5251
 5252            let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
 5253                // Prefer to fit on the same side of the line as the menu, then on the other side of
 5254                // the line.
 5255                if !y_flipped && wanted.height < available.bottom {
 5256                    Some(bottom_position)
 5257                } else if !y_flipped && wanted.height < available.top {
 5258                    Some(top_position)
 5259                } else if y_flipped && wanted.height < available.top {
 5260                    Some(top_position)
 5261                } else if y_flipped && wanted.height < available.bottom {
 5262                    Some(bottom_position)
 5263                } else {
 5264                    None
 5265                }
 5266            };
 5267
 5268            // Prefer choosing a direction using max sizes rather than actual size for stability.
 5269            let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
 5270            let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
 5271            let aside_position = fit_within(available_within_text, wanted)
 5272                // Fallback: fit max size in window.
 5273                .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
 5274                // Fallback: fit actual size in window.
 5275                .or_else(|| fit_within(available_within_viewport, actual_size));
 5276
 5277            aside_position.map(|position| (aside, position, actual_size))
 5278        };
 5279
 5280        // Skip drawing if it doesn't fit anywhere.
 5281        if let Some((aside, position, size)) = positioned_aside {
 5282            let aside_bounds = Bounds::new(position, size);
 5283            window.defer_draw(aside, position, 2);
 5284            return Some(aside_bounds);
 5285        }
 5286
 5287        None
 5288    }
 5289
 5290    fn render_context_menu(
 5291        &self,
 5292        line_height: Pixels,
 5293        height: Pixels,
 5294        window: &mut Window,
 5295        cx: &mut App,
 5296    ) -> Option<AnyElement> {
 5297        let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
 5298        self.editor.update(cx, |editor, cx| {
 5299            editor.render_context_menu(max_height_in_lines, window, cx)
 5300        })
 5301    }
 5302
 5303    fn render_context_menu_aside(
 5304        &self,
 5305        max_size: Size<Pixels>,
 5306        window: &mut Window,
 5307        cx: &mut App,
 5308    ) -> Option<AnyElement> {
 5309        if max_size.width < px(100.) || max_size.height < px(12.) {
 5310            None
 5311        } else {
 5312            self.editor.update(cx, |editor, cx| {
 5313                editor.render_context_menu_aside(max_size, window, cx)
 5314            })
 5315        }
 5316    }
 5317
 5318    fn layout_mouse_context_menu(
 5319        &self,
 5320        editor_snapshot: &EditorSnapshot,
 5321        visible_range: Range<DisplayRow>,
 5322        content_origin: gpui::Point<Pixels>,
 5323        window: &mut Window,
 5324        cx: &mut App,
 5325    ) -> Option<AnyElement> {
 5326        let position = self.editor.update(cx, |editor, cx| {
 5327            let visible_start_point = editor.display_to_pixel_point(
 5328                DisplayPoint::new(visible_range.start, 0),
 5329                editor_snapshot,
 5330                window,
 5331                cx,
 5332            )?;
 5333            let visible_end_point = editor.display_to_pixel_point(
 5334                DisplayPoint::new(visible_range.end, 0),
 5335                editor_snapshot,
 5336                window,
 5337                cx,
 5338            )?;
 5339
 5340            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
 5341            let (source_display_point, position) = match mouse_context_menu.position {
 5342                MenuPosition::PinnedToScreen(point) => (None, point),
 5343                MenuPosition::PinnedToEditor { source, offset } => {
 5344                    let source_display_point = source.to_display_point(editor_snapshot);
 5345                    let source_point =
 5346                        editor.to_pixel_point(source, editor_snapshot, window, cx)?;
 5347                    let position = content_origin + source_point + offset;
 5348                    (Some(source_display_point), position)
 5349                }
 5350            };
 5351
 5352            let source_included = source_display_point.is_none_or(|source_display_point| {
 5353                visible_range
 5354                    .to_inclusive()
 5355                    .contains(&source_display_point.row())
 5356            });
 5357            let position_included =
 5358                visible_start_point.y <= position.y && position.y <= visible_end_point.y;
 5359            if !source_included && !position_included {
 5360                None
 5361            } else {
 5362                Some(position)
 5363            }
 5364        })?;
 5365
 5366        let text_style = TextStyleRefinement {
 5367            line_height: Some(DefiniteLength::Fraction(
 5368                BufferLineHeight::Comfortable.value(),
 5369            )),
 5370            ..Default::default()
 5371        };
 5372        window.with_text_style(Some(text_style), |window| {
 5373            let mut element = self.editor.read_with(cx, |editor, _| {
 5374                let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
 5375                let context_menu = mouse_context_menu.context_menu.clone();
 5376
 5377                Some(
 5378                    deferred(
 5379                        anchored()
 5380                            .position(position)
 5381                            .child(context_menu)
 5382                            .anchor(Corner::TopLeft)
 5383                            .snap_to_window_with_margin(px(8.)),
 5384                    )
 5385                    .with_priority(1)
 5386                    .into_any(),
 5387                )
 5388            })?;
 5389
 5390            element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
 5391            Some(element)
 5392        })
 5393    }
 5394
 5395    fn layout_hover_popovers(
 5396        &self,
 5397        snapshot: &EditorSnapshot,
 5398        hitbox: &Hitbox,
 5399        visible_display_row_range: Range<DisplayRow>,
 5400        content_origin: gpui::Point<Pixels>,
 5401        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 5402        line_layouts: &[LineWithInvisibles],
 5403        line_height: Pixels,
 5404        em_width: Pixels,
 5405        context_menu_layout: Option<ContextMenuLayout>,
 5406        window: &mut Window,
 5407        cx: &mut App,
 5408    ) {
 5409        struct MeasuredHoverPopover {
 5410            element: AnyElement,
 5411            size: Size<Pixels>,
 5412            horizontal_offset: Pixels,
 5413        }
 5414
 5415        let max_size = size(
 5416            (120. * em_width) // Default size
 5417                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
 5418                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
 5419            (16. * line_height) // Default size
 5420                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
 5421                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
 5422        );
 5423
 5424        // Don't show hover popovers when context menu is open to avoid overlap
 5425        let has_context_menu = self.editor.read(cx).mouse_context_menu.is_some();
 5426        if has_context_menu {
 5427            return;
 5428        }
 5429
 5430        let hover_popovers = self.editor.update(cx, |editor, cx| {
 5431            editor.hover_state.render(
 5432                snapshot,
 5433                visible_display_row_range.clone(),
 5434                max_size,
 5435                &editor.text_layout_details(window),
 5436                window,
 5437                cx,
 5438            )
 5439        });
 5440        let Some((popover_position, hover_popovers)) = hover_popovers else {
 5441            return;
 5442        };
 5443
 5444        // This is safe because we check on layout whether the required row is available
 5445        let hovered_row_layout = &line_layouts[popover_position
 5446            .row()
 5447            .minus(visible_display_row_range.start)
 5448            as usize];
 5449
 5450        // Compute Hovered Point
 5451        let x = hovered_row_layout.x_for_index(popover_position.column() as usize)
 5452            - Pixels::from(scroll_pixel_position.x);
 5453        let y = Pixels::from(
 5454            popover_position.row().as_f64() * ScrollPixelOffset::from(line_height)
 5455                - scroll_pixel_position.y,
 5456        );
 5457        let hovered_point = content_origin + point(x, y);
 5458
 5459        let mut overall_height = Pixels::ZERO;
 5460        let mut measured_hover_popovers = Vec::new();
 5461        for (position, mut hover_popover) in hover_popovers.into_iter().with_position() {
 5462            let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
 5463            let horizontal_offset =
 5464                (hitbox.top_right().x - POPOVER_RIGHT_OFFSET - (hovered_point.x + size.width))
 5465                    .min(Pixels::ZERO);
 5466            match position {
 5467                itertools::Position::Middle | itertools::Position::Last => {
 5468                    overall_height += HOVER_POPOVER_GAP
 5469                }
 5470                _ => {}
 5471            }
 5472            overall_height += size.height;
 5473            measured_hover_popovers.push(MeasuredHoverPopover {
 5474                element: hover_popover,
 5475                size,
 5476                horizontal_offset,
 5477            });
 5478        }
 5479
 5480        fn draw_occluder(
 5481            width: Pixels,
 5482            origin: gpui::Point<Pixels>,
 5483            window: &mut Window,
 5484            cx: &mut App,
 5485        ) {
 5486            let mut occlusion = div()
 5487                .size_full()
 5488                .occlude()
 5489                .on_mouse_move(|_, _, cx| cx.stop_propagation())
 5490                .into_any_element();
 5491            occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
 5492            window.defer_draw(occlusion, origin, 2);
 5493        }
 5494
 5495        fn place_popovers_above(
 5496            hovered_point: gpui::Point<Pixels>,
 5497            measured_hover_popovers: Vec<MeasuredHoverPopover>,
 5498            window: &mut Window,
 5499            cx: &mut App,
 5500        ) {
 5501            let mut current_y = hovered_point.y;
 5502            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 5503                let size = popover.size;
 5504                let popover_origin = point(
 5505                    hovered_point.x + popover.horizontal_offset,
 5506                    current_y - size.height,
 5507                );
 5508
 5509                window.defer_draw(popover.element, popover_origin, 2);
 5510                if position != itertools::Position::Last {
 5511                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
 5512                    draw_occluder(size.width, origin, window, cx);
 5513                }
 5514
 5515                current_y = popover_origin.y - HOVER_POPOVER_GAP;
 5516            }
 5517        }
 5518
 5519        fn place_popovers_below(
 5520            hovered_point: gpui::Point<Pixels>,
 5521            measured_hover_popovers: Vec<MeasuredHoverPopover>,
 5522            line_height: Pixels,
 5523            window: &mut Window,
 5524            cx: &mut App,
 5525        ) {
 5526            let mut current_y = hovered_point.y + line_height;
 5527            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 5528                let size = popover.size;
 5529                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
 5530
 5531                window.defer_draw(popover.element, popover_origin, 2);
 5532                if position != itertools::Position::Last {
 5533                    let origin = point(popover_origin.x, popover_origin.y + size.height);
 5534                    draw_occluder(size.width, origin, window, cx);
 5535                }
 5536
 5537                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 5538            }
 5539        }
 5540
 5541        let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
 5542            context_menu_layout
 5543                .as_ref()
 5544                .is_some_and(|menu| bounds.intersects(&menu.bounds))
 5545        };
 5546
 5547        let can_place_above = {
 5548            let mut bounds_above = Vec::new();
 5549            let mut current_y = hovered_point.y;
 5550            for popover in &measured_hover_popovers {
 5551                let size = popover.size;
 5552                let popover_origin = point(
 5553                    hovered_point.x + popover.horizontal_offset,
 5554                    current_y - size.height,
 5555                );
 5556                bounds_above.push(Bounds::new(popover_origin, size));
 5557                current_y = popover_origin.y - HOVER_POPOVER_GAP;
 5558            }
 5559            bounds_above
 5560                .iter()
 5561                .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
 5562        };
 5563
 5564        let can_place_below = || {
 5565            let mut bounds_below = Vec::new();
 5566            let mut current_y = hovered_point.y + line_height;
 5567            for popover in &measured_hover_popovers {
 5568                let size = popover.size;
 5569                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
 5570                bounds_below.push(Bounds::new(popover_origin, size));
 5571                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 5572            }
 5573            bounds_below
 5574                .iter()
 5575                .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
 5576        };
 5577
 5578        if can_place_above {
 5579            // try placing above hovered point
 5580            place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
 5581        } else if can_place_below() {
 5582            // try placing below hovered point
 5583            place_popovers_below(
 5584                hovered_point,
 5585                measured_hover_popovers,
 5586                line_height,
 5587                window,
 5588                cx,
 5589            );
 5590        } else {
 5591            // try to place popovers around the context menu
 5592            let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
 5593                let total_width = measured_hover_popovers
 5594                    .iter()
 5595                    .map(|p| p.size.width)
 5596                    .max()
 5597                    .unwrap_or(Pixels::ZERO);
 5598                let y_for_horizontal_positioning = if menu.y_flipped {
 5599                    menu.bounds.bottom() - overall_height
 5600                } else {
 5601                    menu.bounds.top()
 5602                };
 5603                let possible_origins = vec![
 5604                    // left of context menu
 5605                    point(
 5606                        menu.bounds.left() - total_width - HOVER_POPOVER_GAP,
 5607                        y_for_horizontal_positioning,
 5608                    ),
 5609                    // right of context menu
 5610                    point(
 5611                        menu.bounds.right() + HOVER_POPOVER_GAP,
 5612                        y_for_horizontal_positioning,
 5613                    ),
 5614                    // top of context menu
 5615                    point(
 5616                        menu.bounds.left(),
 5617                        menu.bounds.top() - overall_height - HOVER_POPOVER_GAP,
 5618                    ),
 5619                    // bottom of context menu
 5620                    point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
 5621                ];
 5622                possible_origins.into_iter().find(|&origin| {
 5623                    Bounds::new(origin, size(total_width, overall_height))
 5624                        .is_contained_within(hitbox)
 5625                })
 5626            });
 5627            if let Some(origin) = origin_surrounding_menu {
 5628                let mut current_y = origin.y;
 5629                for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 5630                    let size = popover.size;
 5631                    let popover_origin = point(origin.x, current_y);
 5632
 5633                    window.defer_draw(popover.element, popover_origin, 2);
 5634                    if position != itertools::Position::Last {
 5635                        let origin = point(popover_origin.x, popover_origin.y + size.height);
 5636                        draw_occluder(size.width, origin, window, cx);
 5637                    }
 5638
 5639                    current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 5640                }
 5641            } else {
 5642                // fallback to existing above/below cursor logic
 5643                // this might overlap menu or overflow in rare case
 5644                if can_place_above {
 5645                    place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
 5646                } else {
 5647                    place_popovers_below(
 5648                        hovered_point,
 5649                        measured_hover_popovers,
 5650                        line_height,
 5651                        window,
 5652                        cx,
 5653                    );
 5654                }
 5655            }
 5656        }
 5657    }
 5658
 5659    fn layout_word_diff_highlights(
 5660        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 5661        row_infos: &[RowInfo],
 5662        start_row: DisplayRow,
 5663        snapshot: &EditorSnapshot,
 5664        highlighted_ranges: &mut Vec<(Range<DisplayPoint>, Hsla)>,
 5665        cx: &mut App,
 5666    ) {
 5667        let colors = cx.theme().colors();
 5668
 5669        let word_highlights = display_hunks
 5670            .into_iter()
 5671            .filter_map(|(hunk, _)| match hunk {
 5672                DisplayDiffHunk::Unfolded {
 5673                    word_diffs, status, ..
 5674                } => Some((word_diffs, status)),
 5675                _ => None,
 5676            })
 5677            .filter(|(_, status)| status.is_modified())
 5678            .flat_map(|(word_diffs, _)| word_diffs)
 5679            .filter_map(|word_diff| {
 5680                let start_point = word_diff.start.to_display_point(&snapshot.display_snapshot);
 5681                let end_point = word_diff.end.to_display_point(&snapshot.display_snapshot);
 5682                let start_row_offset = start_point.row().0.saturating_sub(start_row.0) as usize;
 5683
 5684                row_infos
 5685                    .get(start_row_offset)
 5686                    .and_then(|row_info| row_info.diff_status)
 5687                    .and_then(|diff_status| {
 5688                        let background_color = match diff_status.kind {
 5689                            DiffHunkStatusKind::Added => colors.version_control_word_added,
 5690                            DiffHunkStatusKind::Deleted => colors.version_control_word_deleted,
 5691                            DiffHunkStatusKind::Modified => {
 5692                                debug_panic!("modified diff status for row info");
 5693                                return None;
 5694                            }
 5695                        };
 5696                        Some((start_point..end_point, background_color))
 5697                    })
 5698            });
 5699
 5700        highlighted_ranges.extend(word_highlights);
 5701    }
 5702
 5703    fn layout_diff_hunk_controls(
 5704        &self,
 5705        row_range: Range<DisplayRow>,
 5706        row_infos: &[RowInfo],
 5707        text_hitbox: &Hitbox,
 5708        newest_cursor_position: Option<DisplayPoint>,
 5709        line_height: Pixels,
 5710        right_margin: Pixels,
 5711        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 5712        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 5713        highlighted_rows: &BTreeMap<DisplayRow, LineHighlight>,
 5714        editor: Entity<Editor>,
 5715        window: &mut Window,
 5716        cx: &mut App,
 5717    ) -> (Vec<AnyElement>, Vec<(DisplayRow, Bounds<Pixels>)>) {
 5718        let render_diff_hunk_controls = editor.read(cx).render_diff_hunk_controls.clone();
 5719        let hovered_diff_hunk_row = editor.read(cx).hovered_diff_hunk_row;
 5720
 5721        let mut controls = vec![];
 5722        let mut control_bounds = vec![];
 5723
 5724        let active_positions = [
 5725            hovered_diff_hunk_row.map(|row| DisplayPoint::new(row, 0)),
 5726            newest_cursor_position,
 5727        ];
 5728
 5729        for (hunk, _) in display_hunks {
 5730            if let DisplayDiffHunk::Unfolded {
 5731                display_row_range,
 5732                multi_buffer_range,
 5733                status,
 5734                is_created_file,
 5735                ..
 5736            } = &hunk
 5737            {
 5738                if display_row_range.start < row_range.start
 5739                    || display_row_range.start >= row_range.end
 5740                {
 5741                    continue;
 5742                }
 5743                if highlighted_rows
 5744                    .get(&display_row_range.start)
 5745                    .and_then(|highlight| highlight.type_id)
 5746                    .is_some_and(|type_id| {
 5747                        [
 5748                            TypeId::of::<ConflictsOuter>(),
 5749                            TypeId::of::<ConflictsOursMarker>(),
 5750                            TypeId::of::<ConflictsOurs>(),
 5751                            TypeId::of::<ConflictsTheirs>(),
 5752                            TypeId::of::<ConflictsTheirsMarker>(),
 5753                        ]
 5754                        .contains(&type_id)
 5755                    })
 5756                {
 5757                    continue;
 5758                }
 5759                let row_ix = (display_row_range.start - row_range.start).0 as usize;
 5760                if row_infos[row_ix].diff_status.is_none() {
 5761                    continue;
 5762                }
 5763                if row_infos[row_ix]
 5764                    .diff_status
 5765                    .is_some_and(|status| status.is_added())
 5766                    && !status.is_added()
 5767                {
 5768                    continue;
 5769                }
 5770
 5771                if active_positions
 5772                    .iter()
 5773                    .any(|p| p.is_some_and(|p| display_row_range.contains(&p.row())))
 5774                {
 5775                    let y = (display_row_range.start.as_f64()
 5776                        * ScrollPixelOffset::from(line_height)
 5777                        + ScrollPixelOffset::from(text_hitbox.bounds.top())
 5778                        - scroll_pixel_position.y)
 5779                        .into();
 5780
 5781                    let mut element = render_diff_hunk_controls(
 5782                        display_row_range.start.0,
 5783                        status,
 5784                        multi_buffer_range.clone(),
 5785                        *is_created_file,
 5786                        line_height,
 5787                        &editor,
 5788                        window,
 5789                        cx,
 5790                    );
 5791                    let size =
 5792                        element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
 5793
 5794                    let x = text_hitbox.bounds.right() - right_margin - px(10.) - size.width;
 5795
 5796                    let bounds = Bounds::new(gpui::Point::new(x, y), size);
 5797                    control_bounds.push((display_row_range.start, bounds));
 5798
 5799                    window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
 5800                        element.prepaint(window, cx)
 5801                    });
 5802                    controls.push(element);
 5803                }
 5804            }
 5805        }
 5806
 5807        (controls, control_bounds)
 5808    }
 5809
 5810    fn layout_signature_help(
 5811        &self,
 5812        hitbox: &Hitbox,
 5813        content_origin: gpui::Point<Pixels>,
 5814        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 5815        newest_selection_head: Option<DisplayPoint>,
 5816        start_row: DisplayRow,
 5817        line_layouts: &[LineWithInvisibles],
 5818        line_height: Pixels,
 5819        em_width: Pixels,
 5820        context_menu_layout: Option<ContextMenuLayout>,
 5821        window: &mut Window,
 5822        cx: &mut App,
 5823    ) {
 5824        if !self.editor.focus_handle(cx).is_focused(window) {
 5825            return;
 5826        }
 5827        let Some(newest_selection_head) = newest_selection_head else {
 5828            return;
 5829        };
 5830
 5831        let max_size = size(
 5832            (120. * em_width) // Default size
 5833                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
 5834                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
 5835            (16. * line_height) // Default size
 5836                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
 5837                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
 5838        );
 5839
 5840        let maybe_element = self.editor.update(cx, |editor, cx| {
 5841            if let Some(popover) = editor.signature_help_state.popover_mut() {
 5842                let element = popover.render(max_size, window, cx);
 5843                Some(element)
 5844            } else {
 5845                None
 5846            }
 5847        });
 5848        let Some(mut element) = maybe_element else {
 5849            return;
 5850        };
 5851
 5852        let selection_row = newest_selection_head.row();
 5853        let Some(cursor_row_layout) = (selection_row >= start_row)
 5854            .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
 5855            .flatten()
 5856        else {
 5857            return;
 5858        };
 5859
 5860        let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
 5861            - Pixels::from(scroll_pixel_position.x);
 5862        let target_y = Pixels::from(
 5863            selection_row.as_f64() * ScrollPixelOffset::from(line_height) - scroll_pixel_position.y,
 5864        );
 5865        let target_point = content_origin + point(target_x, target_y);
 5866
 5867        let actual_size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
 5868
 5869        let (popover_bounds_above, popover_bounds_below) = {
 5870            let horizontal_offset = (hitbox.top_right().x
 5871                - POPOVER_RIGHT_OFFSET
 5872                - (target_point.x + actual_size.width))
 5873                .min(Pixels::ZERO);
 5874            let initial_x = target_point.x + horizontal_offset;
 5875            (
 5876                Bounds::new(
 5877                    point(initial_x, target_point.y - actual_size.height),
 5878                    actual_size,
 5879                ),
 5880                Bounds::new(
 5881                    point(initial_x, target_point.y + line_height + HOVER_POPOVER_GAP),
 5882                    actual_size,
 5883                ),
 5884            )
 5885        };
 5886
 5887        let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
 5888            context_menu_layout
 5889                .as_ref()
 5890                .is_some_and(|menu| bounds.intersects(&menu.bounds))
 5891        };
 5892
 5893        let final_origin = if popover_bounds_above.is_contained_within(hitbox)
 5894            && !intersects_menu(popover_bounds_above)
 5895        {
 5896            // try placing above cursor
 5897            popover_bounds_above.origin
 5898        } else if popover_bounds_below.is_contained_within(hitbox)
 5899            && !intersects_menu(popover_bounds_below)
 5900        {
 5901            // try placing below cursor
 5902            popover_bounds_below.origin
 5903        } else {
 5904            // try surrounding context menu if exists
 5905            let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
 5906                let y_for_horizontal_positioning = if menu.y_flipped {
 5907                    menu.bounds.bottom() - actual_size.height
 5908                } else {
 5909                    menu.bounds.top()
 5910                };
 5911                let possible_origins = vec![
 5912                    // left of context menu
 5913                    point(
 5914                        menu.bounds.left() - actual_size.width - HOVER_POPOVER_GAP,
 5915                        y_for_horizontal_positioning,
 5916                    ),
 5917                    // right of context menu
 5918                    point(
 5919                        menu.bounds.right() + HOVER_POPOVER_GAP,
 5920                        y_for_horizontal_positioning,
 5921                    ),
 5922                    // top of context menu
 5923                    point(
 5924                        menu.bounds.left(),
 5925                        menu.bounds.top() - actual_size.height - HOVER_POPOVER_GAP,
 5926                    ),
 5927                    // bottom of context menu
 5928                    point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
 5929                ];
 5930                possible_origins
 5931                    .into_iter()
 5932                    .find(|&origin| Bounds::new(origin, actual_size).is_contained_within(hitbox))
 5933            });
 5934            origin_surrounding_menu.unwrap_or_else(|| {
 5935                // fallback to existing above/below cursor logic
 5936                // this might overlap menu or overflow in rare case
 5937                if popover_bounds_above.is_contained_within(hitbox) {
 5938                    popover_bounds_above.origin
 5939                } else {
 5940                    popover_bounds_below.origin
 5941                }
 5942            })
 5943        };
 5944
 5945        window.defer_draw(element, final_origin, 2);
 5946    }
 5947
 5948    fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
 5949        window.paint_layer(layout.hitbox.bounds, |window| {
 5950            let scroll_top = layout.position_map.snapshot.scroll_position().y;
 5951            let gutter_bg = cx.theme().colors().editor_gutter_background;
 5952            window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
 5953            window.paint_quad(fill(
 5954                layout.position_map.text_hitbox.bounds,
 5955                self.style.background,
 5956            ));
 5957
 5958            if matches!(
 5959                layout.mode,
 5960                EditorMode::Full { .. } | EditorMode::Minimap { .. }
 5961            ) {
 5962                let show_active_line_background = match layout.mode {
 5963                    EditorMode::Full {
 5964                        show_active_line_background,
 5965                        ..
 5966                    } => show_active_line_background,
 5967                    EditorMode::Minimap { .. } => true,
 5968                    _ => false,
 5969                };
 5970                let mut active_rows = layout.active_rows.iter().peekable();
 5971                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
 5972                    let mut end_row = start_row.0;
 5973                    while active_rows
 5974                        .peek()
 5975                        .is_some_and(|(active_row, has_selection)| {
 5976                            active_row.0 == end_row + 1
 5977                                && has_selection.selection == contains_non_empty_selection.selection
 5978                        })
 5979                    {
 5980                        active_rows.next().unwrap();
 5981                        end_row += 1;
 5982                    }
 5983
 5984                    if show_active_line_background && !contains_non_empty_selection.selection {
 5985                        let highlight_h_range =
 5986                            match layout.position_map.snapshot.current_line_highlight {
 5987                                CurrentLineHighlight::Gutter => Some(Range {
 5988                                    start: layout.hitbox.left(),
 5989                                    end: layout.gutter_hitbox.right(),
 5990                                }),
 5991                                CurrentLineHighlight::Line => Some(Range {
 5992                                    start: layout.position_map.text_hitbox.bounds.left(),
 5993                                    end: layout.position_map.text_hitbox.bounds.right(),
 5994                                }),
 5995                                CurrentLineHighlight::All => Some(Range {
 5996                                    start: layout.hitbox.left(),
 5997                                    end: layout.hitbox.right(),
 5998                                }),
 5999                                CurrentLineHighlight::None => None,
 6000                            };
 6001                        if let Some(range) = highlight_h_range {
 6002                            let active_line_bg = cx.theme().colors().editor_active_line_background;
 6003                            let bounds = Bounds {
 6004                                origin: point(
 6005                                    range.start,
 6006                                    layout.hitbox.origin.y
 6007                                        + Pixels::from(
 6008                                            (start_row.as_f64() - scroll_top)
 6009                                                * ScrollPixelOffset::from(
 6010                                                    layout.position_map.line_height,
 6011                                                ),
 6012                                        ),
 6013                                ),
 6014                                size: size(
 6015                                    range.end - range.start,
 6016                                    layout.position_map.line_height
 6017                                        * (end_row - start_row.0 + 1) as f32,
 6018                                ),
 6019                            };
 6020                            window.paint_quad(fill(bounds, active_line_bg));
 6021                        }
 6022                    }
 6023                }
 6024
 6025                let mut paint_highlight = |highlight_row_start: DisplayRow,
 6026                                           highlight_row_end: DisplayRow,
 6027                                           highlight: crate::LineHighlight,
 6028                                           edges| {
 6029                    let mut origin_x = layout.hitbox.left();
 6030                    let mut width = layout.hitbox.size.width;
 6031                    if !highlight.include_gutter {
 6032                        origin_x += layout.gutter_hitbox.size.width;
 6033                        width -= layout.gutter_hitbox.size.width;
 6034                    }
 6035
 6036                    let origin = point(
 6037                        origin_x,
 6038                        layout.hitbox.origin.y
 6039                            + Pixels::from(
 6040                                (highlight_row_start.as_f64() - scroll_top)
 6041                                    * ScrollPixelOffset::from(layout.position_map.line_height),
 6042                            ),
 6043                    );
 6044                    let size = size(
 6045                        width,
 6046                        layout.position_map.line_height
 6047                            * highlight_row_end.next_row().minus(highlight_row_start) as f32,
 6048                    );
 6049                    let mut quad = fill(Bounds { origin, size }, highlight.background);
 6050                    if let Some(border_color) = highlight.border {
 6051                        quad.border_color = border_color;
 6052                        quad.border_widths = edges
 6053                    }
 6054                    window.paint_quad(quad);
 6055                };
 6056
 6057                let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
 6058                    None;
 6059                for (&new_row, &new_background) in &layout.highlighted_rows {
 6060                    match &mut current_paint {
 6061                        &mut Some((current_background, ref mut current_range, mut edges)) => {
 6062                            let new_range_started = current_background != new_background
 6063                                || current_range.end.next_row() != new_row;
 6064                            if new_range_started {
 6065                                if current_range.end.next_row() == new_row {
 6066                                    edges.bottom = px(0.);
 6067                                };
 6068                                paint_highlight(
 6069                                    current_range.start,
 6070                                    current_range.end,
 6071                                    current_background,
 6072                                    edges,
 6073                                );
 6074                                let edges = Edges {
 6075                                    top: if current_range.end.next_row() != new_row {
 6076                                        px(1.)
 6077                                    } else {
 6078                                        px(0.)
 6079                                    },
 6080                                    bottom: px(1.),
 6081                                    ..Default::default()
 6082                                };
 6083                                current_paint = Some((new_background, new_row..new_row, edges));
 6084                                continue;
 6085                            } else {
 6086                                current_range.end = current_range.end.next_row();
 6087                            }
 6088                        }
 6089                        None => {
 6090                            let edges = Edges {
 6091                                top: px(1.),
 6092                                bottom: px(1.),
 6093                                ..Default::default()
 6094                            };
 6095                            current_paint = Some((new_background, new_row..new_row, edges))
 6096                        }
 6097                    };
 6098                }
 6099                if let Some((color, range, edges)) = current_paint {
 6100                    paint_highlight(range.start, range.end, color, edges);
 6101                }
 6102
 6103                for (guide_x, active) in layout.wrap_guides.iter() {
 6104                    let color = if *active {
 6105                        cx.theme().colors().editor_active_wrap_guide
 6106                    } else {
 6107                        cx.theme().colors().editor_wrap_guide
 6108                    };
 6109                    window.paint_quad(fill(
 6110                        Bounds {
 6111                            origin: point(*guide_x, layout.position_map.text_hitbox.origin.y),
 6112                            size: size(px(1.), layout.position_map.text_hitbox.size.height),
 6113                        },
 6114                        color,
 6115                    ));
 6116                }
 6117            }
 6118        })
 6119    }
 6120
 6121    fn paint_indent_guides(
 6122        &mut self,
 6123        layout: &mut EditorLayout,
 6124        window: &mut Window,
 6125        cx: &mut App,
 6126    ) {
 6127        let Some(indent_guides) = &layout.indent_guides else {
 6128            return;
 6129        };
 6130
 6131        let faded_color = |color: Hsla, alpha: f32| {
 6132            let mut faded = color;
 6133            faded.a = alpha;
 6134            faded
 6135        };
 6136
 6137        for indent_guide in indent_guides {
 6138            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
 6139            let settings = &indent_guide.settings;
 6140
 6141            // TODO fixed for now, expose them through themes later
 6142            const INDENT_AWARE_ALPHA: f32 = 0.2;
 6143            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
 6144            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
 6145            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
 6146
 6147            let line_color = match (settings.coloring, indent_guide.active) {
 6148                (IndentGuideColoring::Disabled, _) => None,
 6149                (IndentGuideColoring::Fixed, false) => {
 6150                    Some(cx.theme().colors().editor_indent_guide)
 6151                }
 6152                (IndentGuideColoring::Fixed, true) => {
 6153                    Some(cx.theme().colors().editor_indent_guide_active)
 6154                }
 6155                (IndentGuideColoring::IndentAware, false) => {
 6156                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
 6157                }
 6158                (IndentGuideColoring::IndentAware, true) => {
 6159                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
 6160                }
 6161            };
 6162
 6163            let background_color = match (settings.background_coloring, indent_guide.active) {
 6164                (IndentGuideBackgroundColoring::Disabled, _) => None,
 6165                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
 6166                    indent_accent_colors,
 6167                    INDENT_AWARE_BACKGROUND_ALPHA,
 6168                )),
 6169                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
 6170                    indent_accent_colors,
 6171                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
 6172                )),
 6173            };
 6174
 6175            let requested_line_width = if indent_guide.active {
 6176                settings.active_line_width
 6177            } else {
 6178                settings.line_width
 6179            }
 6180            .clamp(1, 10);
 6181            let mut line_indicator_width = 0.;
 6182            if let Some(color) = line_color {
 6183                window.paint_quad(fill(
 6184                    Bounds {
 6185                        origin: indent_guide.origin,
 6186                        size: size(px(requested_line_width as f32), indent_guide.length),
 6187                    },
 6188                    color,
 6189                ));
 6190                line_indicator_width = requested_line_width as f32;
 6191            }
 6192
 6193            if let Some(color) = background_color {
 6194                let width = indent_guide.single_indent_width - px(line_indicator_width);
 6195                window.paint_quad(fill(
 6196                    Bounds {
 6197                        origin: point(
 6198                            indent_guide.origin.x + px(line_indicator_width),
 6199                            indent_guide.origin.y,
 6200                        ),
 6201                        size: size(width, indent_guide.length),
 6202                    },
 6203                    color,
 6204                ));
 6205            }
 6206        }
 6207    }
 6208
 6209    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6210        let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
 6211
 6212        let line_height = layout.position_map.line_height;
 6213        window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
 6214
 6215        for line_layout in layout.line_numbers.values() {
 6216            for LineNumberSegment {
 6217                shaped_line,
 6218                hitbox,
 6219            } in &line_layout.segments
 6220            {
 6221                let Some(hitbox) = hitbox else {
 6222                    continue;
 6223                };
 6224
 6225                let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
 6226                    let color = cx.theme().colors().editor_hover_line_number;
 6227
 6228                    let line = self.shape_line_number(shaped_line.text.clone(), color, window);
 6229                    line.paint(hitbox.origin, line_height, window, cx).log_err()
 6230                } else {
 6231                    shaped_line
 6232                        .paint(hitbox.origin, line_height, window, cx)
 6233                        .log_err()
 6234                }) else {
 6235                    continue;
 6236                };
 6237
 6238                // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
 6239                // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
 6240                if is_singleton {
 6241                    window.set_cursor_style(CursorStyle::IBeam, hitbox);
 6242                } else {
 6243                    window.set_cursor_style(CursorStyle::PointingHand, hitbox);
 6244                }
 6245            }
 6246        }
 6247    }
 6248
 6249    fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6250        if layout.display_hunks.is_empty() {
 6251            return;
 6252        }
 6253
 6254        let line_height = layout.position_map.line_height;
 6255        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6256            for (hunk, hitbox) in &layout.display_hunks {
 6257                let hunk_to_paint = match hunk {
 6258                    DisplayDiffHunk::Folded { .. } => {
 6259                        let hunk_bounds = Self::diff_hunk_bounds(
 6260                            &layout.position_map.snapshot,
 6261                            line_height,
 6262                            layout.gutter_hitbox.bounds,
 6263                            hunk,
 6264                        );
 6265                        Some((
 6266                            hunk_bounds,
 6267                            cx.theme().colors().version_control_modified,
 6268                            Corners::all(px(0.)),
 6269                            DiffHunkStatus::modified_none(),
 6270                        ))
 6271                    }
 6272                    DisplayDiffHunk::Unfolded {
 6273                        status,
 6274                        display_row_range,
 6275                        ..
 6276                    } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
 6277                        DiffHunkStatusKind::Added => (
 6278                            hunk_hitbox.bounds,
 6279                            cx.theme().colors().version_control_added,
 6280                            Corners::all(px(0.)),
 6281                            *status,
 6282                        ),
 6283                        DiffHunkStatusKind::Modified => (
 6284                            hunk_hitbox.bounds,
 6285                            cx.theme().colors().version_control_modified,
 6286                            Corners::all(px(0.)),
 6287                            *status,
 6288                        ),
 6289                        DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
 6290                            hunk_hitbox.bounds,
 6291                            cx.theme().colors().version_control_deleted,
 6292                            Corners::all(px(0.)),
 6293                            *status,
 6294                        ),
 6295                        DiffHunkStatusKind::Deleted => (
 6296                            Bounds::new(
 6297                                point(
 6298                                    hunk_hitbox.origin.x - hunk_hitbox.size.width,
 6299                                    hunk_hitbox.origin.y,
 6300                                ),
 6301                                size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
 6302                            ),
 6303                            cx.theme().colors().version_control_deleted,
 6304                            Corners::all(1. * line_height),
 6305                            *status,
 6306                        ),
 6307                    }),
 6308                };
 6309
 6310                if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
 6311                    // Flatten the background color with the editor color to prevent
 6312                    // elements below transparent hunks from showing through
 6313                    let flattened_background_color = cx
 6314                        .theme()
 6315                        .colors()
 6316                        .editor_background
 6317                        .blend(background_color);
 6318
 6319                    if !Self::diff_hunk_hollow(status, cx) {
 6320                        window.paint_quad(quad(
 6321                            hunk_bounds,
 6322                            corner_radii,
 6323                            flattened_background_color,
 6324                            Edges::default(),
 6325                            transparent_black(),
 6326                            BorderStyle::default(),
 6327                        ));
 6328                    } else {
 6329                        let flattened_unstaged_background_color = cx
 6330                            .theme()
 6331                            .colors()
 6332                            .editor_background
 6333                            .blend(background_color.opacity(0.3));
 6334
 6335                        window.paint_quad(quad(
 6336                            hunk_bounds,
 6337                            corner_radii,
 6338                            flattened_unstaged_background_color,
 6339                            Edges::all(px(1.0)),
 6340                            flattened_background_color,
 6341                            BorderStyle::Solid,
 6342                        ));
 6343                    }
 6344                }
 6345            }
 6346        });
 6347    }
 6348
 6349    fn gutter_strip_width(line_height: Pixels) -> Pixels {
 6350        (0.275 * line_height).floor()
 6351    }
 6352
 6353    fn diff_hunk_bounds(
 6354        snapshot: &EditorSnapshot,
 6355        line_height: Pixels,
 6356        gutter_bounds: Bounds<Pixels>,
 6357        hunk: &DisplayDiffHunk,
 6358    ) -> Bounds<Pixels> {
 6359        let scroll_position = snapshot.scroll_position();
 6360        let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
 6361        let gutter_strip_width = Self::gutter_strip_width(line_height);
 6362
 6363        match hunk {
 6364            DisplayDiffHunk::Folded { display_row, .. } => {
 6365                let start_y = (display_row.as_f64() * ScrollPixelOffset::from(line_height)
 6366                    - scroll_top)
 6367                    .into();
 6368                let end_y = start_y + line_height;
 6369                let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 6370                let highlight_size = size(gutter_strip_width, end_y - start_y);
 6371                Bounds::new(highlight_origin, highlight_size)
 6372            }
 6373            DisplayDiffHunk::Unfolded {
 6374                display_row_range,
 6375                status,
 6376                ..
 6377            } => {
 6378                if status.is_deleted() && display_row_range.is_empty() {
 6379                    let row = display_row_range.start;
 6380
 6381                    let offset = ScrollPixelOffset::from(line_height / 2.);
 6382                    let start_y =
 6383                        (row.as_f64() * ScrollPixelOffset::from(line_height) - offset - scroll_top)
 6384                            .into();
 6385                    let end_y = start_y + line_height;
 6386
 6387                    let width = (0.35 * line_height).floor();
 6388                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 6389                    let highlight_size = size(width, end_y - start_y);
 6390                    Bounds::new(highlight_origin, highlight_size)
 6391                } else {
 6392                    let start_row = display_row_range.start;
 6393                    let end_row = display_row_range.end;
 6394                    // If we're in a multibuffer, row range span might include an
 6395                    // excerpt header, so if we were to draw the marker straight away,
 6396                    // the hunk might include the rows of that header.
 6397                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
 6398                    // Instead, we simply check whether the range we're dealing with includes
 6399                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
 6400                    let end_row_in_current_excerpt = snapshot
 6401                        .blocks_in_range(start_row..end_row)
 6402                        .find_map(|(start_row, block)| {
 6403                            if matches!(
 6404                                block,
 6405                                Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
 6406                            ) {
 6407                                Some(start_row)
 6408                            } else {
 6409                                None
 6410                            }
 6411                        })
 6412                        .unwrap_or(end_row);
 6413
 6414                    let start_y = (start_row.as_f64() * ScrollPixelOffset::from(line_height)
 6415                        - scroll_top)
 6416                        .into();
 6417                    let end_y = Pixels::from(
 6418                        end_row_in_current_excerpt.as_f64() * ScrollPixelOffset::from(line_height)
 6419                            - scroll_top,
 6420                    );
 6421
 6422                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 6423                    let highlight_size = size(gutter_strip_width, end_y - start_y);
 6424                    Bounds::new(highlight_origin, highlight_size)
 6425                }
 6426            }
 6427        }
 6428    }
 6429
 6430    fn paint_gutter_indicators(
 6431        &self,
 6432        layout: &mut EditorLayout,
 6433        window: &mut Window,
 6434        cx: &mut App,
 6435    ) {
 6436        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6437            window.with_element_namespace("crease_toggles", |window| {
 6438                for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
 6439                    crease_toggle.paint(window, cx);
 6440                }
 6441            });
 6442
 6443            window.with_element_namespace("expand_toggles", |window| {
 6444                for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
 6445                    expand_toggle.paint(window, cx);
 6446                }
 6447            });
 6448
 6449            for breakpoint in layout.breakpoints.iter_mut() {
 6450                breakpoint.paint(window, cx);
 6451            }
 6452
 6453            for test_indicator in layout.test_indicators.iter_mut() {
 6454                test_indicator.paint(window, cx);
 6455            }
 6456        });
 6457    }
 6458
 6459    fn paint_gutter_highlights(
 6460        &self,
 6461        layout: &mut EditorLayout,
 6462        window: &mut Window,
 6463        cx: &mut App,
 6464    ) {
 6465        for (_, hunk_hitbox) in &layout.display_hunks {
 6466            if let Some(hunk_hitbox) = hunk_hitbox
 6467                && !self
 6468                    .editor
 6469                    .read(cx)
 6470                    .buffer()
 6471                    .read(cx)
 6472                    .all_diff_hunks_expanded()
 6473            {
 6474                window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
 6475            }
 6476        }
 6477
 6478        let show_git_gutter = layout
 6479            .position_map
 6480            .snapshot
 6481            .show_git_diff_gutter
 6482            .unwrap_or_else(|| {
 6483                matches!(
 6484                    ProjectSettings::get_global(cx).git.git_gutter,
 6485                    GitGutterSetting::TrackedFiles
 6486                )
 6487            });
 6488        if show_git_gutter {
 6489            Self::paint_gutter_diff_hunks(layout, window, cx)
 6490        }
 6491
 6492        let highlight_width = 0.275 * layout.position_map.line_height;
 6493        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
 6494        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6495            for (range, color) in &layout.highlighted_gutter_ranges {
 6496                let start_row = if range.start.row() < layout.visible_display_row_range.start {
 6497                    layout.visible_display_row_range.start - DisplayRow(1)
 6498                } else {
 6499                    range.start.row()
 6500                };
 6501                let end_row = if range.end.row() > layout.visible_display_row_range.end {
 6502                    layout.visible_display_row_range.end + DisplayRow(1)
 6503                } else {
 6504                    range.end.row()
 6505                };
 6506
 6507                let start_y = layout.gutter_hitbox.top()
 6508                    + Pixels::from(
 6509                        start_row.0 as f64
 6510                            * ScrollPixelOffset::from(layout.position_map.line_height)
 6511                            - layout.position_map.scroll_pixel_position.y,
 6512                    );
 6513                let end_y = layout.gutter_hitbox.top()
 6514                    + Pixels::from(
 6515                        (end_row.0 + 1) as f64
 6516                            * ScrollPixelOffset::from(layout.position_map.line_height)
 6517                            - layout.position_map.scroll_pixel_position.y,
 6518                    );
 6519                let bounds = Bounds::from_corners(
 6520                    point(layout.gutter_hitbox.left(), start_y),
 6521                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
 6522                );
 6523                window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
 6524            }
 6525        });
 6526    }
 6527
 6528    fn paint_blamed_display_rows(
 6529        &self,
 6530        layout: &mut EditorLayout,
 6531        window: &mut Window,
 6532        cx: &mut App,
 6533    ) {
 6534        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
 6535            return;
 6536        };
 6537
 6538        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6539            for mut blame_element in blamed_display_rows.into_iter() {
 6540                blame_element.paint(window, cx);
 6541            }
 6542        })
 6543    }
 6544
 6545    fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6546        window.with_content_mask(
 6547            Some(ContentMask {
 6548                bounds: layout.position_map.text_hitbox.bounds,
 6549            }),
 6550            |window| {
 6551                let editor = self.editor.read(cx);
 6552                if editor.mouse_cursor_hidden {
 6553                    window.set_window_cursor_style(CursorStyle::None);
 6554                } else if let SelectionDragState::ReadyToDrag {
 6555                    mouse_down_time, ..
 6556                } = &editor.selection_drag_state
 6557                {
 6558                    let drag_and_drop_delay = Duration::from_millis(
 6559                        EditorSettings::get_global(cx)
 6560                            .drag_and_drop_selection
 6561                            .delay
 6562                            .0,
 6563                    );
 6564                    if mouse_down_time.elapsed() >= drag_and_drop_delay {
 6565                        window.set_cursor_style(
 6566                            CursorStyle::DragCopy,
 6567                            &layout.position_map.text_hitbox,
 6568                        );
 6569                    }
 6570                } else if matches!(
 6571                    editor.selection_drag_state,
 6572                    SelectionDragState::Dragging { .. }
 6573                ) {
 6574                    window
 6575                        .set_cursor_style(CursorStyle::DragCopy, &layout.position_map.text_hitbox);
 6576                } else if editor
 6577                    .hovered_link_state
 6578                    .as_ref()
 6579                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
 6580                {
 6581                    window.set_cursor_style(
 6582                        CursorStyle::PointingHand,
 6583                        &layout.position_map.text_hitbox,
 6584                    );
 6585                } else {
 6586                    window.set_cursor_style(CursorStyle::IBeam, &layout.position_map.text_hitbox);
 6587                };
 6588
 6589                self.paint_lines_background(layout, window, cx);
 6590                let invisible_display_ranges = self.paint_highlights(layout, window, cx);
 6591                self.paint_document_colors(layout, window);
 6592                self.paint_lines(&invisible_display_ranges, layout, window, cx);
 6593                self.paint_redactions(layout, window);
 6594                self.paint_cursors(layout, window, cx);
 6595                self.paint_inline_diagnostics(layout, window, cx);
 6596                self.paint_inline_blame(layout, window, cx);
 6597                self.paint_inline_code_actions(layout, window, cx);
 6598                self.paint_diff_hunk_controls(layout, window, cx);
 6599                window.with_element_namespace("crease_trailers", |window| {
 6600                    for trailer in layout.crease_trailers.iter_mut().flatten() {
 6601                        trailer.element.paint(window, cx);
 6602                    }
 6603                });
 6604            },
 6605        )
 6606    }
 6607
 6608    fn paint_highlights(
 6609        &mut self,
 6610        layout: &mut EditorLayout,
 6611        window: &mut Window,
 6612        cx: &mut App,
 6613    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
 6614        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6615            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
 6616            let line_end_overshoot = 0.15 * layout.position_map.line_height;
 6617            for (range, color) in &layout.highlighted_ranges {
 6618                self.paint_highlighted_range(
 6619                    range.clone(),
 6620                    true,
 6621                    *color,
 6622                    Pixels::ZERO,
 6623                    line_end_overshoot,
 6624                    layout,
 6625                    window,
 6626                );
 6627            }
 6628
 6629            let corner_radius = if EditorSettings::get_global(cx).rounded_selection {
 6630                0.15 * layout.position_map.line_height
 6631            } else {
 6632                Pixels::ZERO
 6633            };
 6634
 6635            for (player_color, selections) in &layout.selections {
 6636                for selection in selections.iter() {
 6637                    self.paint_highlighted_range(
 6638                        selection.range.clone(),
 6639                        true,
 6640                        player_color.selection,
 6641                        corner_radius,
 6642                        corner_radius * 2.,
 6643                        layout,
 6644                        window,
 6645                    );
 6646
 6647                    if selection.is_local && !selection.range.is_empty() {
 6648                        invisible_display_ranges.push(selection.range.clone());
 6649                    }
 6650                }
 6651            }
 6652            invisible_display_ranges
 6653        })
 6654    }
 6655
 6656    fn paint_lines(
 6657        &mut self,
 6658        invisible_display_ranges: &[Range<DisplayPoint>],
 6659        layout: &mut EditorLayout,
 6660        window: &mut Window,
 6661        cx: &mut App,
 6662    ) {
 6663        let whitespace_setting = self
 6664            .editor
 6665            .read(cx)
 6666            .buffer
 6667            .read(cx)
 6668            .language_settings(cx)
 6669            .show_whitespaces;
 6670
 6671        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
 6672            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
 6673            line_with_invisibles.draw(
 6674                layout,
 6675                row,
 6676                layout.content_origin,
 6677                whitespace_setting,
 6678                invisible_display_ranges,
 6679                window,
 6680                cx,
 6681            )
 6682        }
 6683
 6684        for line_element in &mut layout.line_elements {
 6685            line_element.paint(window, cx);
 6686        }
 6687    }
 6688
 6689    fn paint_sticky_headers(
 6690        &mut self,
 6691        layout: &mut EditorLayout,
 6692        window: &mut Window,
 6693        cx: &mut App,
 6694    ) {
 6695        let Some(mut sticky_headers) = layout.sticky_headers.take() else {
 6696            return;
 6697        };
 6698
 6699        if sticky_headers.lines.is_empty() {
 6700            layout.sticky_headers = Some(sticky_headers);
 6701            return;
 6702        }
 6703
 6704        let whitespace_setting = self
 6705            .editor
 6706            .read(cx)
 6707            .buffer
 6708            .read(cx)
 6709            .language_settings(cx)
 6710            .show_whitespaces;
 6711        sticky_headers.paint(layout, whitespace_setting, window, cx);
 6712
 6713        let sticky_header_hitboxes: Vec<Hitbox> = sticky_headers
 6714            .lines
 6715            .iter()
 6716            .map(|line| line.hitbox.clone())
 6717            .collect();
 6718        let hovered_hitbox = sticky_header_hitboxes
 6719            .iter()
 6720            .find_map(|hitbox| hitbox.is_hovered(window).then_some(hitbox.id));
 6721
 6722        window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, _cx| {
 6723            if !phase.bubble() {
 6724                return;
 6725            }
 6726
 6727            let current_hover = sticky_header_hitboxes
 6728                .iter()
 6729                .find_map(|hitbox| hitbox.is_hovered(window).then_some(hitbox.id));
 6730            if hovered_hitbox != current_hover {
 6731                window.refresh();
 6732            }
 6733        });
 6734
 6735        for (line_index, line) in sticky_headers.lines.iter().enumerate() {
 6736            let editor = self.editor.clone();
 6737            let hitbox = line.hitbox.clone();
 6738            let target_anchor = line.target_anchor;
 6739            window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
 6740                if !phase.bubble() {
 6741                    return;
 6742                }
 6743
 6744                if event.button == MouseButton::Left && hitbox.is_hovered(window) {
 6745                    editor.update(cx, |editor, cx| {
 6746                        editor.change_selections(
 6747                            SelectionEffects::scroll(Autoscroll::top_relative(line_index)),
 6748                            window,
 6749                            cx,
 6750                            |selections| selections.select_ranges([target_anchor..target_anchor]),
 6751                        );
 6752                        cx.stop_propagation();
 6753                    });
 6754                }
 6755            });
 6756        }
 6757
 6758        let text_bounds = layout.position_map.text_hitbox.bounds;
 6759        let border_top = text_bounds.top()
 6760            + sticky_headers.lines.last().unwrap().offset
 6761            + layout.position_map.line_height;
 6762        let separator_height = px(1.);
 6763        let border_bounds = Bounds::from_corners(
 6764            point(layout.gutter_hitbox.bounds.left(), border_top),
 6765            point(text_bounds.right(), border_top + separator_height),
 6766        );
 6767        window.paint_quad(fill(border_bounds, cx.theme().colors().border_variant));
 6768
 6769        layout.sticky_headers = Some(sticky_headers);
 6770    }
 6771
 6772    fn paint_lines_background(
 6773        &mut self,
 6774        layout: &mut EditorLayout,
 6775        window: &mut Window,
 6776        cx: &mut App,
 6777    ) {
 6778        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
 6779            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
 6780            line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
 6781        }
 6782    }
 6783
 6784    fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
 6785        if layout.redacted_ranges.is_empty() {
 6786            return;
 6787        }
 6788
 6789        let line_end_overshoot = layout.line_end_overshoot();
 6790
 6791        // A softer than perfect black
 6792        let redaction_color = gpui::rgb(0x0e1111);
 6793
 6794        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6795            for range in layout.redacted_ranges.iter() {
 6796                self.paint_highlighted_range(
 6797                    range.clone(),
 6798                    true,
 6799                    redaction_color.into(),
 6800                    Pixels::ZERO,
 6801                    line_end_overshoot,
 6802                    layout,
 6803                    window,
 6804                );
 6805            }
 6806        });
 6807    }
 6808
 6809    fn paint_document_colors(&self, layout: &mut EditorLayout, window: &mut Window) {
 6810        let Some((colors_render_mode, image_colors)) = &layout.document_colors else {
 6811            return;
 6812        };
 6813        if image_colors.is_empty()
 6814            || colors_render_mode == &DocumentColorsRenderMode::None
 6815            || colors_render_mode == &DocumentColorsRenderMode::Inlay
 6816        {
 6817            return;
 6818        }
 6819
 6820        let line_end_overshoot = layout.line_end_overshoot();
 6821
 6822        for (range, color) in image_colors {
 6823            match colors_render_mode {
 6824                DocumentColorsRenderMode::Inlay | DocumentColorsRenderMode::None => return,
 6825                DocumentColorsRenderMode::Background => {
 6826                    self.paint_highlighted_range(
 6827                        range.clone(),
 6828                        true,
 6829                        *color,
 6830                        Pixels::ZERO,
 6831                        line_end_overshoot,
 6832                        layout,
 6833                        window,
 6834                    );
 6835                }
 6836                DocumentColorsRenderMode::Border => {
 6837                    self.paint_highlighted_range(
 6838                        range.clone(),
 6839                        false,
 6840                        *color,
 6841                        Pixels::ZERO,
 6842                        line_end_overshoot,
 6843                        layout,
 6844                        window,
 6845                    );
 6846                }
 6847            }
 6848        }
 6849    }
 6850
 6851    fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6852        for cursor in &mut layout.visible_cursors {
 6853            cursor.paint(layout.content_origin, window, cx);
 6854        }
 6855    }
 6856
 6857    fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6858        let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
 6859            return;
 6860        };
 6861        let any_scrollbar_dragged = self.editor.read(cx).scroll_manager.any_scrollbar_dragged();
 6862
 6863        for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
 6864            let hitbox = &scrollbar_layout.hitbox;
 6865            if scrollbars_layout.visible {
 6866                let scrollbar_edges = match axis {
 6867                    ScrollbarAxis::Horizontal => Edges {
 6868                        top: Pixels::ZERO,
 6869                        right: Pixels::ZERO,
 6870                        bottom: Pixels::ZERO,
 6871                        left: Pixels::ZERO,
 6872                    },
 6873                    ScrollbarAxis::Vertical => Edges {
 6874                        top: Pixels::ZERO,
 6875                        right: Pixels::ZERO,
 6876                        bottom: Pixels::ZERO,
 6877                        left: ScrollbarLayout::BORDER_WIDTH,
 6878                    },
 6879                };
 6880
 6881                window.paint_layer(hitbox.bounds, |window| {
 6882                    window.paint_quad(quad(
 6883                        hitbox.bounds,
 6884                        Corners::default(),
 6885                        cx.theme().colors().scrollbar_track_background,
 6886                        scrollbar_edges,
 6887                        cx.theme().colors().scrollbar_track_border,
 6888                        BorderStyle::Solid,
 6889                    ));
 6890
 6891                    if axis == ScrollbarAxis::Vertical {
 6892                        let fast_markers =
 6893                            self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
 6894                        // Refresh slow scrollbar markers in the background. Below, we
 6895                        // paint whatever markers have already been computed.
 6896                        self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, window, cx);
 6897
 6898                        let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
 6899                        for marker in markers.iter().chain(&fast_markers) {
 6900                            let mut marker = marker.clone();
 6901                            marker.bounds.origin += hitbox.origin;
 6902                            window.paint_quad(marker);
 6903                        }
 6904                    }
 6905
 6906                    if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
 6907                        let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
 6908                            ScrollbarThumbState::Dragging => {
 6909                                cx.theme().colors().scrollbar_thumb_active_background
 6910                            }
 6911                            ScrollbarThumbState::Hovered => {
 6912                                cx.theme().colors().scrollbar_thumb_hover_background
 6913                            }
 6914                            ScrollbarThumbState::Idle => {
 6915                                cx.theme().colors().scrollbar_thumb_background
 6916                            }
 6917                        };
 6918                        window.paint_quad(quad(
 6919                            thumb_bounds,
 6920                            Corners::default(),
 6921                            scrollbar_thumb_color,
 6922                            scrollbar_edges,
 6923                            cx.theme().colors().scrollbar_thumb_border,
 6924                            BorderStyle::Solid,
 6925                        ));
 6926
 6927                        if any_scrollbar_dragged {
 6928                            window.set_window_cursor_style(CursorStyle::Arrow);
 6929                        } else {
 6930                            window.set_cursor_style(CursorStyle::Arrow, hitbox);
 6931                        }
 6932                    }
 6933                })
 6934            }
 6935        }
 6936
 6937        window.on_mouse_event({
 6938            let editor = self.editor.clone();
 6939            let scrollbars_layout = scrollbars_layout.clone();
 6940
 6941            let mut mouse_position = window.mouse_position();
 6942            move |event: &MouseMoveEvent, phase, window, cx| {
 6943                if phase == DispatchPhase::Capture {
 6944                    return;
 6945                }
 6946
 6947                editor.update(cx, |editor, cx| {
 6948                    if let Some((scrollbar_layout, axis)) = event
 6949                        .pressed_button
 6950                        .filter(|button| *button == MouseButton::Left)
 6951                        .and(editor.scroll_manager.dragging_scrollbar_axis())
 6952                        .and_then(|axis| {
 6953                            scrollbars_layout
 6954                                .iter_scrollbars()
 6955                                .find(|(_, a)| *a == axis)
 6956                        })
 6957                    {
 6958                        let ScrollbarLayout {
 6959                            hitbox,
 6960                            text_unit_size,
 6961                            ..
 6962                        } = scrollbar_layout;
 6963
 6964                        let old_position = mouse_position.along(axis);
 6965                        let new_position = event.position.along(axis);
 6966                        if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
 6967                            .contains(&old_position)
 6968                        {
 6969                            let position = editor.scroll_position(cx).apply_along(axis, |p| {
 6970                                (p + ScrollOffset::from(
 6971                                    (new_position - old_position) / *text_unit_size,
 6972                                ))
 6973                                .max(0.)
 6974                            });
 6975                            editor.set_scroll_position(position, window, cx);
 6976                        }
 6977
 6978                        editor.scroll_manager.show_scrollbars(window, cx);
 6979                        cx.stop_propagation();
 6980                    } else if let Some((layout, axis)) = scrollbars_layout
 6981                        .get_hovered_axis(window)
 6982                        .filter(|_| !event.dragging())
 6983                    {
 6984                        if layout.thumb_hovered(&event.position) {
 6985                            editor
 6986                                .scroll_manager
 6987                                .set_hovered_scroll_thumb_axis(axis, cx);
 6988                        } else {
 6989                            editor.scroll_manager.reset_scrollbar_state(cx);
 6990                        }
 6991
 6992                        editor.scroll_manager.show_scrollbars(window, cx);
 6993                    } else {
 6994                        editor.scroll_manager.reset_scrollbar_state(cx);
 6995                    }
 6996
 6997                    mouse_position = event.position;
 6998                })
 6999            }
 7000        });
 7001
 7002        if any_scrollbar_dragged {
 7003            window.on_mouse_event({
 7004                let editor = self.editor.clone();
 7005                move |_: &MouseUpEvent, phase, window, cx| {
 7006                    if phase == DispatchPhase::Capture {
 7007                        return;
 7008                    }
 7009
 7010                    editor.update(cx, |editor, cx| {
 7011                        if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
 7012                            editor
 7013                                .scroll_manager
 7014                                .set_hovered_scroll_thumb_axis(axis, cx);
 7015                        } else {
 7016                            editor.scroll_manager.reset_scrollbar_state(cx);
 7017                        }
 7018                        cx.stop_propagation();
 7019                    });
 7020                }
 7021            });
 7022        } else {
 7023            window.on_mouse_event({
 7024                let editor = self.editor.clone();
 7025
 7026                move |event: &MouseDownEvent, phase, window, cx| {
 7027                    if phase == DispatchPhase::Capture {
 7028                        return;
 7029                    }
 7030                    let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
 7031                    else {
 7032                        return;
 7033                    };
 7034
 7035                    let ScrollbarLayout {
 7036                        hitbox,
 7037                        visible_range,
 7038                        text_unit_size,
 7039                        thumb_bounds,
 7040                        ..
 7041                    } = scrollbar_layout;
 7042
 7043                    let Some(thumb_bounds) = thumb_bounds else {
 7044                        return;
 7045                    };
 7046
 7047                    editor.update(cx, |editor, cx| {
 7048                        editor
 7049                            .scroll_manager
 7050                            .set_dragged_scroll_thumb_axis(axis, cx);
 7051
 7052                        let event_position = event.position.along(axis);
 7053
 7054                        if event_position < thumb_bounds.origin.along(axis)
 7055                            || thumb_bounds.bottom_right().along(axis) < event_position
 7056                        {
 7057                            let center_position = ((event_position - hitbox.origin.along(axis))
 7058                                / *text_unit_size)
 7059                                .round() as u32;
 7060                            let start_position = center_position.saturating_sub(
 7061                                (visible_range.end - visible_range.start) as u32 / 2,
 7062                            );
 7063
 7064                            let position = editor
 7065                                .scroll_position(cx)
 7066                                .apply_along(axis, |_| start_position as ScrollOffset);
 7067
 7068                            editor.set_scroll_position(position, window, cx);
 7069                        } else {
 7070                            editor.scroll_manager.show_scrollbars(window, cx);
 7071                        }
 7072
 7073                        cx.stop_propagation();
 7074                    });
 7075                }
 7076            });
 7077        }
 7078    }
 7079
 7080    fn collect_fast_scrollbar_markers(
 7081        &self,
 7082        layout: &EditorLayout,
 7083        scrollbar_layout: &ScrollbarLayout,
 7084        cx: &mut App,
 7085    ) -> Vec<PaintQuad> {
 7086        const LIMIT: usize = 100;
 7087        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
 7088            return vec![];
 7089        }
 7090        let cursor_ranges = layout
 7091            .cursors
 7092            .iter()
 7093            .map(|(point, color)| ColoredRange {
 7094                start: point.row(),
 7095                end: point.row(),
 7096                color: *color,
 7097            })
 7098            .collect_vec();
 7099        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
 7100    }
 7101
 7102    fn refresh_slow_scrollbar_markers(
 7103        &self,
 7104        layout: &EditorLayout,
 7105        scrollbar_layout: &ScrollbarLayout,
 7106        window: &mut Window,
 7107        cx: &mut App,
 7108    ) {
 7109        self.editor.update(cx, |editor, cx| {
 7110            if editor.buffer_kind(cx) != ItemBufferKind::Singleton
 7111                || !editor
 7112                    .scrollbar_marker_state
 7113                    .should_refresh(scrollbar_layout.hitbox.size)
 7114            {
 7115                return;
 7116            }
 7117
 7118            let scrollbar_layout = scrollbar_layout.clone();
 7119            let background_highlights = editor.background_highlights.clone();
 7120            let snapshot = layout.position_map.snapshot.clone();
 7121            let theme = cx.theme().clone();
 7122            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
 7123
 7124            editor.scrollbar_marker_state.dirty = false;
 7125            editor.scrollbar_marker_state.pending_refresh =
 7126                Some(cx.spawn_in(window, async move |editor, cx| {
 7127                    let scrollbar_size = scrollbar_layout.hitbox.size;
 7128                    let scrollbar_markers = cx
 7129                        .background_spawn(async move {
 7130                            let max_point = snapshot.display_snapshot.buffer_snapshot().max_point();
 7131                            let mut marker_quads = Vec::new();
 7132                            if scrollbar_settings.git_diff {
 7133                                let marker_row_ranges =
 7134                                    snapshot.buffer_snapshot().diff_hunks().map(|hunk| {
 7135                                        let start_display_row =
 7136                                            MultiBufferPoint::new(hunk.row_range.start.0, 0)
 7137                                                .to_display_point(&snapshot.display_snapshot)
 7138                                                .row();
 7139                                        let mut end_display_row =
 7140                                            MultiBufferPoint::new(hunk.row_range.end.0, 0)
 7141                                                .to_display_point(&snapshot.display_snapshot)
 7142                                                .row();
 7143                                        if end_display_row != start_display_row {
 7144                                            end_display_row.0 -= 1;
 7145                                        }
 7146                                        let color = match &hunk.status().kind {
 7147                                            DiffHunkStatusKind::Added => {
 7148                                                theme.colors().version_control_added
 7149                                            }
 7150                                            DiffHunkStatusKind::Modified => {
 7151                                                theme.colors().version_control_modified
 7152                                            }
 7153                                            DiffHunkStatusKind::Deleted => {
 7154                                                theme.colors().version_control_deleted
 7155                                            }
 7156                                        };
 7157                                        ColoredRange {
 7158                                            start: start_display_row,
 7159                                            end: end_display_row,
 7160                                            color,
 7161                                        }
 7162                                    });
 7163
 7164                                marker_quads.extend(
 7165                                    scrollbar_layout
 7166                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
 7167                                );
 7168                            }
 7169
 7170                            for (background_highlight_id, (_, background_ranges)) in
 7171                                background_highlights.iter()
 7172                            {
 7173                                let is_search_highlights = *background_highlight_id
 7174                                    == HighlightKey::Type(TypeId::of::<BufferSearchHighlights>());
 7175                                let is_text_highlights = *background_highlight_id
 7176                                    == HighlightKey::Type(TypeId::of::<SelectedTextHighlight>());
 7177                                let is_symbol_occurrences = *background_highlight_id
 7178                                    == HighlightKey::Type(TypeId::of::<DocumentHighlightRead>())
 7179                                    || *background_highlight_id
 7180                                        == HighlightKey::Type(
 7181                                            TypeId::of::<DocumentHighlightWrite>(),
 7182                                        );
 7183                                if (is_search_highlights && scrollbar_settings.search_results)
 7184                                    || (is_text_highlights && scrollbar_settings.selected_text)
 7185                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
 7186                                {
 7187                                    let mut color = theme.status().info;
 7188                                    if is_symbol_occurrences {
 7189                                        color.fade_out(0.5);
 7190                                    }
 7191                                    let marker_row_ranges = background_ranges.iter().map(|range| {
 7192                                        let display_start = range
 7193                                            .start
 7194                                            .to_display_point(&snapshot.display_snapshot);
 7195                                        let display_end =
 7196                                            range.end.to_display_point(&snapshot.display_snapshot);
 7197                                        ColoredRange {
 7198                                            start: display_start.row(),
 7199                                            end: display_end.row(),
 7200                                            color,
 7201                                        }
 7202                                    });
 7203                                    marker_quads.extend(
 7204                                        scrollbar_layout
 7205                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
 7206                                    );
 7207                                }
 7208                            }
 7209
 7210                            if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
 7211                                let diagnostics = snapshot
 7212                                    .buffer_snapshot()
 7213                                    .diagnostics_in_range::<Point>(Point::zero()..max_point)
 7214                                    // Don't show diagnostics the user doesn't care about
 7215                                    .filter(|diagnostic| {
 7216                                        match (
 7217                                            scrollbar_settings.diagnostics,
 7218                                            diagnostic.diagnostic.severity,
 7219                                        ) {
 7220                                            (ScrollbarDiagnostics::All, _) => true,
 7221                                            (
 7222                                                ScrollbarDiagnostics::Error,
 7223                                                lsp::DiagnosticSeverity::ERROR,
 7224                                            ) => true,
 7225                                            (
 7226                                                ScrollbarDiagnostics::Warning,
 7227                                                lsp::DiagnosticSeverity::ERROR
 7228                                                | lsp::DiagnosticSeverity::WARNING,
 7229                                            ) => true,
 7230                                            (
 7231                                                ScrollbarDiagnostics::Information,
 7232                                                lsp::DiagnosticSeverity::ERROR
 7233                                                | lsp::DiagnosticSeverity::WARNING
 7234                                                | lsp::DiagnosticSeverity::INFORMATION,
 7235                                            ) => true,
 7236                                            (_, _) => false,
 7237                                        }
 7238                                    })
 7239                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
 7240                                    .sorted_by_key(|diagnostic| {
 7241                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
 7242                                    });
 7243
 7244                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
 7245                                    let start_display = diagnostic
 7246                                        .range
 7247                                        .start
 7248                                        .to_display_point(&snapshot.display_snapshot);
 7249                                    let end_display = diagnostic
 7250                                        .range
 7251                                        .end
 7252                                        .to_display_point(&snapshot.display_snapshot);
 7253                                    let color = match diagnostic.diagnostic.severity {
 7254                                        lsp::DiagnosticSeverity::ERROR => theme.status().error,
 7255                                        lsp::DiagnosticSeverity::WARNING => theme.status().warning,
 7256                                        lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
 7257                                        _ => theme.status().hint,
 7258                                    };
 7259                                    ColoredRange {
 7260                                        start: start_display.row(),
 7261                                        end: end_display.row(),
 7262                                        color,
 7263                                    }
 7264                                });
 7265                                marker_quads.extend(
 7266                                    scrollbar_layout
 7267                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
 7268                                );
 7269                            }
 7270
 7271                            Arc::from(marker_quads)
 7272                        })
 7273                        .await;
 7274
 7275                    editor.update(cx, |editor, cx| {
 7276                        editor.scrollbar_marker_state.markers = scrollbar_markers;
 7277                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
 7278                        editor.scrollbar_marker_state.pending_refresh = None;
 7279                        cx.notify();
 7280                    })?;
 7281
 7282                    Ok(())
 7283                }));
 7284        });
 7285    }
 7286
 7287    fn paint_highlighted_range(
 7288        &self,
 7289        range: Range<DisplayPoint>,
 7290        fill: bool,
 7291        color: Hsla,
 7292        corner_radius: Pixels,
 7293        line_end_overshoot: Pixels,
 7294        layout: &EditorLayout,
 7295        window: &mut Window,
 7296    ) {
 7297        let start_row = layout.visible_display_row_range.start;
 7298        let end_row = layout.visible_display_row_range.end;
 7299        if range.start != range.end {
 7300            let row_range = if range.end.column() == 0 {
 7301                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
 7302            } else {
 7303                cmp::max(range.start.row(), start_row)
 7304                    ..cmp::min(range.end.row().next_row(), end_row)
 7305            };
 7306
 7307            let highlighted_range = HighlightedRange {
 7308                color,
 7309                line_height: layout.position_map.line_height,
 7310                corner_radius,
 7311                start_y: layout.content_origin.y
 7312                    + Pixels::from(
 7313                        (row_range.start.as_f64() - layout.position_map.scroll_position.y)
 7314                            * ScrollOffset::from(layout.position_map.line_height),
 7315                    ),
 7316                lines: row_range
 7317                    .iter_rows()
 7318                    .map(|row| {
 7319                        let line_layout =
 7320                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
 7321                        HighlightedRangeLine {
 7322                            start_x: if row == range.start.row() {
 7323                                layout.content_origin.x
 7324                                    + Pixels::from(
 7325                                        ScrollPixelOffset::from(
 7326                                            line_layout.x_for_index(range.start.column() as usize),
 7327                                        ) - layout.position_map.scroll_pixel_position.x,
 7328                                    )
 7329                            } else {
 7330                                layout.content_origin.x
 7331                                    - Pixels::from(layout.position_map.scroll_pixel_position.x)
 7332                            },
 7333                            end_x: if row == range.end.row() {
 7334                                layout.content_origin.x
 7335                                    + Pixels::from(
 7336                                        ScrollPixelOffset::from(
 7337                                            line_layout.x_for_index(range.end.column() as usize),
 7338                                        ) - layout.position_map.scroll_pixel_position.x,
 7339                                    )
 7340                            } else {
 7341                                Pixels::from(
 7342                                    ScrollPixelOffset::from(
 7343                                        layout.content_origin.x
 7344                                            + line_layout.width
 7345                                            + line_end_overshoot,
 7346                                    ) - layout.position_map.scroll_pixel_position.x,
 7347                                )
 7348                            },
 7349                        }
 7350                    })
 7351                    .collect(),
 7352            };
 7353
 7354            highlighted_range.paint(fill, layout.position_map.text_hitbox.bounds, window);
 7355        }
 7356    }
 7357
 7358    fn paint_inline_diagnostics(
 7359        &mut self,
 7360        layout: &mut EditorLayout,
 7361        window: &mut Window,
 7362        cx: &mut App,
 7363    ) {
 7364        for mut inline_diagnostic in layout.inline_diagnostics.drain() {
 7365            inline_diagnostic.1.paint(window, cx);
 7366        }
 7367    }
 7368
 7369    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 7370        if let Some(mut blame_layout) = layout.inline_blame_layout.take() {
 7371            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 7372                blame_layout.element.paint(window, cx);
 7373            })
 7374        }
 7375    }
 7376
 7377    fn paint_inline_code_actions(
 7378        &mut self,
 7379        layout: &mut EditorLayout,
 7380        window: &mut Window,
 7381        cx: &mut App,
 7382    ) {
 7383        if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
 7384            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 7385                inline_code_actions.paint(window, cx);
 7386            })
 7387        }
 7388    }
 7389
 7390    fn paint_diff_hunk_controls(
 7391        &mut self,
 7392        layout: &mut EditorLayout,
 7393        window: &mut Window,
 7394        cx: &mut App,
 7395    ) {
 7396        for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
 7397            diff_hunk_control.paint(window, cx);
 7398        }
 7399    }
 7400
 7401    fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 7402        if let Some(mut layout) = layout.minimap.take() {
 7403            let minimap_hitbox = layout.thumb_layout.hitbox.clone();
 7404            let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
 7405
 7406            window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
 7407                window.with_element_namespace("minimap", |window| {
 7408                    layout.minimap.paint(window, cx);
 7409                    if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
 7410                        let minimap_thumb_color = match layout.thumb_layout.thumb_state {
 7411                            ScrollbarThumbState::Idle => {
 7412                                cx.theme().colors().minimap_thumb_background
 7413                            }
 7414                            ScrollbarThumbState::Hovered => {
 7415                                cx.theme().colors().minimap_thumb_hover_background
 7416                            }
 7417                            ScrollbarThumbState::Dragging => {
 7418                                cx.theme().colors().minimap_thumb_active_background
 7419                            }
 7420                        };
 7421                        let minimap_thumb_border = match layout.thumb_border_style {
 7422                            MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
 7423                            MinimapThumbBorder::LeftOnly => Edges {
 7424                                left: ScrollbarLayout::BORDER_WIDTH,
 7425                                ..Default::default()
 7426                            },
 7427                            MinimapThumbBorder::LeftOpen => Edges {
 7428                                right: ScrollbarLayout::BORDER_WIDTH,
 7429                                top: ScrollbarLayout::BORDER_WIDTH,
 7430                                bottom: ScrollbarLayout::BORDER_WIDTH,
 7431                                ..Default::default()
 7432                            },
 7433                            MinimapThumbBorder::RightOpen => Edges {
 7434                                left: ScrollbarLayout::BORDER_WIDTH,
 7435                                top: ScrollbarLayout::BORDER_WIDTH,
 7436                                bottom: ScrollbarLayout::BORDER_WIDTH,
 7437                                ..Default::default()
 7438                            },
 7439                            MinimapThumbBorder::None => Default::default(),
 7440                        };
 7441
 7442                        window.paint_layer(minimap_hitbox.bounds, |window| {
 7443                            window.paint_quad(quad(
 7444                                thumb_bounds,
 7445                                Corners::default(),
 7446                                minimap_thumb_color,
 7447                                minimap_thumb_border,
 7448                                cx.theme().colors().minimap_thumb_border,
 7449                                BorderStyle::Solid,
 7450                            ));
 7451                        });
 7452                    }
 7453                });
 7454            });
 7455
 7456            if dragging_minimap {
 7457                window.set_window_cursor_style(CursorStyle::Arrow);
 7458            } else {
 7459                window.set_cursor_style(CursorStyle::Arrow, &minimap_hitbox);
 7460            }
 7461
 7462            let minimap_axis = ScrollbarAxis::Vertical;
 7463            let pixels_per_line = Pixels::from(
 7464                ScrollPixelOffset::from(minimap_hitbox.size.height) / layout.max_scroll_top,
 7465            )
 7466            .min(layout.minimap_line_height);
 7467
 7468            let mut mouse_position = window.mouse_position();
 7469
 7470            window.on_mouse_event({
 7471                let editor = self.editor.clone();
 7472
 7473                let minimap_hitbox = minimap_hitbox.clone();
 7474
 7475                move |event: &MouseMoveEvent, phase, window, cx| {
 7476                    if phase == DispatchPhase::Capture {
 7477                        return;
 7478                    }
 7479
 7480                    editor.update(cx, |editor, cx| {
 7481                        if event.pressed_button == Some(MouseButton::Left)
 7482                            && editor.scroll_manager.is_dragging_minimap()
 7483                        {
 7484                            let old_position = mouse_position.along(minimap_axis);
 7485                            let new_position = event.position.along(minimap_axis);
 7486                            if (minimap_hitbox.origin.along(minimap_axis)
 7487                                ..minimap_hitbox.bottom_right().along(minimap_axis))
 7488                                .contains(&old_position)
 7489                            {
 7490                                let position =
 7491                                    editor.scroll_position(cx).apply_along(minimap_axis, |p| {
 7492                                        (p + ScrollPixelOffset::from(
 7493                                            (new_position - old_position) / pixels_per_line,
 7494                                        ))
 7495                                        .max(0.)
 7496                                    });
 7497
 7498                                editor.set_scroll_position(position, window, cx);
 7499                            }
 7500                            cx.stop_propagation();
 7501                        } else if minimap_hitbox.is_hovered(window) {
 7502                            editor.scroll_manager.set_is_hovering_minimap_thumb(
 7503                                !event.dragging()
 7504                                    && layout
 7505                                        .thumb_layout
 7506                                        .thumb_bounds
 7507                                        .is_some_and(|bounds| bounds.contains(&event.position)),
 7508                                cx,
 7509                            );
 7510
 7511                            // Stop hover events from propagating to the
 7512                            // underlying editor if the minimap hitbox is hovered
 7513                            if !event.dragging() {
 7514                                cx.stop_propagation();
 7515                            }
 7516                        } else {
 7517                            editor.scroll_manager.hide_minimap_thumb(cx);
 7518                        }
 7519                        mouse_position = event.position;
 7520                    });
 7521                }
 7522            });
 7523
 7524            if dragging_minimap {
 7525                window.on_mouse_event({
 7526                    let editor = self.editor.clone();
 7527                    move |event: &MouseUpEvent, phase, window, cx| {
 7528                        if phase == DispatchPhase::Capture {
 7529                            return;
 7530                        }
 7531
 7532                        editor.update(cx, |editor, cx| {
 7533                            if minimap_hitbox.is_hovered(window) {
 7534                                editor.scroll_manager.set_is_hovering_minimap_thumb(
 7535                                    layout
 7536                                        .thumb_layout
 7537                                        .thumb_bounds
 7538                                        .is_some_and(|bounds| bounds.contains(&event.position)),
 7539                                    cx,
 7540                                );
 7541                            } else {
 7542                                editor.scroll_manager.hide_minimap_thumb(cx);
 7543                            }
 7544                            cx.stop_propagation();
 7545                        });
 7546                    }
 7547                });
 7548            } else {
 7549                window.on_mouse_event({
 7550                    let editor = self.editor.clone();
 7551
 7552                    move |event: &MouseDownEvent, phase, window, cx| {
 7553                        if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
 7554                            return;
 7555                        }
 7556
 7557                        let event_position = event.position;
 7558
 7559                        let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
 7560                            return;
 7561                        };
 7562
 7563                        editor.update(cx, |editor, cx| {
 7564                            if !thumb_bounds.contains(&event_position) {
 7565                                let click_position =
 7566                                    event_position.relative_to(&minimap_hitbox.origin).y;
 7567
 7568                                let top_position = (click_position
 7569                                    - thumb_bounds.size.along(minimap_axis) / 2.0)
 7570                                    .max(Pixels::ZERO);
 7571
 7572                                let scroll_offset = (layout.minimap_scroll_top
 7573                                    + ScrollPixelOffset::from(
 7574                                        top_position / layout.minimap_line_height,
 7575                                    ))
 7576                                .min(layout.max_scroll_top);
 7577
 7578                                let scroll_position = editor
 7579                                    .scroll_position(cx)
 7580                                    .apply_along(minimap_axis, |_| scroll_offset);
 7581                                editor.set_scroll_position(scroll_position, window, cx);
 7582                            }
 7583
 7584                            editor.scroll_manager.set_is_dragging_minimap(cx);
 7585                            cx.stop_propagation();
 7586                        });
 7587                    }
 7588                });
 7589            }
 7590        }
 7591    }
 7592
 7593    fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 7594        for mut block in layout.blocks.drain(..) {
 7595            if block.overlaps_gutter {
 7596                block.element.paint(window, cx);
 7597            } else {
 7598                let mut bounds = layout.hitbox.bounds;
 7599                bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
 7600                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 7601                    block.element.paint(window, cx);
 7602                })
 7603            }
 7604        }
 7605    }
 7606
 7607    fn paint_edit_prediction_popover(
 7608        &mut self,
 7609        layout: &mut EditorLayout,
 7610        window: &mut Window,
 7611        cx: &mut App,
 7612    ) {
 7613        if let Some(edit_prediction_popover) = layout.edit_prediction_popover.as_mut() {
 7614            edit_prediction_popover.paint(window, cx);
 7615        }
 7616    }
 7617
 7618    fn paint_mouse_context_menu(
 7619        &mut self,
 7620        layout: &mut EditorLayout,
 7621        window: &mut Window,
 7622        cx: &mut App,
 7623    ) {
 7624        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
 7625            mouse_context_menu.paint(window, cx);
 7626        }
 7627    }
 7628
 7629    fn paint_scroll_wheel_listener(
 7630        &mut self,
 7631        layout: &EditorLayout,
 7632        window: &mut Window,
 7633        cx: &mut App,
 7634    ) {
 7635        window.on_mouse_event({
 7636            let position_map = layout.position_map.clone();
 7637            let editor = self.editor.clone();
 7638            let hitbox = layout.hitbox.clone();
 7639            let mut delta = ScrollDelta::default();
 7640
 7641            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
 7642            // accidentally turn off their scrolling.
 7643            let base_scroll_sensitivity =
 7644                EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
 7645
 7646            // Use a minimum fast_scroll_sensitivity for same reason above
 7647            let fast_scroll_sensitivity = EditorSettings::get_global(cx)
 7648                .fast_scroll_sensitivity
 7649                .max(0.01);
 7650
 7651            move |event: &ScrollWheelEvent, phase, window, cx| {
 7652                let scroll_sensitivity = {
 7653                    if event.modifiers.alt {
 7654                        fast_scroll_sensitivity
 7655                    } else {
 7656                        base_scroll_sensitivity
 7657                    }
 7658                };
 7659
 7660                if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
 7661                    delta = delta.coalesce(event.delta);
 7662                    editor.update(cx, |editor, cx| {
 7663                        let position_map: &PositionMap = &position_map;
 7664
 7665                        let line_height = position_map.line_height;
 7666                        let max_glyph_advance = position_map.em_advance;
 7667                        let (delta, axis) = match delta {
 7668                            gpui::ScrollDelta::Pixels(mut pixels) => {
 7669                                //Trackpad
 7670                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
 7671                                (pixels, axis)
 7672                            }
 7673
 7674                            gpui::ScrollDelta::Lines(lines) => {
 7675                                //Not trackpad
 7676                                let pixels =
 7677                                    point(lines.x * max_glyph_advance, lines.y * line_height);
 7678                                (pixels, None)
 7679                            }
 7680                        };
 7681
 7682                        let current_scroll_position = position_map.snapshot.scroll_position();
 7683                        let x = (current_scroll_position.x
 7684                            * ScrollPixelOffset::from(max_glyph_advance)
 7685                            - ScrollPixelOffset::from(delta.x * scroll_sensitivity))
 7686                            / ScrollPixelOffset::from(max_glyph_advance);
 7687                        let y = (current_scroll_position.y * ScrollPixelOffset::from(line_height)
 7688                            - ScrollPixelOffset::from(delta.y * scroll_sensitivity))
 7689                            / ScrollPixelOffset::from(line_height);
 7690                        let mut scroll_position =
 7691                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
 7692                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
 7693                        if forbid_vertical_scroll {
 7694                            scroll_position.y = current_scroll_position.y;
 7695                        }
 7696
 7697                        if scroll_position != current_scroll_position {
 7698                            editor.scroll(scroll_position, axis, window, cx);
 7699                            cx.stop_propagation();
 7700                        } else if y < 0. {
 7701                            // Due to clamping, we may fail to detect cases of overscroll to the top;
 7702                            // We want the scroll manager to get an update in such cases and detect the change of direction
 7703                            // on the next frame.
 7704                            cx.notify();
 7705                        }
 7706                    });
 7707                }
 7708            }
 7709        });
 7710    }
 7711
 7712    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
 7713        if layout.mode.is_minimap() {
 7714            return;
 7715        }
 7716
 7717        self.paint_scroll_wheel_listener(layout, window, cx);
 7718
 7719        window.on_mouse_event({
 7720            let position_map = layout.position_map.clone();
 7721            let editor = self.editor.clone();
 7722            let line_numbers = layout.line_numbers.clone();
 7723
 7724            move |event: &MouseDownEvent, phase, window, cx| {
 7725                if phase == DispatchPhase::Bubble {
 7726                    match event.button {
 7727                        MouseButton::Left => editor.update(cx, |editor, cx| {
 7728                            let pending_mouse_down = editor
 7729                                .pending_mouse_down
 7730                                .get_or_insert_with(Default::default)
 7731                                .clone();
 7732
 7733                            *pending_mouse_down.borrow_mut() = Some(event.clone());
 7734
 7735                            Self::mouse_left_down(
 7736                                editor,
 7737                                event,
 7738                                &position_map,
 7739                                line_numbers.as_ref(),
 7740                                window,
 7741                                cx,
 7742                            );
 7743                        }),
 7744                        MouseButton::Right => editor.update(cx, |editor, cx| {
 7745                            Self::mouse_right_down(editor, event, &position_map, window, cx);
 7746                        }),
 7747                        MouseButton::Middle => editor.update(cx, |editor, cx| {
 7748                            Self::mouse_middle_down(editor, event, &position_map, window, cx);
 7749                        }),
 7750                        _ => {}
 7751                    };
 7752                }
 7753            }
 7754        });
 7755
 7756        window.on_mouse_event({
 7757            let editor = self.editor.clone();
 7758            let position_map = layout.position_map.clone();
 7759
 7760            move |event: &MouseUpEvent, phase, window, cx| {
 7761                if phase == DispatchPhase::Bubble {
 7762                    editor.update(cx, |editor, cx| {
 7763                        Self::mouse_up(editor, event, &position_map, window, cx)
 7764                    });
 7765                }
 7766            }
 7767        });
 7768
 7769        window.on_mouse_event({
 7770            let editor = self.editor.clone();
 7771            let position_map = layout.position_map.clone();
 7772            let mut captured_mouse_down = None;
 7773
 7774            move |event: &MouseUpEvent, phase, window, cx| match phase {
 7775                // Clear the pending mouse down during the capture phase,
 7776                // so that it happens even if another event handler stops
 7777                // propagation.
 7778                DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
 7779                    let pending_mouse_down = editor
 7780                        .pending_mouse_down
 7781                        .get_or_insert_with(Default::default)
 7782                        .clone();
 7783
 7784                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
 7785                    if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
 7786                        captured_mouse_down = pending_mouse_down.take();
 7787                        window.refresh();
 7788                    }
 7789                }),
 7790                // Fire click handlers during the bubble phase.
 7791                DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
 7792                    if let Some(mouse_down) = captured_mouse_down.take() {
 7793                        let event = ClickEvent::Mouse(MouseClickEvent {
 7794                            down: mouse_down,
 7795                            up: event.clone(),
 7796                        });
 7797                        Self::click(editor, &event, &position_map, window, cx);
 7798                    }
 7799                }),
 7800            }
 7801        });
 7802
 7803        window.on_mouse_event({
 7804            let position_map = layout.position_map.clone();
 7805            let editor = self.editor.clone();
 7806
 7807            move |event: &MousePressureEvent, phase, window, cx| {
 7808                if phase == DispatchPhase::Bubble {
 7809                    editor.update(cx, |editor, cx| {
 7810                        Self::pressure_click(editor, &event, &position_map, window, cx);
 7811                    })
 7812                }
 7813            }
 7814        });
 7815
 7816        window.on_mouse_event({
 7817            let position_map = layout.position_map.clone();
 7818            let editor = self.editor.clone();
 7819
 7820            move |event: &MouseMoveEvent, phase, window, cx| {
 7821                if phase == DispatchPhase::Bubble {
 7822                    editor.update(cx, |editor, cx| {
 7823                        if editor.hover_state.focused(window, cx) {
 7824                            return;
 7825                        }
 7826                        if event.pressed_button == Some(MouseButton::Left)
 7827                            || event.pressed_button == Some(MouseButton::Middle)
 7828                        {
 7829                            Self::mouse_dragged(editor, event, &position_map, window, cx)
 7830                        }
 7831
 7832                        Self::mouse_moved(editor, event, &position_map, window, cx)
 7833                    });
 7834                }
 7835            }
 7836        });
 7837    }
 7838
 7839    fn shape_line_number(
 7840        &self,
 7841        text: SharedString,
 7842        color: Hsla,
 7843        window: &mut Window,
 7844    ) -> ShapedLine {
 7845        let run = TextRun {
 7846            len: text.len(),
 7847            font: self.style.text.font(),
 7848            color,
 7849            ..Default::default()
 7850        };
 7851        window.text_system().shape_line(
 7852            text,
 7853            self.style.text.font_size.to_pixels(window.rem_size()),
 7854            &[run],
 7855            None,
 7856        )
 7857    }
 7858
 7859    fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
 7860        let unstaged = status.has_secondary_hunk();
 7861        let unstaged_hollow = matches!(
 7862            ProjectSettings::get_global(cx).git.hunk_style,
 7863            GitHunkStyleSetting::UnstagedHollow
 7864        );
 7865
 7866        unstaged == unstaged_hollow
 7867    }
 7868
 7869    #[cfg(debug_assertions)]
 7870    fn layout_debug_ranges(
 7871        selections: &mut Vec<(PlayerColor, Vec<SelectionLayout>)>,
 7872        anchor_range: Range<Anchor>,
 7873        display_snapshot: &DisplaySnapshot,
 7874        cx: &App,
 7875    ) {
 7876        let theme = cx.theme();
 7877        text::debug::GlobalDebugRanges::with_locked(|debug_ranges| {
 7878            if debug_ranges.ranges.is_empty() {
 7879                return;
 7880            }
 7881            let buffer_snapshot = &display_snapshot.buffer_snapshot();
 7882            for (buffer, buffer_range, excerpt_id) in
 7883                buffer_snapshot.range_to_buffer_ranges(anchor_range)
 7884            {
 7885                let buffer_range =
 7886                    buffer.anchor_after(buffer_range.start)..buffer.anchor_before(buffer_range.end);
 7887                selections.extend(debug_ranges.ranges.iter().flat_map(|debug_range| {
 7888                    let player_color = theme
 7889                        .players()
 7890                        .color_for_participant(debug_range.occurrence_index as u32 + 1);
 7891                    debug_range.ranges.iter().filter_map(move |range| {
 7892                        if range.start.buffer_id != Some(buffer.remote_id()) {
 7893                            return None;
 7894                        }
 7895                        let clipped_start = range.start.max(&buffer_range.start, buffer);
 7896                        let clipped_end = range.end.min(&buffer_range.end, buffer);
 7897                        let range = buffer_snapshot
 7898                            .anchor_range_in_excerpt(excerpt_id, *clipped_start..*clipped_end)?;
 7899                        let start = range.start.to_display_point(display_snapshot);
 7900                        let end = range.end.to_display_point(display_snapshot);
 7901                        let selection_layout = SelectionLayout {
 7902                            head: start,
 7903                            range: start..end,
 7904                            cursor_shape: CursorShape::Bar,
 7905                            is_newest: false,
 7906                            is_local: false,
 7907                            active_rows: start.row()..end.row(),
 7908                            user_name: Some(SharedString::new(debug_range.value.clone())),
 7909                        };
 7910                        Some((player_color, vec![selection_layout]))
 7911                    })
 7912                }));
 7913            }
 7914        });
 7915    }
 7916}
 7917
 7918fn file_status_label_color(file_status: Option<FileStatus>) -> Color {
 7919    file_status.map_or(Color::Default, |status| {
 7920        if status.is_conflicted() {
 7921            Color::Conflict
 7922        } else if status.is_modified() {
 7923            Color::Modified
 7924        } else if status.is_deleted() {
 7925            Color::Disabled
 7926        } else if status.is_created() {
 7927            Color::Created
 7928        } else {
 7929            Color::Default
 7930        }
 7931    })
 7932}
 7933
 7934fn header_jump_data(
 7935    editor_snapshot: &EditorSnapshot,
 7936    block_row_start: DisplayRow,
 7937    height: u32,
 7938    first_excerpt: &ExcerptInfo,
 7939    latest_selection_anchors: &HashMap<BufferId, Anchor>,
 7940) -> JumpData {
 7941    let jump_target = if let Some(anchor) = latest_selection_anchors.get(&first_excerpt.buffer_id)
 7942        && let Some(range) = editor_snapshot.context_range_for_excerpt(anchor.excerpt_id)
 7943        && let Some(buffer) = editor_snapshot
 7944            .buffer_snapshot()
 7945            .buffer_for_excerpt(anchor.excerpt_id)
 7946    {
 7947        JumpTargetInExcerptInput {
 7948            id: anchor.excerpt_id,
 7949            buffer,
 7950            excerpt_start_anchor: range.start,
 7951            jump_anchor: anchor.text_anchor,
 7952        }
 7953    } else {
 7954        JumpTargetInExcerptInput {
 7955            id: first_excerpt.id,
 7956            buffer: &first_excerpt.buffer,
 7957            excerpt_start_anchor: first_excerpt.range.context.start,
 7958            jump_anchor: first_excerpt.range.primary.start,
 7959        }
 7960    };
 7961    header_jump_data_inner(editor_snapshot, block_row_start, height, &jump_target)
 7962}
 7963
 7964struct JumpTargetInExcerptInput<'a> {
 7965    id: ExcerptId,
 7966    buffer: &'a language::BufferSnapshot,
 7967    excerpt_start_anchor: text::Anchor,
 7968    jump_anchor: text::Anchor,
 7969}
 7970
 7971fn header_jump_data_inner(
 7972    snapshot: &EditorSnapshot,
 7973    block_row_start: DisplayRow,
 7974    height: u32,
 7975    for_excerpt: &JumpTargetInExcerptInput,
 7976) -> JumpData {
 7977    let buffer = &for_excerpt.buffer;
 7978    let jump_position = language::ToPoint::to_point(&for_excerpt.jump_anchor, buffer);
 7979    let excerpt_start = for_excerpt.excerpt_start_anchor;
 7980    let rows_from_excerpt_start = if for_excerpt.jump_anchor == excerpt_start {
 7981        0
 7982    } else {
 7983        let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
 7984        jump_position.row.saturating_sub(excerpt_start_point.row)
 7985    };
 7986
 7987    let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
 7988        .saturating_sub(
 7989            snapshot
 7990                .scroll_anchor
 7991                .scroll_position(&snapshot.display_snapshot)
 7992                .y as u32,
 7993        );
 7994
 7995    JumpData::MultiBufferPoint {
 7996        excerpt_id: for_excerpt.id,
 7997        anchor: for_excerpt.jump_anchor,
 7998        position: jump_position,
 7999        line_offset_from_top,
 8000    }
 8001}
 8002
 8003pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
 8004
 8005impl AcceptEditPredictionBinding {
 8006    pub fn keystroke(&self) -> Option<&KeybindingKeystroke> {
 8007        if let Some(binding) = self.0.as_ref() {
 8008            match &binding.keystrokes() {
 8009                [keystroke, ..] => Some(keystroke),
 8010                _ => None,
 8011            }
 8012        } else {
 8013            None
 8014        }
 8015    }
 8016}
 8017
 8018fn prepaint_gutter_button(
 8019    button: IconButton,
 8020    row: DisplayRow,
 8021    line_height: Pixels,
 8022    gutter_dimensions: &GutterDimensions,
 8023    scroll_position: gpui::Point<ScrollOffset>,
 8024    gutter_hitbox: &Hitbox,
 8025    display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 8026    window: &mut Window,
 8027    cx: &mut App,
 8028) -> AnyElement {
 8029    let mut button = button.into_any_element();
 8030
 8031    let available_space = size(
 8032        AvailableSpace::MinContent,
 8033        AvailableSpace::Definite(line_height),
 8034    );
 8035    let indicator_size = button.layout_as_root(available_space, window, cx);
 8036
 8037    let blame_width = gutter_dimensions.git_blame_entries_width;
 8038    let gutter_width = display_hunks
 8039        .binary_search_by(|(hunk, _)| match hunk {
 8040            DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
 8041            DisplayDiffHunk::Unfolded {
 8042                display_row_range, ..
 8043            } => {
 8044                if display_row_range.end <= row {
 8045                    Ordering::Less
 8046                } else if display_row_range.start > row {
 8047                    Ordering::Greater
 8048                } else {
 8049                    Ordering::Equal
 8050                }
 8051            }
 8052        })
 8053        .ok()
 8054        .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
 8055    let left_offset = blame_width.max(gutter_width).unwrap_or_default();
 8056
 8057    let mut x = left_offset;
 8058    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
 8059        - indicator_size.width
 8060        - left_offset;
 8061    x += available_width / 2.;
 8062
 8063    let mut y =
 8064        Pixels::from((row.as_f64() - scroll_position.y) * ScrollPixelOffset::from(line_height));
 8065    y += (line_height - indicator_size.height) / 2.;
 8066
 8067    button.prepaint_as_root(
 8068        gutter_hitbox.origin + point(x, y),
 8069        available_space,
 8070        window,
 8071        cx,
 8072    );
 8073    button
 8074}
 8075
 8076fn render_inline_blame_entry(
 8077    blame_entry: BlameEntry,
 8078    style: &EditorStyle,
 8079    cx: &mut App,
 8080) -> Option<AnyElement> {
 8081    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 8082    renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
 8083}
 8084
 8085fn render_blame_entry_popover(
 8086    blame_entry: BlameEntry,
 8087    scroll_handle: ScrollHandle,
 8088    commit_message: Option<ParsedCommitMessage>,
 8089    markdown: Entity<Markdown>,
 8090    workspace: WeakEntity<Workspace>,
 8091    blame: &Entity<GitBlame>,
 8092    buffer: BufferId,
 8093    window: &mut Window,
 8094    cx: &mut App,
 8095) -> Option<AnyElement> {
 8096    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 8097    let blame = blame.read(cx);
 8098    let repository = blame.repository(cx, buffer)?;
 8099    renderer.render_blame_entry_popover(
 8100        blame_entry,
 8101        scroll_handle,
 8102        commit_message,
 8103        markdown,
 8104        repository,
 8105        workspace,
 8106        window,
 8107        cx,
 8108    )
 8109}
 8110
 8111fn render_blame_entry(
 8112    ix: usize,
 8113    blame: &Entity<GitBlame>,
 8114    blame_entry: BlameEntry,
 8115    style: &EditorStyle,
 8116    last_used_color: &mut Option<(Hsla, Oid)>,
 8117    editor: Entity<Editor>,
 8118    workspace: Entity<Workspace>,
 8119    buffer: BufferId,
 8120    renderer: &dyn BlameRenderer,
 8121    window: &mut Window,
 8122    cx: &mut App,
 8123) -> Option<AnyElement> {
 8124    let index: u32 = blame_entry.sha.into();
 8125    let mut sha_color = cx.theme().players().color_for_participant(index).cursor;
 8126
 8127    // If the last color we used is the same as the one we get for this line, but
 8128    // the commit SHAs are different, then we try again to get a different color.
 8129    if let Some((color, sha)) = *last_used_color
 8130        && sha != blame_entry.sha
 8131        && color == sha_color
 8132    {
 8133        sha_color = cx.theme().players().color_for_participant(index + 1).cursor;
 8134    }
 8135    last_used_color.replace((sha_color, blame_entry.sha));
 8136
 8137    let blame = blame.read(cx);
 8138    let details = blame.details_for_entry(buffer, &blame_entry);
 8139    let repository = blame.repository(cx, buffer)?;
 8140    renderer.render_blame_entry(
 8141        &style.text,
 8142        blame_entry,
 8143        details,
 8144        repository,
 8145        workspace.downgrade(),
 8146        editor,
 8147        ix,
 8148        sha_color,
 8149        window,
 8150        cx,
 8151    )
 8152}
 8153
 8154#[derive(Debug)]
 8155pub(crate) struct LineWithInvisibles {
 8156    fragments: SmallVec<[LineFragment; 1]>,
 8157    invisibles: Vec<Invisible>,
 8158    len: usize,
 8159    pub(crate) width: Pixels,
 8160    font_size: Pixels,
 8161}
 8162
 8163enum LineFragment {
 8164    Text(ShapedLine),
 8165    Element {
 8166        id: ChunkRendererId,
 8167        element: Option<AnyElement>,
 8168        size: Size<Pixels>,
 8169        len: usize,
 8170    },
 8171}
 8172
 8173impl fmt::Debug for LineFragment {
 8174    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 8175        match self {
 8176            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
 8177            LineFragment::Element { size, len, .. } => f
 8178                .debug_struct("Element")
 8179                .field("size", size)
 8180                .field("len", len)
 8181                .finish(),
 8182        }
 8183    }
 8184}
 8185
 8186impl LineWithInvisibles {
 8187    fn from_chunks<'a>(
 8188        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
 8189        editor_style: &EditorStyle,
 8190        max_line_len: usize,
 8191        max_line_count: usize,
 8192        editor_mode: &EditorMode,
 8193        text_width: Pixels,
 8194        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 8195        bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
 8196        window: &mut Window,
 8197        cx: &mut App,
 8198    ) -> Vec<Self> {
 8199        let text_style = &editor_style.text;
 8200        let mut layouts = Vec::with_capacity(max_line_count);
 8201        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
 8202        let mut line = String::new();
 8203        let mut invisibles = Vec::new();
 8204        let mut width = Pixels::ZERO;
 8205        let mut len = 0;
 8206        let mut styles = Vec::new();
 8207        let mut non_whitespace_added = false;
 8208        let mut row = 0;
 8209        let mut line_exceeded_max_len = false;
 8210        let font_size = text_style.font_size.to_pixels(window.rem_size());
 8211        let min_contrast = EditorSettings::get_global(cx).minimum_contrast_for_highlights;
 8212
 8213        let ellipsis = SharedString::from("β‹―");
 8214
 8215        for highlighted_chunk in chunks.chain([HighlightedChunk {
 8216            text: "\n",
 8217            style: None,
 8218            is_tab: false,
 8219            is_inlay: false,
 8220            replacement: None,
 8221        }]) {
 8222            if let Some(replacement) = highlighted_chunk.replacement {
 8223                if !line.is_empty() {
 8224                    let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
 8225                    let text_runs: &[TextRun] = if segments.is_empty() {
 8226                        &styles
 8227                    } else {
 8228                        &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
 8229                    };
 8230                    let shaped_line = window.text_system().shape_line(
 8231                        line.clone().into(),
 8232                        font_size,
 8233                        text_runs,
 8234                        None,
 8235                    );
 8236                    width += shaped_line.width;
 8237                    len += shaped_line.len;
 8238                    fragments.push(LineFragment::Text(shaped_line));
 8239                    line.clear();
 8240                    styles.clear();
 8241                }
 8242
 8243                match replacement {
 8244                    ChunkReplacement::Renderer(renderer) => {
 8245                        let available_width = if renderer.constrain_width {
 8246                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
 8247                                ellipsis.clone()
 8248                            } else {
 8249                                SharedString::from(Arc::from(highlighted_chunk.text))
 8250                            };
 8251                            let shaped_line = window.text_system().shape_line(
 8252                                chunk,
 8253                                font_size,
 8254                                &[text_style.to_run(highlighted_chunk.text.len())],
 8255                                None,
 8256                            );
 8257                            AvailableSpace::Definite(shaped_line.width)
 8258                        } else {
 8259                            AvailableSpace::MinContent
 8260                        };
 8261
 8262                        let mut element = (renderer.render)(&mut ChunkRendererContext {
 8263                            context: cx,
 8264                            window,
 8265                            max_width: text_width,
 8266                        });
 8267                        let line_height = text_style.line_height_in_pixels(window.rem_size());
 8268                        let size = element.layout_as_root(
 8269                            size(available_width, AvailableSpace::Definite(line_height)),
 8270                            window,
 8271                            cx,
 8272                        );
 8273
 8274                        width += size.width;
 8275                        len += highlighted_chunk.text.len();
 8276                        fragments.push(LineFragment::Element {
 8277                            id: renderer.id,
 8278                            element: Some(element),
 8279                            size,
 8280                            len: highlighted_chunk.text.len(),
 8281                        });
 8282                    }
 8283                    ChunkReplacement::Str(x) => {
 8284                        let text_style = if let Some(style) = highlighted_chunk.style {
 8285                            Cow::Owned(text_style.clone().highlight(style))
 8286                        } else {
 8287                            Cow::Borrowed(text_style)
 8288                        };
 8289
 8290                        let run = TextRun {
 8291                            len: x.len(),
 8292                            font: text_style.font(),
 8293                            color: text_style.color,
 8294                            background_color: text_style.background_color,
 8295                            underline: text_style.underline,
 8296                            strikethrough: text_style.strikethrough,
 8297                        };
 8298                        let line_layout = window
 8299                            .text_system()
 8300                            .shape_line(x, font_size, &[run], None)
 8301                            .with_len(highlighted_chunk.text.len());
 8302
 8303                        width += line_layout.width;
 8304                        len += highlighted_chunk.text.len();
 8305                        fragments.push(LineFragment::Text(line_layout))
 8306                    }
 8307                }
 8308            } else {
 8309                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
 8310                    if ix > 0 {
 8311                        let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
 8312                        let text_runs = if segments.is_empty() {
 8313                            &styles
 8314                        } else {
 8315                            &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
 8316                        };
 8317                        let shaped_line = window.text_system().shape_line(
 8318                            line.clone().into(),
 8319                            font_size,
 8320                            text_runs,
 8321                            None,
 8322                        );
 8323                        width += shaped_line.width;
 8324                        len += shaped_line.len;
 8325                        fragments.push(LineFragment::Text(shaped_line));
 8326                        layouts.push(Self {
 8327                            width: mem::take(&mut width),
 8328                            len: mem::take(&mut len),
 8329                            fragments: mem::take(&mut fragments),
 8330                            invisibles: std::mem::take(&mut invisibles),
 8331                            font_size,
 8332                        });
 8333
 8334                        line.clear();
 8335                        styles.clear();
 8336                        row += 1;
 8337                        line_exceeded_max_len = false;
 8338                        non_whitespace_added = false;
 8339                        if row == max_line_count {
 8340                            return layouts;
 8341                        }
 8342                    }
 8343
 8344                    if !line_chunk.is_empty() && !line_exceeded_max_len {
 8345                        let text_style = if let Some(style) = highlighted_chunk.style {
 8346                            Cow::Owned(text_style.clone().highlight(style))
 8347                        } else {
 8348                            Cow::Borrowed(text_style)
 8349                        };
 8350
 8351                        if line.len() + line_chunk.len() > max_line_len {
 8352                            let mut chunk_len = max_line_len - line.len();
 8353                            while !line_chunk.is_char_boundary(chunk_len) {
 8354                                chunk_len -= 1;
 8355                            }
 8356                            line_chunk = &line_chunk[..chunk_len];
 8357                            line_exceeded_max_len = true;
 8358                        }
 8359
 8360                        styles.push(TextRun {
 8361                            len: line_chunk.len(),
 8362                            font: text_style.font(),
 8363                            color: text_style.color,
 8364                            background_color: text_style.background_color,
 8365                            underline: text_style.underline,
 8366                            strikethrough: text_style.strikethrough,
 8367                        });
 8368
 8369                        if editor_mode.is_full() && !highlighted_chunk.is_inlay {
 8370                            // Line wrap pads its contents with fake whitespaces,
 8371                            // avoid printing them
 8372                            let is_soft_wrapped = is_row_soft_wrapped(row);
 8373                            if highlighted_chunk.is_tab {
 8374                                if non_whitespace_added || !is_soft_wrapped {
 8375                                    invisibles.push(Invisible::Tab {
 8376                                        line_start_offset: line.len(),
 8377                                        line_end_offset: line.len() + line_chunk.len(),
 8378                                    });
 8379                                }
 8380                            } else {
 8381                                invisibles.extend(line_chunk.char_indices().filter_map(
 8382                                    |(index, c)| {
 8383                                        let is_whitespace = c.is_whitespace();
 8384                                        non_whitespace_added |= !is_whitespace;
 8385                                        if is_whitespace
 8386                                            && (non_whitespace_added || !is_soft_wrapped)
 8387                                        {
 8388                                            Some(Invisible::Whitespace {
 8389                                                line_offset: line.len() + index,
 8390                                            })
 8391                                        } else {
 8392                                            None
 8393                                        }
 8394                                    },
 8395                                ))
 8396                            }
 8397                        }
 8398
 8399                        line.push_str(line_chunk);
 8400                    }
 8401                }
 8402            }
 8403        }
 8404
 8405        layouts
 8406    }
 8407
 8408    /// Takes text runs and non-overlapping left-to-right background ranges with color.
 8409    /// Returns new text runs with adjusted contrast as per background ranges.
 8410    fn split_runs_by_bg_segments(
 8411        text_runs: &[TextRun],
 8412        bg_segments: &[(Range<DisplayPoint>, Hsla)],
 8413        min_contrast: f32,
 8414        start_col_offset: usize,
 8415    ) -> Vec<TextRun> {
 8416        let mut output_runs: Vec<TextRun> = Vec::with_capacity(text_runs.len());
 8417        let mut line_col = start_col_offset;
 8418        let mut segment_ix = 0usize;
 8419
 8420        for text_run in text_runs.iter() {
 8421            let run_start_col = line_col;
 8422            let run_end_col = run_start_col + text_run.len;
 8423            while segment_ix < bg_segments.len()
 8424                && (bg_segments[segment_ix].0.end.column() as usize) <= run_start_col
 8425            {
 8426                segment_ix += 1;
 8427            }
 8428            let mut cursor_col = run_start_col;
 8429            let mut local_segment_ix = segment_ix;
 8430            while local_segment_ix < bg_segments.len() {
 8431                let (range, segment_color) = &bg_segments[local_segment_ix];
 8432                let segment_start_col = range.start.column() as usize;
 8433                let segment_end_col = range.end.column() as usize;
 8434                if segment_start_col >= run_end_col {
 8435                    break;
 8436                }
 8437                if segment_start_col > cursor_col {
 8438                    let span_len = segment_start_col - cursor_col;
 8439                    output_runs.push(TextRun {
 8440                        len: span_len,
 8441                        font: text_run.font.clone(),
 8442                        color: text_run.color,
 8443                        background_color: text_run.background_color,
 8444                        underline: text_run.underline,
 8445                        strikethrough: text_run.strikethrough,
 8446                    });
 8447                    cursor_col = segment_start_col;
 8448                }
 8449                let segment_slice_end_col = segment_end_col.min(run_end_col);
 8450                if segment_slice_end_col > cursor_col {
 8451                    let new_text_color =
 8452                        ensure_minimum_contrast(text_run.color, *segment_color, min_contrast);
 8453                    output_runs.push(TextRun {
 8454                        len: segment_slice_end_col - cursor_col,
 8455                        font: text_run.font.clone(),
 8456                        color: new_text_color,
 8457                        background_color: text_run.background_color,
 8458                        underline: text_run.underline,
 8459                        strikethrough: text_run.strikethrough,
 8460                    });
 8461                    cursor_col = segment_slice_end_col;
 8462                }
 8463                if segment_end_col >= run_end_col {
 8464                    break;
 8465                }
 8466                local_segment_ix += 1;
 8467            }
 8468            if cursor_col < run_end_col {
 8469                output_runs.push(TextRun {
 8470                    len: run_end_col - cursor_col,
 8471                    font: text_run.font.clone(),
 8472                    color: text_run.color,
 8473                    background_color: text_run.background_color,
 8474                    underline: text_run.underline,
 8475                    strikethrough: text_run.strikethrough,
 8476                });
 8477            }
 8478            line_col = run_end_col;
 8479            segment_ix = local_segment_ix;
 8480        }
 8481        output_runs
 8482    }
 8483
 8484    fn prepaint(
 8485        &mut self,
 8486        line_height: Pixels,
 8487        scroll_position: gpui::Point<ScrollOffset>,
 8488        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 8489        row: DisplayRow,
 8490        content_origin: gpui::Point<Pixels>,
 8491        line_elements: &mut SmallVec<[AnyElement; 1]>,
 8492        window: &mut Window,
 8493        cx: &mut App,
 8494    ) {
 8495        let line_y = f32::from(line_height) * Pixels::from(row.as_f64() - scroll_position.y);
 8496        self.prepaint_with_custom_offset(
 8497            line_height,
 8498            scroll_pixel_position,
 8499            content_origin,
 8500            line_y,
 8501            line_elements,
 8502            window,
 8503            cx,
 8504        );
 8505    }
 8506
 8507    fn prepaint_with_custom_offset(
 8508        &mut self,
 8509        line_height: Pixels,
 8510        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 8511        content_origin: gpui::Point<Pixels>,
 8512        line_y: Pixels,
 8513        line_elements: &mut SmallVec<[AnyElement; 1]>,
 8514        window: &mut Window,
 8515        cx: &mut App,
 8516    ) {
 8517        let mut fragment_origin =
 8518            content_origin + gpui::point(Pixels::from(-scroll_pixel_position.x), line_y);
 8519        for fragment in &mut self.fragments {
 8520            match fragment {
 8521                LineFragment::Text(line) => {
 8522                    fragment_origin.x += line.width;
 8523                }
 8524                LineFragment::Element { element, size, .. } => {
 8525                    let mut element = element
 8526                        .take()
 8527                        .expect("you can't prepaint LineWithInvisibles twice");
 8528
 8529                    // Center the element vertically within the line.
 8530                    let mut element_origin = fragment_origin;
 8531                    element_origin.y += (line_height - size.height) / 2.;
 8532                    element.prepaint_at(element_origin, window, cx);
 8533                    line_elements.push(element);
 8534
 8535                    fragment_origin.x += size.width;
 8536                }
 8537            }
 8538        }
 8539    }
 8540
 8541    fn draw(
 8542        &self,
 8543        layout: &EditorLayout,
 8544        row: DisplayRow,
 8545        content_origin: gpui::Point<Pixels>,
 8546        whitespace_setting: ShowWhitespaceSetting,
 8547        selection_ranges: &[Range<DisplayPoint>],
 8548        window: &mut Window,
 8549        cx: &mut App,
 8550    ) {
 8551        self.draw_with_custom_offset(
 8552            layout,
 8553            row,
 8554            content_origin,
 8555            layout.position_map.line_height
 8556                * (row.as_f64() - layout.position_map.scroll_position.y) as f32,
 8557            whitespace_setting,
 8558            selection_ranges,
 8559            window,
 8560            cx,
 8561        );
 8562    }
 8563
 8564    fn draw_with_custom_offset(
 8565        &self,
 8566        layout: &EditorLayout,
 8567        row: DisplayRow,
 8568        content_origin: gpui::Point<Pixels>,
 8569        line_y: Pixels,
 8570        whitespace_setting: ShowWhitespaceSetting,
 8571        selection_ranges: &[Range<DisplayPoint>],
 8572        window: &mut Window,
 8573        cx: &mut App,
 8574    ) {
 8575        let line_height = layout.position_map.line_height;
 8576        let mut fragment_origin = content_origin
 8577            + gpui::point(
 8578                Pixels::from(-layout.position_map.scroll_pixel_position.x),
 8579                line_y,
 8580            );
 8581
 8582        for fragment in &self.fragments {
 8583            match fragment {
 8584                LineFragment::Text(line) => {
 8585                    line.paint(fragment_origin, line_height, window, cx)
 8586                        .log_err();
 8587                    fragment_origin.x += line.width;
 8588                }
 8589                LineFragment::Element { size, .. } => {
 8590                    fragment_origin.x += size.width;
 8591                }
 8592            }
 8593        }
 8594
 8595        self.draw_invisibles(
 8596            selection_ranges,
 8597            layout,
 8598            content_origin,
 8599            line_y,
 8600            row,
 8601            line_height,
 8602            whitespace_setting,
 8603            window,
 8604            cx,
 8605        );
 8606    }
 8607
 8608    fn draw_background(
 8609        &self,
 8610        layout: &EditorLayout,
 8611        row: DisplayRow,
 8612        content_origin: gpui::Point<Pixels>,
 8613        window: &mut Window,
 8614        cx: &mut App,
 8615    ) {
 8616        let line_height = layout.position_map.line_height;
 8617        let line_y = line_height * (row.as_f64() - layout.position_map.scroll_position.y) as f32;
 8618
 8619        let mut fragment_origin = content_origin
 8620            + gpui::point(
 8621                Pixels::from(-layout.position_map.scroll_pixel_position.x),
 8622                line_y,
 8623            );
 8624
 8625        for fragment in &self.fragments {
 8626            match fragment {
 8627                LineFragment::Text(line) => {
 8628                    line.paint_background(fragment_origin, line_height, window, cx)
 8629                        .log_err();
 8630                    fragment_origin.x += line.width;
 8631                }
 8632                LineFragment::Element { size, .. } => {
 8633                    fragment_origin.x += size.width;
 8634                }
 8635            }
 8636        }
 8637    }
 8638
 8639    fn draw_invisibles(
 8640        &self,
 8641        selection_ranges: &[Range<DisplayPoint>],
 8642        layout: &EditorLayout,
 8643        content_origin: gpui::Point<Pixels>,
 8644        line_y: Pixels,
 8645        row: DisplayRow,
 8646        line_height: Pixels,
 8647        whitespace_setting: ShowWhitespaceSetting,
 8648        window: &mut Window,
 8649        cx: &mut App,
 8650    ) {
 8651        let extract_whitespace_info = |invisible: &Invisible| {
 8652            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
 8653                Invisible::Tab {
 8654                    line_start_offset,
 8655                    line_end_offset,
 8656                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
 8657                Invisible::Whitespace { line_offset } => {
 8658                    (*line_offset, line_offset + 1, &layout.space_invisible)
 8659                }
 8660            };
 8661
 8662            let x_offset: ScrollPixelOffset = self.x_for_index(token_offset).into();
 8663            let invisible_offset: ScrollPixelOffset =
 8664                ((layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0)
 8665                    .into();
 8666            let origin = content_origin
 8667                + gpui::point(
 8668                    Pixels::from(
 8669                        x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
 8670                    ),
 8671                    line_y,
 8672                );
 8673
 8674            (
 8675                [token_offset, token_end_offset],
 8676                Box::new(move |window: &mut Window, cx: &mut App| {
 8677                    invisible_symbol
 8678                        .paint(origin, line_height, window, cx)
 8679                        .log_err();
 8680                }),
 8681            )
 8682        };
 8683
 8684        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
 8685        match whitespace_setting {
 8686            ShowWhitespaceSetting::None => (),
 8687            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
 8688            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
 8689                let invisible_point = DisplayPoint::new(row, start as u32);
 8690                if !selection_ranges
 8691                    .iter()
 8692                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
 8693                {
 8694                    return;
 8695                }
 8696
 8697                paint(window, cx);
 8698            }),
 8699
 8700            ShowWhitespaceSetting::Trailing => {
 8701                let mut previous_start = self.len;
 8702                for ([start, end], paint) in invisible_iter.rev() {
 8703                    if previous_start != end {
 8704                        break;
 8705                    }
 8706                    previous_start = start;
 8707                    paint(window, cx);
 8708                }
 8709            }
 8710
 8711            // For a whitespace to be on a boundary, any of the following conditions need to be met:
 8712            // - It is a tab
 8713            // - It is adjacent to an edge (start or end)
 8714            // - It is adjacent to a whitespace (left or right)
 8715            ShowWhitespaceSetting::Boundary => {
 8716                // 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
 8717                // the above cases.
 8718                // Note: We zip in the original `invisibles` to check for tab equality
 8719                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
 8720                for (([start, end], paint), invisible) in
 8721                    invisible_iter.zip_eq(self.invisibles.iter())
 8722                {
 8723                    let should_render = match (&last_seen, invisible) {
 8724                        (_, Invisible::Tab { .. }) => true,
 8725                        (Some((_, last_end, _)), _) => *last_end == start,
 8726                        _ => false,
 8727                    };
 8728
 8729                    if should_render || start == 0 || end == self.len {
 8730                        paint(window, cx);
 8731
 8732                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
 8733                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
 8734                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
 8735                            // Note that we need to make sure that the last one is actually adjacent
 8736                            if !should_render_last && last_end == start {
 8737                                paint_last(window, cx);
 8738                            }
 8739                        }
 8740                    }
 8741
 8742                    // Manually render anything within a selection
 8743                    let invisible_point = DisplayPoint::new(row, start as u32);
 8744                    if selection_ranges.iter().any(|region| {
 8745                        region.start <= invisible_point && invisible_point < region.end
 8746                    }) {
 8747                        paint(window, cx);
 8748                    }
 8749
 8750                    last_seen = Some((should_render, end, paint));
 8751                }
 8752            }
 8753        }
 8754    }
 8755
 8756    pub fn x_for_index(&self, index: usize) -> Pixels {
 8757        let mut fragment_start_x = Pixels::ZERO;
 8758        let mut fragment_start_index = 0;
 8759
 8760        for fragment in &self.fragments {
 8761            match fragment {
 8762                LineFragment::Text(shaped_line) => {
 8763                    let fragment_end_index = fragment_start_index + shaped_line.len;
 8764                    if index < fragment_end_index {
 8765                        return fragment_start_x
 8766                            + shaped_line.x_for_index(index - fragment_start_index);
 8767                    }
 8768                    fragment_start_x += shaped_line.width;
 8769                    fragment_start_index = fragment_end_index;
 8770                }
 8771                LineFragment::Element { len, size, .. } => {
 8772                    let fragment_end_index = fragment_start_index + len;
 8773                    if index < fragment_end_index {
 8774                        return fragment_start_x;
 8775                    }
 8776                    fragment_start_x += size.width;
 8777                    fragment_start_index = fragment_end_index;
 8778                }
 8779            }
 8780        }
 8781
 8782        fragment_start_x
 8783    }
 8784
 8785    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
 8786        let mut fragment_start_x = Pixels::ZERO;
 8787        let mut fragment_start_index = 0;
 8788
 8789        for fragment in &self.fragments {
 8790            match fragment {
 8791                LineFragment::Text(shaped_line) => {
 8792                    let fragment_end_x = fragment_start_x + shaped_line.width;
 8793                    if x < fragment_end_x {
 8794                        return Some(
 8795                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
 8796                        );
 8797                    }
 8798                    fragment_start_x = fragment_end_x;
 8799                    fragment_start_index += shaped_line.len;
 8800                }
 8801                LineFragment::Element { len, size, .. } => {
 8802                    let fragment_end_x = fragment_start_x + size.width;
 8803                    if x < fragment_end_x {
 8804                        return Some(fragment_start_index);
 8805                    }
 8806                    fragment_start_index += len;
 8807                    fragment_start_x = fragment_end_x;
 8808                }
 8809            }
 8810        }
 8811
 8812        None
 8813    }
 8814
 8815    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
 8816        let mut fragment_start_index = 0;
 8817
 8818        for fragment in &self.fragments {
 8819            match fragment {
 8820                LineFragment::Text(shaped_line) => {
 8821                    let fragment_end_index = fragment_start_index + shaped_line.len;
 8822                    if index < fragment_end_index {
 8823                        return shaped_line.font_id_for_index(index - fragment_start_index);
 8824                    }
 8825                    fragment_start_index = fragment_end_index;
 8826                }
 8827                LineFragment::Element { len, .. } => {
 8828                    let fragment_end_index = fragment_start_index + len;
 8829                    if index < fragment_end_index {
 8830                        return None;
 8831                    }
 8832                    fragment_start_index = fragment_end_index;
 8833                }
 8834            }
 8835        }
 8836
 8837        None
 8838    }
 8839}
 8840
 8841#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 8842enum Invisible {
 8843    /// A tab character
 8844    ///
 8845    /// A tab character is internally represented by spaces (configured by the user's tab width)
 8846    /// aligned to the nearest column, so it's necessary to store the start and end offset for
 8847    /// adjacency checks.
 8848    Tab {
 8849        line_start_offset: usize,
 8850        line_end_offset: usize,
 8851    },
 8852    Whitespace {
 8853        line_offset: usize,
 8854    },
 8855}
 8856
 8857impl EditorElement {
 8858    /// Returns the rem size to use when rendering the [`EditorElement`].
 8859    ///
 8860    /// This allows UI elements to scale based on the `buffer_font_size`.
 8861    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
 8862        match self.editor.read(cx).mode {
 8863            EditorMode::Full {
 8864                scale_ui_elements_with_buffer_font_size: true,
 8865                ..
 8866            }
 8867            | EditorMode::Minimap { .. } => {
 8868                let buffer_font_size = self.style.text.font_size;
 8869                match buffer_font_size {
 8870                    AbsoluteLength::Pixels(pixels) => {
 8871                        let rem_size_scale = {
 8872                            // Our default UI font size is 14px on a 16px base scale.
 8873                            // This means the default UI font size is 0.875rems.
 8874                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
 8875
 8876                            // We then determine the delta between a single rem and the default font
 8877                            // size scale.
 8878                            let default_font_size_delta = 1. - default_font_size_scale;
 8879
 8880                            // Finally, we add this delta to 1rem to get the scale factor that
 8881                            // should be used to scale up the UI.
 8882                            1. + default_font_size_delta
 8883                        };
 8884
 8885                        Some(pixels * rem_size_scale)
 8886                    }
 8887                    AbsoluteLength::Rems(rems) => {
 8888                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
 8889                    }
 8890                }
 8891            }
 8892            // We currently use single-line and auto-height editors in UI contexts,
 8893            // so we don't want to scale everything with the buffer font size, as it
 8894            // ends up looking off.
 8895            _ => None,
 8896        }
 8897    }
 8898
 8899    fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
 8900        if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
 8901            parent.upgrade()
 8902        } else {
 8903            Some(self.editor.clone())
 8904        }
 8905    }
 8906}
 8907
 8908#[derive(Default)]
 8909pub struct EditorRequestLayoutState {
 8910    // We use prepaint depth to limit the number of times prepaint is
 8911    // called recursively. We need this so that we can update stale
 8912    // data for e.g. block heights in block map.
 8913    prepaint_depth: Rc<Cell<usize>>,
 8914}
 8915
 8916impl EditorRequestLayoutState {
 8917    // In ideal conditions we only need one more subsequent prepaint call for resize to take effect.
 8918    // i.e. MAX_PREPAINT_DEPTH = 2, but since moving blocks inline (place_near), more lines from
 8919    // below get exposed, and we end up querying blocks for those lines too in subsequent renders.
 8920    // Setting MAX_PREPAINT_DEPTH = 3, passes all tests. Just to be on the safe side we set it to 5, so
 8921    // that subsequent shrinking does not lead to incorrect block placing.
 8922    const MAX_PREPAINT_DEPTH: usize = 5;
 8923
 8924    fn increment_prepaint_depth(&self) -> EditorPrepaintGuard {
 8925        let depth = self.prepaint_depth.get();
 8926        self.prepaint_depth.set(depth + 1);
 8927        EditorPrepaintGuard {
 8928            prepaint_depth: self.prepaint_depth.clone(),
 8929        }
 8930    }
 8931
 8932    fn can_prepaint(&self) -> bool {
 8933        self.prepaint_depth.get() < Self::MAX_PREPAINT_DEPTH
 8934    }
 8935}
 8936
 8937struct EditorPrepaintGuard {
 8938    prepaint_depth: Rc<Cell<usize>>,
 8939}
 8940
 8941impl Drop for EditorPrepaintGuard {
 8942    fn drop(&mut self) {
 8943        let depth = self.prepaint_depth.get();
 8944        self.prepaint_depth.set(depth.saturating_sub(1));
 8945    }
 8946}
 8947
 8948impl Element for EditorElement {
 8949    type RequestLayoutState = EditorRequestLayoutState;
 8950    type PrepaintState = EditorLayout;
 8951
 8952    fn id(&self) -> Option<ElementId> {
 8953        None
 8954    }
 8955
 8956    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
 8957        None
 8958    }
 8959
 8960    fn request_layout(
 8961        &mut self,
 8962        _: Option<&GlobalElementId>,
 8963        _inspector_id: Option<&gpui::InspectorElementId>,
 8964        window: &mut Window,
 8965        cx: &mut App,
 8966    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
 8967        let rem_size = self.rem_size(cx);
 8968        window.with_rem_size(rem_size, |window| {
 8969            self.editor.update(cx, |editor, cx| {
 8970                editor.set_style(self.style.clone(), window, cx);
 8971
 8972                let layout_id = match editor.mode {
 8973                    EditorMode::SingleLine => {
 8974                        let rem_size = window.rem_size();
 8975                        let height = self.style.text.line_height_in_pixels(rem_size);
 8976                        let mut style = Style::default();
 8977                        style.size.height = height.into();
 8978                        style.size.width = relative(1.).into();
 8979                        window.request_layout(style, None, cx)
 8980                    }
 8981                    EditorMode::AutoHeight {
 8982                        min_lines,
 8983                        max_lines,
 8984                    } => {
 8985                        let editor_handle = cx.entity();
 8986                        window.request_measured_layout(
 8987                            Style::default(),
 8988                            move |known_dimensions, available_space, window, cx| {
 8989                                editor_handle
 8990                                    .update(cx, |editor, cx| {
 8991                                        compute_auto_height_layout(
 8992                                            editor,
 8993                                            min_lines,
 8994                                            max_lines,
 8995                                            known_dimensions,
 8996                                            available_space.width,
 8997                                            window,
 8998                                            cx,
 8999                                        )
 9000                                    })
 9001                                    .unwrap_or_default()
 9002                            },
 9003                        )
 9004                    }
 9005                    EditorMode::Minimap { .. } => {
 9006                        let mut style = Style::default();
 9007                        style.size.width = relative(1.).into();
 9008                        style.size.height = relative(1.).into();
 9009                        window.request_layout(style, None, cx)
 9010                    }
 9011                    EditorMode::Full {
 9012                        sizing_behavior, ..
 9013                    } => {
 9014                        let mut style = Style::default();
 9015                        style.size.width = relative(1.).into();
 9016                        if sizing_behavior == SizingBehavior::SizeByContent {
 9017                            let snapshot = editor.snapshot(window, cx);
 9018                            let line_height =
 9019                                self.style.text.line_height_in_pixels(window.rem_size());
 9020                            let scroll_height =
 9021                                (snapshot.max_point().row().next_row().0 as f32) * line_height;
 9022                            style.size.height = scroll_height.into();
 9023                        } else {
 9024                            style.size.height = relative(1.).into();
 9025                        }
 9026                        window.request_layout(style, None, cx)
 9027                    }
 9028                };
 9029
 9030                (layout_id, EditorRequestLayoutState::default())
 9031            })
 9032        })
 9033    }
 9034
 9035    fn prepaint(
 9036        &mut self,
 9037        _: Option<&GlobalElementId>,
 9038        _inspector_id: Option<&gpui::InspectorElementId>,
 9039        bounds: Bounds<Pixels>,
 9040        request_layout: &mut Self::RequestLayoutState,
 9041        window: &mut Window,
 9042        cx: &mut App,
 9043    ) -> Self::PrepaintState {
 9044        let _prepaint_depth_guard = request_layout.increment_prepaint_depth();
 9045        let text_style = TextStyleRefinement {
 9046            font_size: Some(self.style.text.font_size),
 9047            line_height: Some(self.style.text.line_height),
 9048            ..Default::default()
 9049        };
 9050
 9051        let is_minimap = self.editor.read(cx).mode.is_minimap();
 9052        let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
 9053
 9054        if !is_minimap {
 9055            let focus_handle = self.editor.focus_handle(cx);
 9056            window.set_view_id(self.editor.entity_id());
 9057            window.set_focus_handle(&focus_handle, cx);
 9058        }
 9059
 9060        let rem_size = self.rem_size(cx);
 9061        window.with_rem_size(rem_size, |window| {
 9062            window.with_text_style(Some(text_style), |window| {
 9063                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 9064                    let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
 9065                        (editor.snapshot(window, cx), editor.read_only(cx))
 9066                    });
 9067                    let style = &self.style;
 9068
 9069                    let rem_size = window.rem_size();
 9070                    let font_id = window.text_system().resolve_font(&style.text.font());
 9071                    let font_size = style.text.font_size.to_pixels(rem_size);
 9072                    let line_height = style.text.line_height_in_pixels(rem_size);
 9073                    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
 9074                    let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
 9075                    let glyph_grid_cell = size(em_advance, line_height);
 9076
 9077                    let gutter_dimensions = snapshot
 9078                        .gutter_dimensions(
 9079                            font_id,
 9080                            font_size,
 9081                            style,
 9082                            window,
 9083                            cx,
 9084                        );
 9085                    let text_width = bounds.size.width - gutter_dimensions.width;
 9086
 9087                    let settings = EditorSettings::get_global(cx);
 9088                    let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
 9089                    let vertical_scrollbar_width = (scrollbars_shown
 9090                        && settings.scrollbar.axes.vertical
 9091                        && self.editor.read(cx).show_scrollbars.vertical)
 9092                        .then_some(style.scrollbar_width)
 9093                        .unwrap_or_default();
 9094                    let minimap_width = self
 9095                        .get_minimap_width(
 9096                            &settings.minimap,
 9097                            scrollbars_shown,
 9098                            text_width,
 9099                            em_width,
 9100                            font_size,
 9101                            rem_size,
 9102                            cx,
 9103                        )
 9104                        .unwrap_or_default();
 9105
 9106                    let right_margin = minimap_width + vertical_scrollbar_width;
 9107
 9108                    let editor_width =
 9109                        text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
 9110                    let editor_margins = EditorMargins {
 9111                        gutter: gutter_dimensions,
 9112                        right: right_margin,
 9113                    };
 9114
 9115                    snapshot = self.editor.update(cx, |editor, cx| {
 9116                        editor.last_bounds = Some(bounds);
 9117                        editor.gutter_dimensions = gutter_dimensions;
 9118                        editor.set_visible_line_count(
 9119                            (bounds.size.height / line_height) as f64,
 9120                            window,
 9121                            cx,
 9122                        );
 9123                        editor.set_visible_column_count(f64::from(editor_width / em_advance));
 9124
 9125                        if matches!(
 9126                            editor.mode,
 9127                            EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
 9128                        ) {
 9129                            snapshot
 9130                        } else {
 9131                            let wrap_width_for = |column: u32| (column as f32 * em_advance).ceil();
 9132                            let wrap_width = match editor.soft_wrap_mode(cx) {
 9133                                SoftWrap::GitDiff => None,
 9134                                SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
 9135                                SoftWrap::EditorWidth => Some(editor_width),
 9136                                SoftWrap::Column(column) => Some(wrap_width_for(column)),
 9137                                SoftWrap::Bounded(column) => {
 9138                                    Some(editor_width.min(wrap_width_for(column)))
 9139                                }
 9140                            };
 9141
 9142                            if editor.set_wrap_width(wrap_width, cx) {
 9143                                editor.snapshot(window, cx)
 9144                            } else {
 9145                                snapshot
 9146                            }
 9147                        }
 9148                    });
 9149
 9150                    let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
 9151                    let gutter_hitbox = window.insert_hitbox(
 9152                        gutter_bounds(bounds, gutter_dimensions),
 9153                        HitboxBehavior::Normal,
 9154                    );
 9155                    let text_hitbox = window.insert_hitbox(
 9156                        Bounds {
 9157                            origin: gutter_hitbox.top_right(),
 9158                            size: size(text_width, bounds.size.height),
 9159                        },
 9160                        HitboxBehavior::Normal,
 9161                    );
 9162
 9163                    // Offset the content_bounds from the text_bounds by the gutter margin (which
 9164                    // is roughly half a character wide) to make hit testing work more like how we want.
 9165                    let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
 9166                    let content_origin = text_hitbox.origin + content_offset;
 9167
 9168                    let height_in_lines = f64::from(bounds.size.height / line_height);
 9169                    let max_row = snapshot.max_point().row().as_f64();
 9170
 9171                    // Calculate how much of the editor is clipped by parent containers (e.g., List).
 9172                    // This allows us to only render lines that are actually visible, which is
 9173                    // critical for performance when large AutoHeight editors are inside Lists.
 9174                    let visible_bounds = window.content_mask().bounds;
 9175                    let clipped_top = (visible_bounds.origin.y - bounds.origin.y).max(px(0.));
 9176                    let clipped_top_in_lines = f64::from(clipped_top / line_height);
 9177                    let visible_height_in_lines =
 9178                        f64::from(visible_bounds.size.height / line_height);
 9179
 9180                    // The max scroll position for the top of the window
 9181                    let max_scroll_top = if matches!(
 9182                        snapshot.mode,
 9183                        EditorMode::SingleLine
 9184                            | EditorMode::AutoHeight { .. }
 9185                            | EditorMode::Full {
 9186                                sizing_behavior: SizingBehavior::ExcludeOverscrollMargin
 9187                                    | SizingBehavior::SizeByContent,
 9188                                ..
 9189                            }
 9190                    ) {
 9191                        (max_row - height_in_lines + 1.).max(0.)
 9192                    } else {
 9193                        let settings = EditorSettings::get_global(cx);
 9194                        match settings.scroll_beyond_last_line {
 9195                            ScrollBeyondLastLine::OnePage => max_row,
 9196                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
 9197                            ScrollBeyondLastLine::VerticalScrollMargin => {
 9198                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
 9199                                    .max(0.)
 9200                            }
 9201                        }
 9202                    };
 9203
 9204                    let (
 9205                        autoscroll_request,
 9206                        autoscroll_containing_element,
 9207                        needs_horizontal_autoscroll,
 9208                    ) = self.editor.update(cx, |editor, cx| {
 9209                        let autoscroll_request = editor.scroll_manager.take_autoscroll_request();
 9210
 9211                        let autoscroll_containing_element =
 9212                            autoscroll_request.is_some() || editor.has_pending_selection();
 9213
 9214                        let (needs_horizontal_autoscroll, was_scrolled) = editor
 9215                            .autoscroll_vertically(
 9216                                bounds,
 9217                                line_height,
 9218                                max_scroll_top,
 9219                                autoscroll_request,
 9220                                window,
 9221                                cx,
 9222                            );
 9223                        if was_scrolled.0 {
 9224                            snapshot = editor.snapshot(window, cx);
 9225                        }
 9226                        (
 9227                            autoscroll_request,
 9228                            autoscroll_containing_element,
 9229                            needs_horizontal_autoscroll,
 9230                        )
 9231                    });
 9232
 9233                    let mut scroll_position = snapshot.scroll_position();
 9234                    // The scroll position is a fractional point, the whole number of which represents
 9235                    // the top of the window in terms of display rows.
 9236                    // We add clipped_top_in_lines to skip rows that are clipped by parent containers,
 9237                    // but we don't modify scroll_position itself since the parent handles positioning.
 9238                    let max_row = snapshot.max_point().row();
 9239                    let start_row = cmp::min(
 9240                        DisplayRow((scroll_position.y + clipped_top_in_lines).floor() as u32),
 9241                        max_row,
 9242                    );
 9243                    let end_row = cmp::min(
 9244                        (scroll_position.y + clipped_top_in_lines + visible_height_in_lines).ceil()
 9245                            as u32,
 9246                        max_row.next_row().0,
 9247                    );
 9248                    let end_row = DisplayRow(end_row);
 9249
 9250                    let row_infos = snapshot // note we only get the visual range
 9251                        .row_infos(start_row)
 9252                        .take((start_row..end_row).len())
 9253                        .collect::<Vec<RowInfo>>();
 9254                    let is_row_soft_wrapped = |row: usize| {
 9255                        row_infos
 9256                            .get(row)
 9257                            .is_none_or(|info| info.buffer_row.is_none())
 9258                    };
 9259
 9260                    let start_anchor = if start_row == Default::default() {
 9261                        Anchor::min()
 9262                    } else {
 9263                        snapshot.buffer_snapshot().anchor_before(
 9264                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
 9265                        )
 9266                    };
 9267                    let end_anchor = if end_row > max_row {
 9268                        Anchor::max()
 9269                    } else {
 9270                        snapshot.buffer_snapshot().anchor_before(
 9271                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
 9272                        )
 9273                    };
 9274
 9275                    let mut highlighted_rows = self
 9276                        .editor
 9277                        .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
 9278
 9279                    let is_light = cx.theme().appearance().is_light();
 9280
 9281                    let mut highlighted_ranges = self
 9282                        .editor_with_selections(cx)
 9283                        .map(|editor| {
 9284                            editor.read(cx).background_highlights_in_range(
 9285                                start_anchor..end_anchor,
 9286                                &snapshot.display_snapshot,
 9287                                cx.theme(),
 9288                            )
 9289                        })
 9290                        .unwrap_or_default();
 9291
 9292                    for (ix, row_info) in row_infos.iter().enumerate() {
 9293                        let Some(diff_status) = row_info.diff_status else {
 9294                            continue;
 9295                        };
 9296
 9297                        let background_color = match diff_status.kind {
 9298                            DiffHunkStatusKind::Added =>
 9299                                cx.theme().colors().version_control_added,
 9300                            DiffHunkStatusKind::Deleted =>
 9301                                cx.theme().colors().version_control_deleted,
 9302                            DiffHunkStatusKind::Modified => {
 9303                                debug_panic!("modified diff status for row info");
 9304                                continue;
 9305                            }
 9306                        };
 9307
 9308                        let hunk_opacity = if is_light { 0.16 } else { 0.12 };
 9309
 9310                        let hollow_highlight = LineHighlight {
 9311                            background: (background_color.opacity(if is_light {
 9312                                0.08
 9313                            } else {
 9314                                0.06
 9315                            }))
 9316                            .into(),
 9317                            border: Some(if is_light {
 9318                                background_color.opacity(0.48)
 9319                            } else {
 9320                                background_color.opacity(0.36)
 9321                            }),
 9322                            include_gutter: true,
 9323                            type_id: None,
 9324                        };
 9325
 9326                        let filled_highlight = LineHighlight {
 9327                            background: solid_background(background_color.opacity(hunk_opacity)),
 9328                            border: None,
 9329                            include_gutter: true,
 9330                            type_id: None,
 9331                        };
 9332
 9333                        let background = if Self::diff_hunk_hollow(diff_status, cx) {
 9334                            hollow_highlight
 9335                        } else {
 9336                            filled_highlight
 9337                        };
 9338
 9339                        let base_display_point =
 9340                            DisplayPoint::new(start_row + DisplayRow(ix as u32), 0);
 9341
 9342                        highlighted_rows
 9343                            .entry(base_display_point.row())
 9344                            .or_insert(background);
 9345                    }
 9346
 9347                    let highlighted_gutter_ranges =
 9348                        self.editor.read(cx).gutter_highlights_in_range(
 9349                            start_anchor..end_anchor,
 9350                            &snapshot.display_snapshot,
 9351                            cx,
 9352                        );
 9353
 9354                    let document_colors = self
 9355                        .editor
 9356                        .read(cx)
 9357                        .colors
 9358                        .as_ref()
 9359                        .map(|colors| colors.editor_display_highlights(&snapshot));
 9360                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
 9361                        start_anchor..end_anchor,
 9362                        &snapshot.display_snapshot,
 9363                        cx,
 9364                    );
 9365
 9366                    let (local_selections, selected_buffer_ids, latest_selection_anchors): (
 9367                        Vec<Selection<Point>>,
 9368                        Vec<BufferId>,
 9369                        HashMap<BufferId, Anchor>,
 9370                    ) = self
 9371                        .editor_with_selections(cx)
 9372                        .map(|editor| {
 9373                            editor.update(cx, |editor, cx| {
 9374                                let all_selections =
 9375                                    editor.selections.all::<Point>(&snapshot.display_snapshot);
 9376                                let all_anchor_selections =
 9377                                    editor.selections.all_anchors(&snapshot.display_snapshot);
 9378                                let selected_buffer_ids =
 9379                                    if editor.buffer_kind(cx) == ItemBufferKind::Singleton {
 9380                                        Vec::new()
 9381                                    } else {
 9382                                        let mut selected_buffer_ids =
 9383                                            Vec::with_capacity(all_selections.len());
 9384
 9385                                        for selection in all_selections {
 9386                                            for buffer_id in snapshot
 9387                                                .buffer_snapshot()
 9388                                                .buffer_ids_for_range(selection.range())
 9389                                            {
 9390                                                if selected_buffer_ids.last() != Some(&buffer_id) {
 9391                                                    selected_buffer_ids.push(buffer_id);
 9392                                                }
 9393                                            }
 9394                                        }
 9395
 9396                                        selected_buffer_ids
 9397                                    };
 9398
 9399                                let mut selections = editor.selections.disjoint_in_range(
 9400                                    start_anchor..end_anchor,
 9401                                    &snapshot.display_snapshot,
 9402                                );
 9403                                selections
 9404                                    .extend(editor.selections.pending(&snapshot.display_snapshot));
 9405
 9406                                let mut anchors_by_buffer: HashMap<BufferId, (usize, Anchor)> =
 9407                                    HashMap::default();
 9408                                for selection in all_anchor_selections.iter() {
 9409                                    let head = selection.head();
 9410                                    if let Some(buffer_id) = head.text_anchor.buffer_id {
 9411                                        anchors_by_buffer
 9412                                            .entry(buffer_id)
 9413                                            .and_modify(|(latest_id, latest_anchor)| {
 9414                                                if selection.id > *latest_id {
 9415                                                    *latest_id = selection.id;
 9416                                                    *latest_anchor = head;
 9417                                                }
 9418                                            })
 9419                                            .or_insert((selection.id, head));
 9420                                    }
 9421                                }
 9422                                let latest_selection_anchors = anchors_by_buffer
 9423                                    .into_iter()
 9424                                    .map(|(buffer_id, (_, anchor))| (buffer_id, anchor))
 9425                                    .collect();
 9426
 9427                                (selections, selected_buffer_ids, latest_selection_anchors)
 9428                            })
 9429                        })
 9430                        .unwrap_or_else(|| (Vec::new(), Vec::new(), HashMap::default()));
 9431
 9432                    let (selections, mut active_rows, newest_selection_head) = self
 9433                        .layout_selections(
 9434                            start_anchor,
 9435                            end_anchor,
 9436                            &local_selections,
 9437                            &snapshot,
 9438                            start_row,
 9439                            end_row,
 9440                            window,
 9441                            cx,
 9442                        );
 9443                    let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
 9444                        editor.active_breakpoints(start_row..end_row, window, cx)
 9445                    });
 9446                    for (display_row, (_, bp, state)) in &breakpoint_rows {
 9447                        if bp.is_enabled() && state.is_none_or(|s| s.verified) {
 9448                            active_rows.entry(*display_row).or_default().breakpoint = true;
 9449                        }
 9450                    }
 9451
 9452                    let line_numbers = self.layout_line_numbers(
 9453                        Some(&gutter_hitbox),
 9454                        gutter_dimensions,
 9455                        line_height,
 9456                        scroll_position,
 9457                        start_row..end_row,
 9458                        &row_infos,
 9459                        &active_rows,
 9460                        newest_selection_head,
 9461                        &snapshot,
 9462                        window,
 9463                        cx,
 9464                    );
 9465
 9466                    // We add the gutter breakpoint indicator to breakpoint_rows after painting
 9467                    // line numbers so we don't paint a line number debug accent color if a user
 9468                    // has their mouse over that line when a breakpoint isn't there
 9469                    self.editor.update(cx, |editor, _| {
 9470                        if let Some(phantom_breakpoint) = &mut editor
 9471                            .gutter_breakpoint_indicator
 9472                            .0
 9473                            .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
 9474                        {
 9475                            // Is there a non-phantom breakpoint on this line?
 9476                            phantom_breakpoint.collides_with_existing_breakpoint = true;
 9477                            breakpoint_rows
 9478                                .entry(phantom_breakpoint.display_row)
 9479                                .or_insert_with(|| {
 9480                                    let position = snapshot.display_point_to_anchor(
 9481                                        DisplayPoint::new(phantom_breakpoint.display_row, 0),
 9482                                        Bias::Right,
 9483                                    );
 9484                                    let breakpoint = Breakpoint::new_standard();
 9485                                    phantom_breakpoint.collides_with_existing_breakpoint = false;
 9486                                    (position, breakpoint, None)
 9487                                });
 9488                        }
 9489                    });
 9490
 9491                    let mut expand_toggles =
 9492                        window.with_element_namespace("expand_toggles", |window| {
 9493                            self.layout_expand_toggles(
 9494                                &gutter_hitbox,
 9495                                gutter_dimensions,
 9496                                em_width,
 9497                                line_height,
 9498                                scroll_position,
 9499                                &row_infos,
 9500                                window,
 9501                                cx,
 9502                            )
 9503                        });
 9504
 9505                    let mut crease_toggles =
 9506                        window.with_element_namespace("crease_toggles", |window| {
 9507                            self.layout_crease_toggles(
 9508                                start_row..end_row,
 9509                                &row_infos,
 9510                                &active_rows,
 9511                                &snapshot,
 9512                                window,
 9513                                cx,
 9514                            )
 9515                        });
 9516                    let crease_trailers =
 9517                        window.with_element_namespace("crease_trailers", |window| {
 9518                            self.layout_crease_trailers(
 9519                                row_infos.iter().cloned(),
 9520                                &snapshot,
 9521                                window,
 9522                                cx,
 9523                            )
 9524                        });
 9525
 9526                    let display_hunks = self.layout_gutter_diff_hunks(
 9527                        line_height,
 9528                        &gutter_hitbox,
 9529                        start_row..end_row,
 9530                        &snapshot,
 9531                        window,
 9532                        cx,
 9533                    );
 9534
 9535                    Self::layout_word_diff_highlights(
 9536                        &display_hunks,
 9537                        &row_infos,
 9538                        start_row,
 9539                        &snapshot,
 9540                        &mut highlighted_ranges,
 9541                        cx,
 9542                    );
 9543
 9544                    let merged_highlighted_ranges =
 9545                        if let Some((_, colors)) = document_colors.as_ref() {
 9546                            &highlighted_ranges
 9547                                .clone()
 9548                                .into_iter()
 9549                                .chain(colors.clone())
 9550                                .collect()
 9551                        } else {
 9552                            &highlighted_ranges
 9553                        };
 9554                    let bg_segments_per_row = Self::bg_segments_per_row(
 9555                        start_row..end_row,
 9556                        &selections,
 9557                        &merged_highlighted_ranges,
 9558                        self.style.background,
 9559                    );
 9560
 9561                    let mut line_layouts = Self::layout_lines(
 9562                        start_row..end_row,
 9563                        &snapshot,
 9564                        &self.style,
 9565                        editor_width,
 9566                        is_row_soft_wrapped,
 9567                        &bg_segments_per_row,
 9568                        window,
 9569                        cx,
 9570                    );
 9571                    let new_renderer_widths = (!is_minimap).then(|| {
 9572                        line_layouts
 9573                            .iter()
 9574                            .flat_map(|layout| &layout.fragments)
 9575                            .filter_map(|fragment| {
 9576                                if let LineFragment::Element { id, size, .. } = fragment {
 9577                                    Some((*id, size.width))
 9578                                } else {
 9579                                    None
 9580                                }
 9581                            })
 9582                    });
 9583                    if new_renderer_widths.is_some_and(|new_renderer_widths| {
 9584                        self.editor.update(cx, |editor, cx| {
 9585                            editor.update_renderer_widths(new_renderer_widths, cx)
 9586                        })
 9587                    }) {
 9588                        // If the fold widths have changed, we need to prepaint
 9589                        // the element again to account for any changes in
 9590                        // wrapping.
 9591                        if request_layout.can_prepaint() {
 9592                            return self.prepaint(
 9593                                None,
 9594                                _inspector_id,
 9595                                bounds,
 9596                                request_layout,
 9597                                window,
 9598                                cx,
 9599                            );
 9600                        } else {
 9601                            debug_panic!(
 9602                                "skipping recursive prepaint at max depth. renderer widths may be stale."
 9603                            );
 9604                        }
 9605                    }
 9606
 9607                    let longest_line_blame_width = self
 9608                        .editor
 9609                        .update(cx, |editor, cx| {
 9610                            if !editor.show_git_blame_inline {
 9611                                return None;
 9612                            }
 9613                            let blame = editor.blame.as_ref()?;
 9614                            let (_, blame_entry) = blame
 9615                                .update(cx, |blame, cx| {
 9616                                    let row_infos =
 9617                                        snapshot.row_infos(snapshot.longest_row()).next()?;
 9618                                    blame.blame_for_rows(&[row_infos], cx).next()
 9619                                })
 9620                                .flatten()?;
 9621                            let mut element = render_inline_blame_entry(blame_entry, style, cx)?;
 9622                            let inline_blame_padding =
 9623                                ProjectSettings::get_global(cx).git.inline_blame.padding as f32
 9624                                    * em_advance;
 9625                            Some(
 9626                                element
 9627                                    .layout_as_root(AvailableSpace::min_size(), window, cx)
 9628                                    .width
 9629                                    + inline_blame_padding,
 9630                            )
 9631                        })
 9632                        .unwrap_or(Pixels::ZERO);
 9633
 9634                    let longest_line_width = layout_line(
 9635                        snapshot.longest_row(),
 9636                        &snapshot,
 9637                        style,
 9638                        editor_width,
 9639                        is_row_soft_wrapped,
 9640                        window,
 9641                        cx,
 9642                    )
 9643                    .width;
 9644
 9645                    let scrollbar_layout_information = ScrollbarLayoutInformation::new(
 9646                        text_hitbox.bounds,
 9647                        glyph_grid_cell,
 9648                        size(
 9649                            longest_line_width,
 9650                            Pixels::from(max_row.as_f64() * f64::from(line_height)),
 9651                        ),
 9652                        longest_line_blame_width,
 9653                        EditorSettings::get_global(cx),
 9654                    );
 9655
 9656                    let mut scroll_width = scrollbar_layout_information.scroll_range.width;
 9657
 9658                    let sticky_header_excerpt = if snapshot.buffer_snapshot().show_headers() {
 9659                        snapshot.sticky_header_excerpt(scroll_position.y)
 9660                    } else {
 9661                        None
 9662                    };
 9663                    let sticky_header_excerpt_id =
 9664                        sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
 9665
 9666                    let blocks = (!is_minimap)
 9667                        .then(|| {
 9668                            window.with_element_namespace("blocks", |window| {
 9669                                self.render_blocks(
 9670                                    start_row..end_row,
 9671                                    &snapshot,
 9672                                    &hitbox,
 9673                                    &text_hitbox,
 9674                                    editor_width,
 9675                                    &mut scroll_width,
 9676                                    &editor_margins,
 9677                                    em_width,
 9678                                    gutter_dimensions.full_width(),
 9679                                    line_height,
 9680                                    &mut line_layouts,
 9681                                    &local_selections,
 9682                                    &selected_buffer_ids,
 9683                                    &latest_selection_anchors,
 9684                                    is_row_soft_wrapped,
 9685                                    sticky_header_excerpt_id,
 9686                                    window,
 9687                                    cx,
 9688                                )
 9689                            })
 9690                        })
 9691                        .unwrap_or_default();
 9692                    let RenderBlocksOutput {
 9693                        mut blocks,
 9694                        row_block_types,
 9695                        resized_blocks,
 9696                    } = blocks;
 9697                    if let Some(resized_blocks) = resized_blocks {
 9698                        self.editor.update(cx, |editor, cx| {
 9699                            editor.resize_blocks(
 9700                                resized_blocks,
 9701                                autoscroll_request.map(|(autoscroll, _)| autoscroll),
 9702                                cx,
 9703                            )
 9704                        });
 9705                        if request_layout.can_prepaint() {
 9706                            return self.prepaint(
 9707                                None,
 9708                                _inspector_id,
 9709                                bounds,
 9710                                request_layout,
 9711                                window,
 9712                                cx,
 9713                            );
 9714                        } else {
 9715                            debug_panic!(
 9716                                "skipping recursive prepaint at max depth. block layout may be stale."
 9717                            );
 9718                        }
 9719                    }
 9720
 9721                    let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
 9722                        window.with_element_namespace("blocks", |window| {
 9723                            self.layout_sticky_buffer_header(
 9724                                sticky_header_excerpt,
 9725                                scroll_position,
 9726                                line_height,
 9727                                right_margin,
 9728                                &snapshot,
 9729                                &hitbox,
 9730                                &selected_buffer_ids,
 9731                                &blocks,
 9732                                &latest_selection_anchors,
 9733                                window,
 9734                                cx,
 9735                            )
 9736                        })
 9737                    });
 9738
 9739                    let start_buffer_row =
 9740                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot()).row);
 9741                    let end_buffer_row =
 9742                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot()).row);
 9743
 9744                    let scroll_max: gpui::Point<ScrollPixelOffset> = point(
 9745                        ScrollPixelOffset::from(
 9746                            ((scroll_width - editor_width) / em_advance).max(0.0),
 9747                        ),
 9748                        max_scroll_top,
 9749                    );
 9750
 9751                    self.editor.update(cx, |editor, cx| {
 9752                        if editor.scroll_manager.clamp_scroll_left(scroll_max.x) {
 9753                            scroll_position.x = scroll_position.x.min(scroll_max.x);
 9754                        }
 9755
 9756                        if needs_horizontal_autoscroll.0
 9757                            && let Some(new_scroll_position) = editor.autoscroll_horizontally(
 9758                                start_row,
 9759                                editor_width,
 9760                                scroll_width,
 9761                                em_advance,
 9762                                &line_layouts,
 9763                                autoscroll_request,
 9764                                window,
 9765                                cx,
 9766                            )
 9767                        {
 9768                            scroll_position = new_scroll_position;
 9769                        }
 9770                    });
 9771
 9772                    let scroll_pixel_position = point(
 9773                        scroll_position.x * f64::from(em_advance),
 9774                        scroll_position.y * f64::from(line_height),
 9775                    );
 9776                    let sticky_headers = if !is_minimap
 9777                        && is_singleton
 9778                        && EditorSettings::get_global(cx).sticky_scroll.enabled
 9779                    {
 9780                        self.layout_sticky_headers(
 9781                            &snapshot,
 9782                            editor_width,
 9783                            is_row_soft_wrapped,
 9784                            line_height,
 9785                            scroll_pixel_position,
 9786                            content_origin,
 9787                            &gutter_dimensions,
 9788                            &gutter_hitbox,
 9789                            &text_hitbox,
 9790                            &style,
 9791                            window,
 9792                            cx,
 9793                        )
 9794                    } else {
 9795                        None
 9796                    };
 9797                    let indent_guides = self.layout_indent_guides(
 9798                        content_origin,
 9799                        text_hitbox.origin,
 9800                        start_buffer_row..end_buffer_row,
 9801                        scroll_pixel_position,
 9802                        line_height,
 9803                        &snapshot,
 9804                        window,
 9805                        cx,
 9806                    );
 9807
 9808                    let crease_trailers =
 9809                        window.with_element_namespace("crease_trailers", |window| {
 9810                            self.prepaint_crease_trailers(
 9811                                crease_trailers,
 9812                                &line_layouts,
 9813                                line_height,
 9814                                content_origin,
 9815                                scroll_pixel_position,
 9816                                em_width,
 9817                                window,
 9818                                cx,
 9819                            )
 9820                        });
 9821
 9822                    let (edit_prediction_popover, edit_prediction_popover_origin) = self
 9823                        .editor
 9824                        .update(cx, |editor, cx| {
 9825                            editor.render_edit_prediction_popover(
 9826                                &text_hitbox.bounds,
 9827                                content_origin,
 9828                                right_margin,
 9829                                &snapshot,
 9830                                start_row..end_row,
 9831                                scroll_position.y,
 9832                                scroll_position.y + height_in_lines,
 9833                                &line_layouts,
 9834                                line_height,
 9835                                scroll_position,
 9836                                scroll_pixel_position,
 9837                                newest_selection_head,
 9838                                editor_width,
 9839                                style,
 9840                                window,
 9841                                cx,
 9842                            )
 9843                        })
 9844                        .unzip();
 9845
 9846                    let mut inline_diagnostics = self.layout_inline_diagnostics(
 9847                        &line_layouts,
 9848                        &crease_trailers,
 9849                        &row_block_types,
 9850                        content_origin,
 9851                        scroll_position,
 9852                        scroll_pixel_position,
 9853                        edit_prediction_popover_origin,
 9854                        start_row,
 9855                        end_row,
 9856                        line_height,
 9857                        em_width,
 9858                        style,
 9859                        window,
 9860                        cx,
 9861                    );
 9862
 9863                    let mut inline_blame_layout = None;
 9864                    let mut inline_code_actions = None;
 9865                    if let Some(newest_selection_head) = newest_selection_head {
 9866                        let display_row = newest_selection_head.row();
 9867                        if (start_row..end_row).contains(&display_row)
 9868                            && !row_block_types.contains_key(&display_row)
 9869                        {
 9870                            inline_code_actions = self.layout_inline_code_actions(
 9871                                newest_selection_head,
 9872                                content_origin,
 9873                                scroll_position,
 9874                                scroll_pixel_position,
 9875                                line_height,
 9876                                &snapshot,
 9877                                window,
 9878                                cx,
 9879                            );
 9880
 9881                            let line_ix = display_row.minus(start_row) as usize;
 9882                            if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
 9883                                row_infos.get(line_ix),
 9884                                line_layouts.get(line_ix),
 9885                                crease_trailers.get(line_ix),
 9886                            ) {
 9887                                let crease_trailer_layout = crease_trailer.as_ref();
 9888                                if let Some(layout) = self.layout_inline_blame(
 9889                                    display_row,
 9890                                    row_info,
 9891                                    line_layout,
 9892                                    crease_trailer_layout,
 9893                                    em_width,
 9894                                    content_origin,
 9895                                    scroll_position,
 9896                                    scroll_pixel_position,
 9897                                    line_height,
 9898                                    window,
 9899                                    cx,
 9900                                ) {
 9901                                    inline_blame_layout = Some(layout);
 9902                                    // Blame overrides inline diagnostics
 9903                                    inline_diagnostics.remove(&display_row);
 9904                                }
 9905                            } else {
 9906                                log::error!(
 9907                                    "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
 9908                                    line_layouts.len(): {}, \
 9909                                    crease_trailers.len(): {}",
 9910                                    line_ix,
 9911                                    row_infos.len(),
 9912                                    line_layouts.len(),
 9913                                    crease_trailers.len(),
 9914                                );
 9915                            }
 9916                        }
 9917                    }
 9918
 9919                    let blamed_display_rows = self.layout_blame_entries(
 9920                        &row_infos,
 9921                        em_width,
 9922                        scroll_position,
 9923                        line_height,
 9924                        &gutter_hitbox,
 9925                        gutter_dimensions.git_blame_entries_width,
 9926                        window,
 9927                        cx,
 9928                    );
 9929
 9930                    let line_elements = self.prepaint_lines(
 9931                        start_row,
 9932                        &mut line_layouts,
 9933                        line_height,
 9934                        scroll_position,
 9935                        scroll_pixel_position,
 9936                        content_origin,
 9937                        window,
 9938                        cx,
 9939                    );
 9940
 9941                    window.with_element_namespace("blocks", |window| {
 9942                        self.layout_blocks(
 9943                            &mut blocks,
 9944                            &hitbox,
 9945                            line_height,
 9946                            scroll_position,
 9947                            scroll_pixel_position,
 9948                            window,
 9949                            cx,
 9950                        );
 9951                    });
 9952
 9953                    let cursors = self.collect_cursors(&snapshot, cx);
 9954                    let visible_row_range = start_row..end_row;
 9955                    let non_visible_cursors = cursors
 9956                        .iter()
 9957                        .any(|c| !visible_row_range.contains(&c.0.row()));
 9958
 9959                    let visible_cursors = self.layout_visible_cursors(
 9960                        &snapshot,
 9961                        &selections,
 9962                        &row_block_types,
 9963                        start_row..end_row,
 9964                        &line_layouts,
 9965                        &text_hitbox,
 9966                        content_origin,
 9967                        scroll_position,
 9968                        scroll_pixel_position,
 9969                        line_height,
 9970                        em_width,
 9971                        em_advance,
 9972                        autoscroll_containing_element,
 9973                        window,
 9974                        cx,
 9975                    );
 9976
 9977                    let scrollbars_layout = self.layout_scrollbars(
 9978                        &snapshot,
 9979                        &scrollbar_layout_information,
 9980                        content_offset,
 9981                        scroll_position,
 9982                        non_visible_cursors,
 9983                        right_margin,
 9984                        editor_width,
 9985                        window,
 9986                        cx,
 9987                    );
 9988
 9989                    let gutter_settings = EditorSettings::get_global(cx).gutter;
 9990
 9991                    let context_menu_layout =
 9992                        if let Some(newest_selection_head) = newest_selection_head {
 9993                            let newest_selection_point =
 9994                                newest_selection_head.to_point(&snapshot.display_snapshot);
 9995                            if (start_row..end_row).contains(&newest_selection_head.row()) {
 9996                                self.layout_cursor_popovers(
 9997                                    line_height,
 9998                                    &text_hitbox,
 9999                                    content_origin,
10000                                    right_margin,
10001                                    start_row,
10002                                    scroll_pixel_position,
10003                                    &line_layouts,
10004                                    newest_selection_head,
10005                                    newest_selection_point,
10006                                    style,
10007                                    window,
10008                                    cx,
10009                                )
10010                            } else {
10011                                None
10012                            }
10013                        } else {
10014                            None
10015                        };
10016
10017                    self.layout_gutter_menu(
10018                        line_height,
10019                        &text_hitbox,
10020                        content_origin,
10021                        right_margin,
10022                        scroll_pixel_position,
10023                        gutter_dimensions.width - gutter_dimensions.left_padding,
10024                        window,
10025                        cx,
10026                    );
10027
10028                    let test_indicators = if gutter_settings.runnables {
10029                        self.layout_run_indicators(
10030                            line_height,
10031                            start_row..end_row,
10032                            &row_infos,
10033                            scroll_position,
10034                            &gutter_dimensions,
10035                            &gutter_hitbox,
10036                            &display_hunks,
10037                            &snapshot,
10038                            &mut breakpoint_rows,
10039                            window,
10040                            cx,
10041                        )
10042                    } else {
10043                        Vec::new()
10044                    };
10045
10046                    let show_breakpoints = snapshot
10047                        .show_breakpoints
10048                        .unwrap_or(gutter_settings.breakpoints);
10049                    let breakpoints = if show_breakpoints {
10050                        self.layout_breakpoints(
10051                            line_height,
10052                            start_row..end_row,
10053                            scroll_position,
10054                            &gutter_dimensions,
10055                            &gutter_hitbox,
10056                            &display_hunks,
10057                            &snapshot,
10058                            breakpoint_rows,
10059                            &row_infos,
10060                            window,
10061                            cx,
10062                        )
10063                    } else {
10064                        Vec::new()
10065                    };
10066
10067                    self.layout_signature_help(
10068                        &hitbox,
10069                        content_origin,
10070                        scroll_pixel_position,
10071                        newest_selection_head,
10072                        start_row,
10073                        &line_layouts,
10074                        line_height,
10075                        em_width,
10076                        context_menu_layout,
10077                        window,
10078                        cx,
10079                    );
10080
10081                    if !cx.has_active_drag() {
10082                        self.layout_hover_popovers(
10083                            &snapshot,
10084                            &hitbox,
10085                            start_row..end_row,
10086                            content_origin,
10087                            scroll_pixel_position,
10088                            &line_layouts,
10089                            line_height,
10090                            em_width,
10091                            context_menu_layout,
10092                            window,
10093                            cx,
10094                        );
10095
10096                        self.layout_blame_popover(&snapshot, &hitbox, line_height, window, cx);
10097                    }
10098
10099                    let mouse_context_menu = self.layout_mouse_context_menu(
10100                        &snapshot,
10101                        start_row..end_row,
10102                        content_origin,
10103                        window,
10104                        cx,
10105                    );
10106
10107                    window.with_element_namespace("crease_toggles", |window| {
10108                        self.prepaint_crease_toggles(
10109                            &mut crease_toggles,
10110                            line_height,
10111                            &gutter_dimensions,
10112                            gutter_settings,
10113                            scroll_pixel_position,
10114                            &gutter_hitbox,
10115                            window,
10116                            cx,
10117                        )
10118                    });
10119
10120                    window.with_element_namespace("expand_toggles", |window| {
10121                        self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
10122                    });
10123
10124                    let wrap_guides = self.layout_wrap_guides(
10125                        em_advance,
10126                        scroll_position,
10127                        content_origin,
10128                        scrollbars_layout.as_ref(),
10129                        vertical_scrollbar_width,
10130                        &hitbox,
10131                        window,
10132                        cx,
10133                    );
10134
10135                    let minimap = window.with_element_namespace("minimap", |window| {
10136                        self.layout_minimap(
10137                            &snapshot,
10138                            minimap_width,
10139                            scroll_position,
10140                            &scrollbar_layout_information,
10141                            scrollbars_layout.as_ref(),
10142                            window,
10143                            cx,
10144                        )
10145                    });
10146
10147                    let invisible_symbol_font_size = font_size / 2.;
10148                    let whitespace_map = &self
10149                        .editor
10150                        .read(cx)
10151                        .buffer
10152                        .read(cx)
10153                        .language_settings(cx)
10154                        .whitespace_map;
10155
10156                    let tab_char = whitespace_map.tab.clone();
10157                    let tab_len = tab_char.len();
10158                    let tab_invisible = window.text_system().shape_line(
10159                        tab_char,
10160                        invisible_symbol_font_size,
10161                        &[TextRun {
10162                            len: tab_len,
10163                            font: self.style.text.font(),
10164                            color: cx.theme().colors().editor_invisible,
10165                            ..Default::default()
10166                        }],
10167                        None,
10168                    );
10169
10170                    let space_char = whitespace_map.space.clone();
10171                    let space_len = space_char.len();
10172                    let space_invisible = window.text_system().shape_line(
10173                        space_char,
10174                        invisible_symbol_font_size,
10175                        &[TextRun {
10176                            len: space_len,
10177                            font: self.style.text.font(),
10178                            color: cx.theme().colors().editor_invisible,
10179                            ..Default::default()
10180                        }],
10181                        None,
10182                    );
10183
10184                    let mode = snapshot.mode.clone();
10185
10186                    let (diff_hunk_controls, diff_hunk_control_bounds) = if is_read_only {
10187                        (vec![], vec![])
10188                    } else {
10189                        self.layout_diff_hunk_controls(
10190                            start_row..end_row,
10191                            &row_infos,
10192                            &text_hitbox,
10193                            newest_selection_head,
10194                            line_height,
10195                            right_margin,
10196                            scroll_pixel_position,
10197                            &display_hunks,
10198                            &highlighted_rows,
10199                            self.editor.clone(),
10200                            window,
10201                            cx,
10202                        )
10203                    };
10204
10205                    let position_map = Rc::new(PositionMap {
10206                        size: bounds.size,
10207                        visible_row_range,
10208                        scroll_position,
10209                        scroll_pixel_position,
10210                        scroll_max,
10211                        line_layouts,
10212                        line_height,
10213                        em_width,
10214                        em_advance,
10215                        snapshot,
10216                        gutter_hitbox: gutter_hitbox.clone(),
10217                        text_hitbox: text_hitbox.clone(),
10218                        inline_blame_bounds: inline_blame_layout
10219                            .as_ref()
10220                            .map(|layout| (layout.bounds, layout.buffer_id, layout.entry.clone())),
10221                        display_hunks: display_hunks.clone(),
10222                        diff_hunk_control_bounds,
10223                    });
10224
10225                    self.editor.update(cx, |editor, _| {
10226                        editor.last_position_map = Some(position_map.clone())
10227                    });
10228
10229                    EditorLayout {
10230                        mode,
10231                        position_map,
10232                        visible_display_row_range: start_row..end_row,
10233                        wrap_guides,
10234                        indent_guides,
10235                        hitbox,
10236                        gutter_hitbox,
10237                        display_hunks,
10238                        content_origin,
10239                        scrollbars_layout,
10240                        minimap,
10241                        active_rows,
10242                        highlighted_rows,
10243                        highlighted_ranges,
10244                        highlighted_gutter_ranges,
10245                        redacted_ranges,
10246                        document_colors,
10247                        line_elements,
10248                        line_numbers,
10249                        blamed_display_rows,
10250                        inline_diagnostics,
10251                        inline_blame_layout,
10252                        inline_code_actions,
10253                        blocks,
10254                        cursors,
10255                        visible_cursors,
10256                        selections,
10257                        edit_prediction_popover,
10258                        diff_hunk_controls,
10259                        mouse_context_menu,
10260                        test_indicators,
10261                        breakpoints,
10262                        crease_toggles,
10263                        crease_trailers,
10264                        tab_invisible,
10265                        space_invisible,
10266                        sticky_buffer_header,
10267                        sticky_headers,
10268                        expand_toggles,
10269                    }
10270                })
10271            })
10272        })
10273    }
10274
10275    fn paint(
10276        &mut self,
10277        _: Option<&GlobalElementId>,
10278        _inspector_id: Option<&gpui::InspectorElementId>,
10279        bounds: Bounds<gpui::Pixels>,
10280        _: &mut Self::RequestLayoutState,
10281        layout: &mut Self::PrepaintState,
10282        window: &mut Window,
10283        cx: &mut App,
10284    ) {
10285        if !layout.mode.is_minimap() {
10286            let focus_handle = self.editor.focus_handle(cx);
10287            let key_context = self
10288                .editor
10289                .update(cx, |editor, cx| editor.key_context(window, cx));
10290
10291            window.set_key_context(key_context);
10292            window.handle_input(
10293                &focus_handle,
10294                ElementInputHandler::new(bounds, self.editor.clone()),
10295                cx,
10296            );
10297            self.register_actions(window, cx);
10298            self.register_key_listeners(window, cx, layout);
10299        }
10300
10301        let text_style = TextStyleRefinement {
10302            font_size: Some(self.style.text.font_size),
10303            line_height: Some(self.style.text.line_height),
10304            ..Default::default()
10305        };
10306        let rem_size = self.rem_size(cx);
10307        window.with_rem_size(rem_size, |window| {
10308            window.with_text_style(Some(text_style), |window| {
10309                window.with_content_mask(Some(ContentMask { bounds }), |window| {
10310                    self.paint_mouse_listeners(layout, window, cx);
10311                    self.paint_background(layout, window, cx);
10312                    self.paint_indent_guides(layout, window, cx);
10313
10314                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
10315                        self.paint_blamed_display_rows(layout, window, cx);
10316                        self.paint_line_numbers(layout, window, cx);
10317                    }
10318
10319                    self.paint_text(layout, window, cx);
10320
10321                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
10322                        self.paint_gutter_highlights(layout, window, cx);
10323                        self.paint_gutter_indicators(layout, window, cx);
10324                    }
10325
10326                    if !layout.blocks.is_empty() {
10327                        window.with_element_namespace("blocks", |window| {
10328                            self.paint_blocks(layout, window, cx);
10329                        });
10330                    }
10331
10332                    window.with_element_namespace("blocks", |window| {
10333                        if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
10334                            sticky_header.paint(window, cx)
10335                        }
10336                    });
10337
10338                    self.paint_sticky_headers(layout, window, cx);
10339                    self.paint_minimap(layout, window, cx);
10340                    self.paint_scrollbars(layout, window, cx);
10341                    self.paint_edit_prediction_popover(layout, window, cx);
10342                    self.paint_mouse_context_menu(layout, window, cx);
10343                });
10344            })
10345        })
10346    }
10347}
10348
10349pub(super) fn gutter_bounds(
10350    editor_bounds: Bounds<Pixels>,
10351    gutter_dimensions: GutterDimensions,
10352) -> Bounds<Pixels> {
10353    Bounds {
10354        origin: editor_bounds.origin,
10355        size: size(gutter_dimensions.width, editor_bounds.size.height),
10356    }
10357}
10358
10359#[derive(Clone, Copy)]
10360struct ContextMenuLayout {
10361    y_flipped: bool,
10362    bounds: Bounds<Pixels>,
10363}
10364
10365/// Holds information required for layouting the editor scrollbars.
10366struct ScrollbarLayoutInformation {
10367    /// The bounds of the editor area (excluding the content offset).
10368    editor_bounds: Bounds<Pixels>,
10369    /// The available range to scroll within the document.
10370    scroll_range: Size<Pixels>,
10371    /// The space available for one glyph in the editor.
10372    glyph_grid_cell: Size<Pixels>,
10373}
10374
10375impl ScrollbarLayoutInformation {
10376    pub fn new(
10377        editor_bounds: Bounds<Pixels>,
10378        glyph_grid_cell: Size<Pixels>,
10379        document_size: Size<Pixels>,
10380        longest_line_blame_width: Pixels,
10381        settings: &EditorSettings,
10382    ) -> Self {
10383        let vertical_overscroll = match settings.scroll_beyond_last_line {
10384            ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
10385            ScrollBeyondLastLine::Off => glyph_grid_cell.height,
10386            ScrollBeyondLastLine::VerticalScrollMargin => {
10387                (1.0 + settings.vertical_scroll_margin) as f32 * glyph_grid_cell.height
10388            }
10389        };
10390
10391        let overscroll = size(longest_line_blame_width, vertical_overscroll);
10392
10393        ScrollbarLayoutInformation {
10394            editor_bounds,
10395            scroll_range: document_size + overscroll,
10396            glyph_grid_cell,
10397        }
10398    }
10399}
10400
10401impl IntoElement for EditorElement {
10402    type Element = Self;
10403
10404    fn into_element(self) -> Self::Element {
10405        self
10406    }
10407}
10408
10409pub struct EditorLayout {
10410    position_map: Rc<PositionMap>,
10411    hitbox: Hitbox,
10412    gutter_hitbox: Hitbox,
10413    content_origin: gpui::Point<Pixels>,
10414    scrollbars_layout: Option<EditorScrollbars>,
10415    minimap: Option<MinimapLayout>,
10416    mode: EditorMode,
10417    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
10418    indent_guides: Option<Vec<IndentGuideLayout>>,
10419    visible_display_row_range: Range<DisplayRow>,
10420    active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
10421    highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
10422    line_elements: SmallVec<[AnyElement; 1]>,
10423    line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
10424    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
10425    blamed_display_rows: Option<Vec<AnyElement>>,
10426    inline_diagnostics: HashMap<DisplayRow, AnyElement>,
10427    inline_blame_layout: Option<InlineBlameLayout>,
10428    inline_code_actions: Option<AnyElement>,
10429    blocks: Vec<BlockLayout>,
10430    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
10431    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
10432    redacted_ranges: Vec<Range<DisplayPoint>>,
10433    cursors: Vec<(DisplayPoint, Hsla)>,
10434    visible_cursors: Vec<CursorLayout>,
10435    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
10436    test_indicators: Vec<AnyElement>,
10437    breakpoints: Vec<AnyElement>,
10438    crease_toggles: Vec<Option<AnyElement>>,
10439    expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
10440    diff_hunk_controls: Vec<AnyElement>,
10441    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
10442    edit_prediction_popover: Option<AnyElement>,
10443    mouse_context_menu: Option<AnyElement>,
10444    tab_invisible: ShapedLine,
10445    space_invisible: ShapedLine,
10446    sticky_buffer_header: Option<AnyElement>,
10447    sticky_headers: Option<StickyHeaders>,
10448    document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
10449}
10450
10451struct StickyHeaders {
10452    lines: Vec<StickyHeaderLine>,
10453    gutter_background: Hsla,
10454    content_background: Hsla,
10455    gutter_right_padding: Pixels,
10456}
10457
10458struct StickyHeaderLine {
10459    row: DisplayRow,
10460    offset: Pixels,
10461    line: LineWithInvisibles,
10462    line_number: Option<ShapedLine>,
10463    elements: SmallVec<[AnyElement; 1]>,
10464    available_text_width: Pixels,
10465    target_anchor: Anchor,
10466    hitbox: Hitbox,
10467}
10468
10469impl EditorLayout {
10470    fn line_end_overshoot(&self) -> Pixels {
10471        0.15 * self.position_map.line_height
10472    }
10473}
10474
10475impl StickyHeaders {
10476    fn paint(
10477        &mut self,
10478        layout: &mut EditorLayout,
10479        whitespace_setting: ShowWhitespaceSetting,
10480        window: &mut Window,
10481        cx: &mut App,
10482    ) {
10483        let line_height = layout.position_map.line_height;
10484
10485        for line in self.lines.iter_mut().rev() {
10486            window.paint_layer(
10487                Bounds::new(
10488                    layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
10489                    size(line.hitbox.size.width, line_height),
10490                ),
10491                |window| {
10492                    let gutter_bounds = Bounds::new(
10493                        layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
10494                        size(layout.gutter_hitbox.size.width, line_height),
10495                    );
10496                    window.paint_quad(fill(gutter_bounds, self.gutter_background));
10497
10498                    let text_bounds = Bounds::new(
10499                        layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset),
10500                        size(line.available_text_width, line_height),
10501                    );
10502                    window.paint_quad(fill(text_bounds, self.content_background));
10503
10504                    if line.hitbox.is_hovered(window) {
10505                        let hover_overlay = cx.theme().colors().panel_overlay_hover;
10506                        window.paint_quad(fill(gutter_bounds, hover_overlay));
10507                        window.paint_quad(fill(text_bounds, hover_overlay));
10508                    }
10509
10510                    line.paint(
10511                        layout,
10512                        self.gutter_right_padding,
10513                        line.available_text_width,
10514                        layout.content_origin,
10515                        line_height,
10516                        whitespace_setting,
10517                        window,
10518                        cx,
10519                    );
10520                },
10521            );
10522
10523            window.set_cursor_style(CursorStyle::PointingHand, &line.hitbox);
10524        }
10525    }
10526}
10527
10528impl StickyHeaderLine {
10529    fn new(
10530        row: DisplayRow,
10531        offset: Pixels,
10532        mut line: LineWithInvisibles,
10533        line_number: Option<ShapedLine>,
10534        target_anchor: Anchor,
10535        line_height: Pixels,
10536        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
10537        content_origin: gpui::Point<Pixels>,
10538        gutter_hitbox: &Hitbox,
10539        text_hitbox: &Hitbox,
10540        window: &mut Window,
10541        cx: &mut App,
10542    ) -> Self {
10543        let mut elements = SmallVec::<[AnyElement; 1]>::new();
10544        line.prepaint_with_custom_offset(
10545            line_height,
10546            scroll_pixel_position,
10547            content_origin,
10548            offset,
10549            &mut elements,
10550            window,
10551            cx,
10552        );
10553
10554        let hitbox_bounds = Bounds::new(
10555            gutter_hitbox.origin + point(Pixels::ZERO, offset),
10556            size(text_hitbox.right() - gutter_hitbox.left(), line_height),
10557        );
10558        let available_text_width =
10559            (hitbox_bounds.size.width - gutter_hitbox.size.width).max(Pixels::ZERO);
10560
10561        Self {
10562            row,
10563            offset,
10564            line,
10565            line_number,
10566            elements,
10567            available_text_width,
10568            target_anchor,
10569            hitbox: window.insert_hitbox(hitbox_bounds, HitboxBehavior::BlockMouseExceptScroll),
10570        }
10571    }
10572
10573    fn paint(
10574        &mut self,
10575        layout: &EditorLayout,
10576        gutter_right_padding: Pixels,
10577        available_text_width: Pixels,
10578        content_origin: gpui::Point<Pixels>,
10579        line_height: Pixels,
10580        whitespace_setting: ShowWhitespaceSetting,
10581        window: &mut Window,
10582        cx: &mut App,
10583    ) {
10584        window.with_content_mask(
10585            Some(ContentMask {
10586                bounds: Bounds::new(
10587                    layout.position_map.text_hitbox.bounds.origin
10588                        + point(Pixels::ZERO, self.offset),
10589                    size(available_text_width, line_height),
10590                ),
10591            }),
10592            |window| {
10593                self.line.draw_with_custom_offset(
10594                    layout,
10595                    self.row,
10596                    content_origin,
10597                    self.offset,
10598                    whitespace_setting,
10599                    &[],
10600                    window,
10601                    cx,
10602                );
10603                for element in &mut self.elements {
10604                    element.paint(window, cx);
10605                }
10606            },
10607        );
10608
10609        if let Some(line_number) = &self.line_number {
10610            let gutter_origin = layout.gutter_hitbox.origin + point(Pixels::ZERO, self.offset);
10611            let gutter_width = layout.gutter_hitbox.size.width;
10612            let origin = point(
10613                gutter_origin.x + gutter_width - gutter_right_padding - line_number.width,
10614                gutter_origin.y,
10615            );
10616            line_number.paint(origin, line_height, window, cx).log_err();
10617        }
10618    }
10619}
10620
10621#[derive(Debug)]
10622struct LineNumberSegment {
10623    shaped_line: ShapedLine,
10624    hitbox: Option<Hitbox>,
10625}
10626
10627#[derive(Debug)]
10628struct LineNumberLayout {
10629    segments: SmallVec<[LineNumberSegment; 1]>,
10630}
10631
10632struct ColoredRange<T> {
10633    start: T,
10634    end: T,
10635    color: Hsla,
10636}
10637
10638impl Along for ScrollbarAxes {
10639    type Unit = bool;
10640
10641    fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
10642        match axis {
10643            ScrollbarAxis::Horizontal => self.horizontal,
10644            ScrollbarAxis::Vertical => self.vertical,
10645        }
10646    }
10647
10648    fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
10649        match axis {
10650            ScrollbarAxis::Horizontal => ScrollbarAxes {
10651                horizontal: f(self.horizontal),
10652                vertical: self.vertical,
10653            },
10654            ScrollbarAxis::Vertical => ScrollbarAxes {
10655                horizontal: self.horizontal,
10656                vertical: f(self.vertical),
10657            },
10658        }
10659    }
10660}
10661
10662#[derive(Clone)]
10663struct EditorScrollbars {
10664    pub vertical: Option<ScrollbarLayout>,
10665    pub horizontal: Option<ScrollbarLayout>,
10666    pub visible: bool,
10667}
10668
10669impl EditorScrollbars {
10670    pub fn from_scrollbar_axes(
10671        show_scrollbar: ScrollbarAxes,
10672        layout_information: &ScrollbarLayoutInformation,
10673        content_offset: gpui::Point<Pixels>,
10674        scroll_position: gpui::Point<f64>,
10675        scrollbar_width: Pixels,
10676        right_margin: Pixels,
10677        editor_width: Pixels,
10678        show_scrollbars: bool,
10679        scrollbar_state: Option<&ActiveScrollbarState>,
10680        window: &mut Window,
10681    ) -> Self {
10682        let ScrollbarLayoutInformation {
10683            editor_bounds,
10684            scroll_range,
10685            glyph_grid_cell,
10686        } = layout_information;
10687
10688        let viewport_size = size(editor_width, editor_bounds.size.height);
10689
10690        let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
10691            ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
10692                Corner::BottomLeft,
10693                editor_bounds.bottom_left(),
10694                size(
10695                    // The horizontal viewport size differs from the space available for the
10696                    // horizontal scrollbar, so we have to manually stitch it together here.
10697                    editor_bounds.size.width - right_margin,
10698                    scrollbar_width,
10699                ),
10700            ),
10701            ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
10702                Corner::TopRight,
10703                editor_bounds.top_right(),
10704                size(scrollbar_width, viewport_size.height),
10705            ),
10706        };
10707
10708        let mut create_scrollbar_layout = |axis| {
10709            let viewport_size = viewport_size.along(axis);
10710            let scroll_range = scroll_range.along(axis);
10711
10712            // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
10713            (show_scrollbar.along(axis)
10714                && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
10715                .then(|| {
10716                    ScrollbarLayout::new(
10717                        window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
10718                        viewport_size,
10719                        scroll_range,
10720                        glyph_grid_cell.along(axis),
10721                        content_offset.along(axis),
10722                        scroll_position.along(axis),
10723                        show_scrollbars,
10724                        axis,
10725                    )
10726                    .with_thumb_state(
10727                        scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
10728                    )
10729                })
10730        };
10731
10732        Self {
10733            vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
10734            horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
10735            visible: show_scrollbars,
10736        }
10737    }
10738
10739    pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
10740        [
10741            (&self.vertical, ScrollbarAxis::Vertical),
10742            (&self.horizontal, ScrollbarAxis::Horizontal),
10743        ]
10744        .into_iter()
10745        .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
10746    }
10747
10748    /// Returns the currently hovered scrollbar axis, if any.
10749    pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
10750        self.iter_scrollbars()
10751            .find(|s| s.0.hitbox.is_hovered(window))
10752    }
10753}
10754
10755#[derive(Clone)]
10756struct ScrollbarLayout {
10757    hitbox: Hitbox,
10758    visible_range: Range<ScrollOffset>,
10759    text_unit_size: Pixels,
10760    thumb_bounds: Option<Bounds<Pixels>>,
10761    thumb_state: ScrollbarThumbState,
10762}
10763
10764impl ScrollbarLayout {
10765    const BORDER_WIDTH: Pixels = px(1.0);
10766    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
10767    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
10768    const MIN_THUMB_SIZE: Pixels = px(25.0);
10769
10770    fn new(
10771        scrollbar_track_hitbox: Hitbox,
10772        viewport_size: Pixels,
10773        scroll_range: Pixels,
10774        glyph_space: Pixels,
10775        content_offset: Pixels,
10776        scroll_position: ScrollOffset,
10777        show_thumb: bool,
10778        axis: ScrollbarAxis,
10779    ) -> Self {
10780        let track_bounds = scrollbar_track_hitbox.bounds;
10781        // The length of the track available to the scrollbar thumb. We deliberately
10782        // exclude the content size here so that the thumb aligns with the content.
10783        let track_length = track_bounds.size.along(axis) - content_offset;
10784
10785        Self::new_with_hitbox_and_track_length(
10786            scrollbar_track_hitbox,
10787            track_length,
10788            viewport_size,
10789            scroll_range.into(),
10790            glyph_space,
10791            content_offset.into(),
10792            scroll_position,
10793            show_thumb,
10794            axis,
10795        )
10796    }
10797
10798    fn for_minimap(
10799        minimap_track_hitbox: Hitbox,
10800        visible_lines: f64,
10801        total_editor_lines: f64,
10802        minimap_line_height: Pixels,
10803        scroll_position: ScrollOffset,
10804        minimap_scroll_top: ScrollOffset,
10805        show_thumb: bool,
10806    ) -> Self {
10807        // The scrollbar thumb size is calculated as
10808        // (visible_content/total_content) Γ— scrollbar_track_length.
10809        //
10810        // For the minimap's thumb layout, we leverage this by setting the
10811        // scrollbar track length to the entire document size (using minimap line
10812        // height). This creates a thumb that exactly represents the editor
10813        // viewport scaled to minimap proportions.
10814        //
10815        // We adjust the thumb position relative to `minimap_scroll_top` to
10816        // accommodate for the deliberately oversized track.
10817        //
10818        // This approach ensures that the minimap thumb accurately reflects the
10819        // editor's current scroll position whilst nicely synchronizing the minimap
10820        // thumb and scrollbar thumb.
10821        let scroll_range = total_editor_lines * f64::from(minimap_line_height);
10822        let viewport_size = visible_lines * f64::from(minimap_line_height);
10823
10824        let track_top_offset = -minimap_scroll_top * f64::from(minimap_line_height);
10825
10826        Self::new_with_hitbox_and_track_length(
10827            minimap_track_hitbox,
10828            Pixels::from(scroll_range),
10829            Pixels::from(viewport_size),
10830            scroll_range,
10831            minimap_line_height,
10832            track_top_offset,
10833            scroll_position,
10834            show_thumb,
10835            ScrollbarAxis::Vertical,
10836        )
10837    }
10838
10839    fn new_with_hitbox_and_track_length(
10840        scrollbar_track_hitbox: Hitbox,
10841        track_length: Pixels,
10842        viewport_size: Pixels,
10843        scroll_range: f64,
10844        glyph_space: Pixels,
10845        content_offset: ScrollOffset,
10846        scroll_position: ScrollOffset,
10847        show_thumb: bool,
10848        axis: ScrollbarAxis,
10849    ) -> Self {
10850        let text_units_per_page = viewport_size.to_f64() / glyph_space.to_f64();
10851        let visible_range = scroll_position..scroll_position + text_units_per_page;
10852        let total_text_units = scroll_range / glyph_space.to_f64();
10853
10854        let thumb_percentage = text_units_per_page / total_text_units;
10855        let thumb_size = Pixels::from(ScrollOffset::from(track_length) * thumb_percentage)
10856            .max(ScrollbarLayout::MIN_THUMB_SIZE)
10857            .min(track_length);
10858
10859        let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
10860
10861        let content_larger_than_viewport = text_unit_divisor > 0.;
10862
10863        let text_unit_size = if content_larger_than_viewport {
10864            Pixels::from(ScrollOffset::from(track_length - thumb_size) / text_unit_divisor)
10865        } else {
10866            glyph_space
10867        };
10868
10869        let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
10870            Self::thumb_bounds(
10871                &scrollbar_track_hitbox,
10872                content_offset,
10873                visible_range.start,
10874                text_unit_size,
10875                thumb_size,
10876                axis,
10877            )
10878        });
10879
10880        ScrollbarLayout {
10881            hitbox: scrollbar_track_hitbox,
10882            visible_range,
10883            text_unit_size,
10884            thumb_bounds,
10885            thumb_state: Default::default(),
10886        }
10887    }
10888
10889    fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
10890        if let Some(thumb_state) = thumb_state {
10891            Self {
10892                thumb_state,
10893                ..self
10894            }
10895        } else {
10896            self
10897        }
10898    }
10899
10900    fn thumb_bounds(
10901        scrollbar_track: &Hitbox,
10902        content_offset: f64,
10903        visible_range_start: f64,
10904        text_unit_size: Pixels,
10905        thumb_size: Pixels,
10906        axis: ScrollbarAxis,
10907    ) -> Bounds<Pixels> {
10908        let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
10909            origin
10910                + Pixels::from(
10911                    content_offset + visible_range_start * ScrollOffset::from(text_unit_size),
10912                )
10913        });
10914        Bounds::new(
10915            thumb_origin,
10916            scrollbar_track.size.apply_along(axis, |_| thumb_size),
10917        )
10918    }
10919
10920    fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
10921        self.thumb_bounds
10922            .is_some_and(|bounds| bounds.contains(position))
10923    }
10924
10925    fn marker_quads_for_ranges(
10926        &self,
10927        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
10928        column: Option<usize>,
10929    ) -> Vec<PaintQuad> {
10930        struct MinMax {
10931            min: Pixels,
10932            max: Pixels,
10933        }
10934        let (x_range, height_limit) = if let Some(column) = column {
10935            let column_width = ((self.hitbox.size.width - Self::BORDER_WIDTH) / 3.0).floor();
10936            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
10937            let end = start + column_width;
10938            (
10939                Range { start, end },
10940                MinMax {
10941                    min: Self::MIN_MARKER_HEIGHT,
10942                    max: px(f32::MAX),
10943                },
10944            )
10945        } else {
10946            (
10947                Range {
10948                    start: Self::BORDER_WIDTH,
10949                    end: self.hitbox.size.width,
10950                },
10951                MinMax {
10952                    min: Self::LINE_MARKER_HEIGHT,
10953                    max: Self::LINE_MARKER_HEIGHT,
10954                },
10955            )
10956        };
10957
10958        let row_to_y = |row: DisplayRow| row.as_f64() as f32 * self.text_unit_size;
10959        let mut pixel_ranges = row_ranges
10960            .into_iter()
10961            .map(|range| {
10962                let start_y = row_to_y(range.start);
10963                let end_y = row_to_y(range.end)
10964                    + self
10965                        .text_unit_size
10966                        .max(height_limit.min)
10967                        .min(height_limit.max);
10968                ColoredRange {
10969                    start: start_y,
10970                    end: end_y,
10971                    color: range.color,
10972                }
10973            })
10974            .peekable();
10975
10976        let mut quads = Vec::new();
10977        while let Some(mut pixel_range) = pixel_ranges.next() {
10978            while let Some(next_pixel_range) = pixel_ranges.peek() {
10979                if pixel_range.end >= next_pixel_range.start - px(1.0)
10980                    && pixel_range.color == next_pixel_range.color
10981                {
10982                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
10983                    pixel_ranges.next();
10984                } else {
10985                    break;
10986                }
10987            }
10988
10989            let bounds = Bounds::from_corners(
10990                point(x_range.start, pixel_range.start),
10991                point(x_range.end, pixel_range.end),
10992            );
10993            quads.push(quad(
10994                bounds,
10995                Corners::default(),
10996                pixel_range.color,
10997                Edges::default(),
10998                Hsla::transparent_black(),
10999                BorderStyle::default(),
11000            ));
11001        }
11002
11003        quads
11004    }
11005}
11006
11007struct MinimapLayout {
11008    pub minimap: AnyElement,
11009    pub thumb_layout: ScrollbarLayout,
11010    pub minimap_scroll_top: ScrollOffset,
11011    pub minimap_line_height: Pixels,
11012    pub thumb_border_style: MinimapThumbBorder,
11013    pub max_scroll_top: ScrollOffset,
11014}
11015
11016impl MinimapLayout {
11017    /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
11018    const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
11019    /// The minimap width as a percentage of the editor width.
11020    const MINIMAP_WIDTH_PCT: f32 = 0.15;
11021    /// Calculates the scroll top offset the minimap editor has to have based on the
11022    /// current scroll progress.
11023    fn calculate_minimap_top_offset(
11024        document_lines: f64,
11025        visible_editor_lines: f64,
11026        visible_minimap_lines: f64,
11027        scroll_position: f64,
11028    ) -> ScrollOffset {
11029        let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
11030        if non_visible_document_lines == 0. {
11031            0.
11032        } else {
11033            let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
11034            scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
11035        }
11036    }
11037}
11038
11039struct CreaseTrailerLayout {
11040    element: AnyElement,
11041    bounds: Bounds<Pixels>,
11042}
11043
11044pub(crate) struct PositionMap {
11045    pub size: Size<Pixels>,
11046    pub line_height: Pixels,
11047    pub scroll_position: gpui::Point<ScrollOffset>,
11048    pub scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11049    pub scroll_max: gpui::Point<ScrollOffset>,
11050    pub em_width: Pixels,
11051    pub em_advance: Pixels,
11052    pub visible_row_range: Range<DisplayRow>,
11053    pub line_layouts: Vec<LineWithInvisibles>,
11054    pub snapshot: EditorSnapshot,
11055    pub text_hitbox: Hitbox,
11056    pub gutter_hitbox: Hitbox,
11057    pub inline_blame_bounds: Option<(Bounds<Pixels>, BufferId, BlameEntry)>,
11058    pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
11059    pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
11060}
11061
11062#[derive(Debug, Copy, Clone)]
11063pub struct PointForPosition {
11064    pub previous_valid: DisplayPoint,
11065    pub next_valid: DisplayPoint,
11066    pub exact_unclipped: DisplayPoint,
11067    pub column_overshoot_after_line_end: u32,
11068}
11069
11070impl PointForPosition {
11071    pub fn as_valid(&self) -> Option<DisplayPoint> {
11072        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
11073            Some(self.previous_valid)
11074        } else {
11075            None
11076        }
11077    }
11078
11079    pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
11080        let Some(valid_point) = self.as_valid() else {
11081            return false;
11082        };
11083        let range = selection.range();
11084
11085        let candidate_row = valid_point.row();
11086        let candidate_col = valid_point.column();
11087
11088        let start_row = range.start.row();
11089        let start_col = range.start.column();
11090        let end_row = range.end.row();
11091        let end_col = range.end.column();
11092
11093        if candidate_row < start_row || candidate_row > end_row {
11094            false
11095        } else if start_row == end_row {
11096            candidate_col >= start_col && candidate_col < end_col
11097        } else if candidate_row == start_row {
11098            candidate_col >= start_col
11099        } else if candidate_row == end_row {
11100            candidate_col < end_col
11101        } else {
11102            true
11103        }
11104    }
11105}
11106
11107impl PositionMap {
11108    pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
11109        let text_bounds = self.text_hitbox.bounds;
11110        let scroll_position = self.snapshot.scroll_position();
11111        let position = position - text_bounds.origin;
11112        let y = position.y.max(px(0.)).min(self.size.height);
11113        let x = position.x + (scroll_position.x as f32 * self.em_advance);
11114        let row = ((y / self.line_height) as f64 + scroll_position.y) as u32;
11115
11116        let (column, x_overshoot_after_line_end) = if let Some(line) = self
11117            .line_layouts
11118            .get(row as usize - scroll_position.y as usize)
11119        {
11120            if let Some(ix) = line.index_for_x(x) {
11121                (ix as u32, px(0.))
11122            } else {
11123                (line.len as u32, px(0.).max(x - line.width))
11124            }
11125        } else {
11126            (0, x)
11127        };
11128
11129        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
11130        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
11131        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
11132
11133        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
11134        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
11135        PointForPosition {
11136            previous_valid,
11137            next_valid,
11138            exact_unclipped,
11139            column_overshoot_after_line_end,
11140        }
11141    }
11142}
11143
11144struct BlockLayout {
11145    id: BlockId,
11146    x_offset: Pixels,
11147    row: Option<DisplayRow>,
11148    element: AnyElement,
11149    available_space: Size<AvailableSpace>,
11150    style: BlockStyle,
11151    overlaps_gutter: bool,
11152    is_buffer_header: bool,
11153}
11154
11155pub fn layout_line(
11156    row: DisplayRow,
11157    snapshot: &EditorSnapshot,
11158    style: &EditorStyle,
11159    text_width: Pixels,
11160    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
11161    window: &mut Window,
11162    cx: &mut App,
11163) -> LineWithInvisibles {
11164    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
11165    LineWithInvisibles::from_chunks(
11166        chunks,
11167        style,
11168        MAX_LINE_LEN,
11169        1,
11170        &snapshot.mode,
11171        text_width,
11172        is_row_soft_wrapped,
11173        &[],
11174        window,
11175        cx,
11176    )
11177    .pop()
11178    .unwrap()
11179}
11180
11181#[derive(Debug)]
11182pub struct IndentGuideLayout {
11183    origin: gpui::Point<Pixels>,
11184    length: Pixels,
11185    single_indent_width: Pixels,
11186    depth: u32,
11187    active: bool,
11188    settings: IndentGuideSettings,
11189}
11190
11191pub struct CursorLayout {
11192    origin: gpui::Point<Pixels>,
11193    block_width: Pixels,
11194    line_height: Pixels,
11195    color: Hsla,
11196    shape: CursorShape,
11197    block_text: Option<ShapedLine>,
11198    cursor_name: Option<AnyElement>,
11199}
11200
11201#[derive(Debug)]
11202pub struct CursorName {
11203    string: SharedString,
11204    color: Hsla,
11205    is_top_row: bool,
11206}
11207
11208impl CursorLayout {
11209    pub fn new(
11210        origin: gpui::Point<Pixels>,
11211        block_width: Pixels,
11212        line_height: Pixels,
11213        color: Hsla,
11214        shape: CursorShape,
11215        block_text: Option<ShapedLine>,
11216    ) -> CursorLayout {
11217        CursorLayout {
11218            origin,
11219            block_width,
11220            line_height,
11221            color,
11222            shape,
11223            block_text,
11224            cursor_name: None,
11225        }
11226    }
11227
11228    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
11229        Bounds {
11230            origin: self.origin + origin,
11231            size: size(self.block_width, self.line_height),
11232        }
11233    }
11234
11235    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
11236        match self.shape {
11237            CursorShape::Bar => Bounds {
11238                origin: self.origin + origin,
11239                size: size(px(2.0), self.line_height),
11240            },
11241            CursorShape::Block | CursorShape::Hollow => Bounds {
11242                origin: self.origin + origin,
11243                size: size(self.block_width, self.line_height),
11244            },
11245            CursorShape::Underline => Bounds {
11246                origin: self.origin
11247                    + origin
11248                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
11249                size: size(self.block_width, px(2.0)),
11250            },
11251        }
11252    }
11253
11254    pub fn layout(
11255        &mut self,
11256        origin: gpui::Point<Pixels>,
11257        cursor_name: Option<CursorName>,
11258        window: &mut Window,
11259        cx: &mut App,
11260    ) {
11261        if let Some(cursor_name) = cursor_name {
11262            let bounds = self.bounds(origin);
11263            let text_size = self.line_height / 1.5;
11264
11265            let name_origin = if cursor_name.is_top_row {
11266                point(bounds.right() - px(1.), bounds.top())
11267            } else {
11268                match self.shape {
11269                    CursorShape::Bar => point(
11270                        bounds.right() - px(2.),
11271                        bounds.top() - text_size / 2. - px(1.),
11272                    ),
11273                    _ => point(
11274                        bounds.right() - px(1.),
11275                        bounds.top() - text_size / 2. - px(1.),
11276                    ),
11277                }
11278            };
11279            let mut name_element = div()
11280                .bg(self.color)
11281                .text_size(text_size)
11282                .px_0p5()
11283                .line_height(text_size + px(2.))
11284                .text_color(cursor_name.color)
11285                .child(cursor_name.string)
11286                .into_any_element();
11287
11288            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
11289
11290            self.cursor_name = Some(name_element);
11291        }
11292    }
11293
11294    pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
11295        let bounds = self.bounds(origin);
11296
11297        //Draw background or border quad
11298        let cursor = if matches!(self.shape, CursorShape::Hollow) {
11299            outline(bounds, self.color, BorderStyle::Solid)
11300        } else {
11301            fill(bounds, self.color)
11302        };
11303
11304        if let Some(name) = &mut self.cursor_name {
11305            name.paint(window, cx);
11306        }
11307
11308        window.paint_quad(cursor);
11309
11310        if let Some(block_text) = &self.block_text {
11311            block_text
11312                .paint(self.origin + origin, self.line_height, window, cx)
11313                .log_err();
11314        }
11315    }
11316
11317    pub fn shape(&self) -> CursorShape {
11318        self.shape
11319    }
11320}
11321
11322#[derive(Debug)]
11323pub struct HighlightedRange {
11324    pub start_y: Pixels,
11325    pub line_height: Pixels,
11326    pub lines: Vec<HighlightedRangeLine>,
11327    pub color: Hsla,
11328    pub corner_radius: Pixels,
11329}
11330
11331#[derive(Debug)]
11332pub struct HighlightedRangeLine {
11333    pub start_x: Pixels,
11334    pub end_x: Pixels,
11335}
11336
11337impl HighlightedRange {
11338    pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
11339        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
11340            self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
11341            self.paint_lines(
11342                self.start_y + self.line_height,
11343                &self.lines[1..],
11344                fill,
11345                bounds,
11346                window,
11347            );
11348        } else {
11349            self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
11350        }
11351    }
11352
11353    fn paint_lines(
11354        &self,
11355        start_y: Pixels,
11356        lines: &[HighlightedRangeLine],
11357        fill: bool,
11358        _bounds: Bounds<Pixels>,
11359        window: &mut Window,
11360    ) {
11361        if lines.is_empty() {
11362            return;
11363        }
11364
11365        let first_line = lines.first().unwrap();
11366        let last_line = lines.last().unwrap();
11367
11368        let first_top_left = point(first_line.start_x, start_y);
11369        let first_top_right = point(first_line.end_x, start_y);
11370
11371        let curve_height = point(Pixels::ZERO, self.corner_radius);
11372        let curve_width = |start_x: Pixels, end_x: Pixels| {
11373            let max = (end_x - start_x) / 2.;
11374            let width = if max < self.corner_radius {
11375                max
11376            } else {
11377                self.corner_radius
11378            };
11379
11380            point(width, Pixels::ZERO)
11381        };
11382
11383        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
11384        let mut builder = if fill {
11385            gpui::PathBuilder::fill()
11386        } else {
11387            gpui::PathBuilder::stroke(px(1.))
11388        };
11389        builder.move_to(first_top_right - top_curve_width);
11390        builder.curve_to(first_top_right + curve_height, first_top_right);
11391
11392        let mut iter = lines.iter().enumerate().peekable();
11393        while let Some((ix, line)) = iter.next() {
11394            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
11395
11396            if let Some((_, next_line)) = iter.peek() {
11397                let next_top_right = point(next_line.end_x, bottom_right.y);
11398
11399                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
11400                    Ordering::Equal => {
11401                        builder.line_to(bottom_right);
11402                    }
11403                    Ordering::Less => {
11404                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
11405                        builder.line_to(bottom_right - curve_height);
11406                        if self.corner_radius > Pixels::ZERO {
11407                            builder.curve_to(bottom_right - curve_width, bottom_right);
11408                        }
11409                        builder.line_to(next_top_right + curve_width);
11410                        if self.corner_radius > Pixels::ZERO {
11411                            builder.curve_to(next_top_right + curve_height, next_top_right);
11412                        }
11413                    }
11414                    Ordering::Greater => {
11415                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
11416                        builder.line_to(bottom_right - curve_height);
11417                        if self.corner_radius > Pixels::ZERO {
11418                            builder.curve_to(bottom_right + curve_width, bottom_right);
11419                        }
11420                        builder.line_to(next_top_right - curve_width);
11421                        if self.corner_radius > Pixels::ZERO {
11422                            builder.curve_to(next_top_right + curve_height, next_top_right);
11423                        }
11424                    }
11425                }
11426            } else {
11427                let curve_width = curve_width(line.start_x, line.end_x);
11428                builder.line_to(bottom_right - curve_height);
11429                if self.corner_radius > Pixels::ZERO {
11430                    builder.curve_to(bottom_right - curve_width, bottom_right);
11431                }
11432
11433                let bottom_left = point(line.start_x, bottom_right.y);
11434                builder.line_to(bottom_left + curve_width);
11435                if self.corner_radius > Pixels::ZERO {
11436                    builder.curve_to(bottom_left - curve_height, bottom_left);
11437                }
11438            }
11439        }
11440
11441        if first_line.start_x > last_line.start_x {
11442            let curve_width = curve_width(last_line.start_x, first_line.start_x);
11443            let second_top_left = point(last_line.start_x, start_y + self.line_height);
11444            builder.line_to(second_top_left + curve_height);
11445            if self.corner_radius > Pixels::ZERO {
11446                builder.curve_to(second_top_left + curve_width, second_top_left);
11447            }
11448            let first_bottom_left = point(first_line.start_x, second_top_left.y);
11449            builder.line_to(first_bottom_left - curve_width);
11450            if self.corner_radius > Pixels::ZERO {
11451                builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
11452            }
11453        }
11454
11455        builder.line_to(first_top_left + curve_height);
11456        if self.corner_radius > Pixels::ZERO {
11457            builder.curve_to(first_top_left + top_curve_width, first_top_left);
11458        }
11459        builder.line_to(first_top_right - top_curve_width);
11460
11461        if let Ok(path) = builder.build() {
11462            window.paint_path(path, self.color);
11463        }
11464    }
11465}
11466
11467pub(crate) struct StickyHeader {
11468    pub item: language::OutlineItem<Anchor>,
11469    pub sticky_row: DisplayRow,
11470    pub start_point: Point,
11471    pub offset: ScrollOffset,
11472}
11473
11474enum CursorPopoverType {
11475    CodeContextMenu,
11476    EditPrediction,
11477}
11478
11479pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
11480    (delta.pow(1.2) / 100.0).min(px(3.0)).into()
11481}
11482
11483fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
11484    (delta.pow(1.2) / 300.0).into()
11485}
11486
11487pub fn register_action<T: Action>(
11488    editor: &Entity<Editor>,
11489    window: &mut Window,
11490    listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
11491) {
11492    let editor = editor.clone();
11493    window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
11494        let action = action.downcast_ref().unwrap();
11495        if phase == DispatchPhase::Bubble {
11496            editor.update(cx, |editor, cx| {
11497                listener(editor, action, window, cx);
11498            })
11499        }
11500    })
11501}
11502
11503fn compute_auto_height_layout(
11504    editor: &mut Editor,
11505    min_lines: usize,
11506    max_lines: Option<usize>,
11507    known_dimensions: Size<Option<Pixels>>,
11508    available_width: AvailableSpace,
11509    window: &mut Window,
11510    cx: &mut Context<Editor>,
11511) -> Option<Size<Pixels>> {
11512    let width = known_dimensions.width.or({
11513        if let AvailableSpace::Definite(available_width) = available_width {
11514            Some(available_width)
11515        } else {
11516            None
11517        }
11518    })?;
11519    if let Some(height) = known_dimensions.height {
11520        return Some(size(width, height));
11521    }
11522
11523    let style = editor.style.as_ref().unwrap();
11524    let font_id = window.text_system().resolve_font(&style.text.font());
11525    let font_size = style.text.font_size.to_pixels(window.rem_size());
11526    let line_height = style.text.line_height_in_pixels(window.rem_size());
11527    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
11528
11529    let mut snapshot = editor.snapshot(window, cx);
11530    let gutter_dimensions = snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
11531
11532    editor.gutter_dimensions = gutter_dimensions;
11533    let text_width = width - gutter_dimensions.width;
11534    let overscroll = size(em_width, px(0.));
11535
11536    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
11537    if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None)
11538        && editor.set_wrap_width(Some(editor_width), cx)
11539    {
11540        snapshot = editor.snapshot(window, cx);
11541    }
11542
11543    let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
11544
11545    let min_height = line_height * min_lines as f32;
11546    let content_height = scroll_height.max(min_height);
11547
11548    let final_height = if let Some(max_lines) = max_lines {
11549        let max_height = line_height * max_lines as f32;
11550        content_height.min(max_height)
11551    } else {
11552        content_height
11553    };
11554
11555    Some(size(width, final_height))
11556}
11557
11558#[cfg(test)]
11559mod tests {
11560    use super::*;
11561    use crate::{
11562        Editor, MultiBuffer, SelectionEffects,
11563        display_map::{BlockPlacement, BlockProperties},
11564        editor_tests::{init_test, update_test_language_settings},
11565    };
11566    use gpui::{TestAppContext, VisualTestContext};
11567    use language::language_settings;
11568    use log::info;
11569    use std::num::NonZeroU32;
11570    use util::test::sample_text;
11571
11572    #[gpui::test]
11573    async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
11574        init_test(cx, |_| {});
11575
11576        let window = cx.add_window(|window, cx| {
11577            let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
11578            let mut editor = Editor::new(
11579                EditorMode::AutoHeight {
11580                    min_lines: 1,
11581                    max_lines: None,
11582                },
11583                buffer,
11584                None,
11585                window,
11586                cx,
11587            );
11588            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
11589            editor
11590        });
11591        let cx = &mut VisualTestContext::from_window(*window, cx);
11592        let editor = window.root(cx).unwrap();
11593        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
11594
11595        for x in 1..=100 {
11596            let (_, state) = cx.draw(
11597                Default::default(),
11598                size(px(200. + 0.13 * x as f32), px(500.)),
11599                |_, _| EditorElement::new(&editor, style.clone()),
11600            );
11601
11602            assert!(
11603                state.position_map.scroll_max.x == 0.,
11604                "Soft wrapped editor should have no horizontal scrolling!"
11605            );
11606        }
11607    }
11608
11609    #[gpui::test]
11610    async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
11611        init_test(cx, |_| {});
11612
11613        let window = cx.add_window(|window, cx| {
11614            let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
11615            let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
11616            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
11617            editor
11618        });
11619        let cx = &mut VisualTestContext::from_window(*window, cx);
11620        let editor = window.root(cx).unwrap();
11621        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
11622
11623        for x in 1..=100 {
11624            let (_, state) = cx.draw(
11625                Default::default(),
11626                size(px(200. + 0.13 * x as f32), px(500.)),
11627                |_, _| EditorElement::new(&editor, style.clone()),
11628            );
11629
11630            assert!(
11631                state.position_map.scroll_max.x == 0.,
11632                "Soft wrapped editor should have no horizontal scrolling!"
11633            );
11634        }
11635    }
11636
11637    #[gpui::test]
11638    fn test_shape_line_numbers(cx: &mut TestAppContext) {
11639        init_test(cx, |_| {});
11640        let window = cx.add_window(|window, cx| {
11641            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
11642            Editor::new(EditorMode::full(), buffer, None, window, cx)
11643        });
11644
11645        let editor = window.root(cx).unwrap();
11646        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
11647        let line_height = window
11648            .update(cx, |_, window, _| {
11649                style.text.line_height_in_pixels(window.rem_size())
11650            })
11651            .unwrap();
11652        let element = EditorElement::new(&editor, style);
11653        let snapshot = window
11654            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
11655            .unwrap();
11656
11657        let layouts = cx
11658            .update_window(*window, |_, window, cx| {
11659                element.layout_line_numbers(
11660                    None,
11661                    GutterDimensions {
11662                        left_padding: Pixels::ZERO,
11663                        right_padding: Pixels::ZERO,
11664                        width: px(30.0),
11665                        margin: Pixels::ZERO,
11666                        git_blame_entries_width: None,
11667                    },
11668                    line_height,
11669                    gpui::Point::default(),
11670                    DisplayRow(0)..DisplayRow(6),
11671                    &(0..6)
11672                        .map(|row| RowInfo {
11673                            buffer_row: Some(row),
11674                            ..Default::default()
11675                        })
11676                        .collect::<Vec<_>>(),
11677                    &BTreeMap::default(),
11678                    Some(DisplayPoint::new(DisplayRow(0), 0)),
11679                    &snapshot,
11680                    window,
11681                    cx,
11682                )
11683            })
11684            .unwrap();
11685        assert_eq!(layouts.len(), 6);
11686
11687        let relative_rows = window
11688            .update(cx, |editor, window, cx| {
11689                let snapshot = editor.snapshot(window, cx);
11690                element.calculate_relative_line_numbers(
11691                    &snapshot,
11692                    &(DisplayRow(0)..DisplayRow(6)),
11693                    Some(DisplayRow(3)),
11694                    false,
11695                )
11696            })
11697            .unwrap();
11698        assert_eq!(relative_rows[&DisplayRow(0)], 3);
11699        assert_eq!(relative_rows[&DisplayRow(1)], 2);
11700        assert_eq!(relative_rows[&DisplayRow(2)], 1);
11701        // current line has no relative number
11702        assert_eq!(relative_rows[&DisplayRow(4)], 1);
11703        assert_eq!(relative_rows[&DisplayRow(5)], 2);
11704
11705        // works if cursor is before screen
11706        let relative_rows = window
11707            .update(cx, |editor, window, cx| {
11708                let snapshot = editor.snapshot(window, cx);
11709                element.calculate_relative_line_numbers(
11710                    &snapshot,
11711                    &(DisplayRow(3)..DisplayRow(6)),
11712                    Some(DisplayRow(1)),
11713                    false,
11714                )
11715            })
11716            .unwrap();
11717        assert_eq!(relative_rows.len(), 3);
11718        assert_eq!(relative_rows[&DisplayRow(3)], 2);
11719        assert_eq!(relative_rows[&DisplayRow(4)], 3);
11720        assert_eq!(relative_rows[&DisplayRow(5)], 4);
11721
11722        // works if cursor is after screen
11723        let relative_rows = window
11724            .update(cx, |editor, window, cx| {
11725                let snapshot = editor.snapshot(window, cx);
11726                element.calculate_relative_line_numbers(
11727                    &snapshot,
11728                    &(DisplayRow(0)..DisplayRow(3)),
11729                    Some(DisplayRow(6)),
11730                    false,
11731                )
11732            })
11733            .unwrap();
11734        assert_eq!(relative_rows.len(), 3);
11735        assert_eq!(relative_rows[&DisplayRow(0)], 5);
11736        assert_eq!(relative_rows[&DisplayRow(1)], 4);
11737        assert_eq!(relative_rows[&DisplayRow(2)], 3);
11738
11739        const DELETED_LINE: u32 = 3;
11740        let layouts = cx
11741            .update_window(*window, |_, window, cx| {
11742                element.layout_line_numbers(
11743                    None,
11744                    GutterDimensions {
11745                        left_padding: Pixels::ZERO,
11746                        right_padding: Pixels::ZERO,
11747                        width: px(30.0),
11748                        margin: Pixels::ZERO,
11749                        git_blame_entries_width: None,
11750                    },
11751                    line_height,
11752                    gpui::Point::default(),
11753                    DisplayRow(0)..DisplayRow(6),
11754                    &(0..6)
11755                        .map(|row| RowInfo {
11756                            buffer_row: Some(row),
11757                            diff_status: (row == DELETED_LINE).then(|| {
11758                                DiffHunkStatus::deleted(
11759                                    buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
11760                                )
11761                            }),
11762                            ..Default::default()
11763                        })
11764                        .collect::<Vec<_>>(),
11765                    &BTreeMap::default(),
11766                    Some(DisplayPoint::new(DisplayRow(0), 0)),
11767                    &snapshot,
11768                    window,
11769                    cx,
11770                )
11771            })
11772            .unwrap();
11773        assert_eq!(layouts.len(), 5,);
11774        assert!(
11775            layouts.get(&MultiBufferRow(DELETED_LINE)).is_none(),
11776            "Deleted line should not have a line number"
11777        );
11778    }
11779
11780    #[gpui::test]
11781    fn test_shape_line_numbers_wrapping(cx: &mut TestAppContext) {
11782        init_test(cx, |_| {});
11783        let window = cx.add_window(|window, cx| {
11784            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
11785            Editor::new(EditorMode::full(), buffer, None, window, cx)
11786        });
11787
11788        update_test_language_settings(cx, |s| {
11789            s.defaults.preferred_line_length = Some(5_u32);
11790            s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
11791        });
11792
11793        let editor = window.root(cx).unwrap();
11794        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
11795        let line_height = window
11796            .update(cx, |_, window, _| {
11797                style.text.line_height_in_pixels(window.rem_size())
11798            })
11799            .unwrap();
11800        let element = EditorElement::new(&editor, style);
11801        let snapshot = window
11802            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
11803            .unwrap();
11804
11805        let layouts = cx
11806            .update_window(*window, |_, window, cx| {
11807                element.layout_line_numbers(
11808                    None,
11809                    GutterDimensions {
11810                        left_padding: Pixels::ZERO,
11811                        right_padding: Pixels::ZERO,
11812                        width: px(30.0),
11813                        margin: Pixels::ZERO,
11814                        git_blame_entries_width: None,
11815                    },
11816                    line_height,
11817                    gpui::Point::default(),
11818                    DisplayRow(0)..DisplayRow(6),
11819                    &(0..6)
11820                        .map(|row| RowInfo {
11821                            buffer_row: Some(row),
11822                            ..Default::default()
11823                        })
11824                        .collect::<Vec<_>>(),
11825                    &BTreeMap::default(),
11826                    Some(DisplayPoint::new(DisplayRow(0), 0)),
11827                    &snapshot,
11828                    window,
11829                    cx,
11830                )
11831            })
11832            .unwrap();
11833        assert_eq!(layouts.len(), 3);
11834
11835        let relative_rows = window
11836            .update(cx, |editor, window, cx| {
11837                let snapshot = editor.snapshot(window, cx);
11838                element.calculate_relative_line_numbers(
11839                    &snapshot,
11840                    &(DisplayRow(0)..DisplayRow(6)),
11841                    Some(DisplayRow(3)),
11842                    true,
11843                )
11844            })
11845            .unwrap();
11846
11847        assert_eq!(relative_rows[&DisplayRow(0)], 3);
11848        assert_eq!(relative_rows[&DisplayRow(1)], 2);
11849        assert_eq!(relative_rows[&DisplayRow(2)], 1);
11850        // current line has no relative number
11851        assert_eq!(relative_rows[&DisplayRow(4)], 1);
11852        assert_eq!(relative_rows[&DisplayRow(5)], 2);
11853
11854        let layouts = cx
11855            .update_window(*window, |_, window, cx| {
11856                element.layout_line_numbers(
11857                    None,
11858                    GutterDimensions {
11859                        left_padding: Pixels::ZERO,
11860                        right_padding: Pixels::ZERO,
11861                        width: px(30.0),
11862                        margin: Pixels::ZERO,
11863                        git_blame_entries_width: None,
11864                    },
11865                    line_height,
11866                    gpui::Point::default(),
11867                    DisplayRow(0)..DisplayRow(6),
11868                    &(0..6)
11869                        .map(|row| RowInfo {
11870                            buffer_row: Some(row),
11871                            diff_status: Some(DiffHunkStatus::deleted(
11872                                buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
11873                            )),
11874                            ..Default::default()
11875                        })
11876                        .collect::<Vec<_>>(),
11877                    &BTreeMap::from_iter([(DisplayRow(0), LineHighlightSpec::default())]),
11878                    Some(DisplayPoint::new(DisplayRow(0), 0)),
11879                    &snapshot,
11880                    window,
11881                    cx,
11882                )
11883            })
11884            .unwrap();
11885        assert!(
11886            layouts.is_empty(),
11887            "Deleted lines should have no line number"
11888        );
11889
11890        let relative_rows = window
11891            .update(cx, |editor, window, cx| {
11892                let snapshot = editor.snapshot(window, cx);
11893                element.calculate_relative_line_numbers(
11894                    &snapshot,
11895                    &(DisplayRow(0)..DisplayRow(6)),
11896                    Some(DisplayRow(3)),
11897                    true,
11898                )
11899            })
11900            .unwrap();
11901
11902        // Deleted lines should still have relative numbers
11903        assert_eq!(relative_rows[&DisplayRow(0)], 3);
11904        assert_eq!(relative_rows[&DisplayRow(1)], 2);
11905        assert_eq!(relative_rows[&DisplayRow(2)], 1);
11906        // current line, even if deleted, has no relative number
11907        assert_eq!(relative_rows[&DisplayRow(4)], 1);
11908        assert_eq!(relative_rows[&DisplayRow(5)], 2);
11909    }
11910
11911    #[gpui::test]
11912    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
11913        init_test(cx, |_| {});
11914
11915        let window = cx.add_window(|window, cx| {
11916            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
11917            Editor::new(EditorMode::full(), buffer, None, window, cx)
11918        });
11919        let cx = &mut VisualTestContext::from_window(*window, cx);
11920        let editor = window.root(cx).unwrap();
11921        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
11922
11923        window
11924            .update(cx, |editor, window, cx| {
11925                editor.cursor_offset_on_selection = true;
11926                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
11927                    s.select_ranges([
11928                        Point::new(0, 0)..Point::new(1, 0),
11929                        Point::new(3, 2)..Point::new(3, 3),
11930                        Point::new(5, 6)..Point::new(6, 0),
11931                    ]);
11932                });
11933            })
11934            .unwrap();
11935
11936        let (_, state) = cx.draw(
11937            point(px(500.), px(500.)),
11938            size(px(500.), px(500.)),
11939            |_, _| EditorElement::new(&editor, style),
11940        );
11941
11942        assert_eq!(state.selections.len(), 1);
11943        let local_selections = &state.selections[0].1;
11944        assert_eq!(local_selections.len(), 3);
11945        // moves cursor back one line
11946        assert_eq!(
11947            local_selections[0].head,
11948            DisplayPoint::new(DisplayRow(0), 6)
11949        );
11950        assert_eq!(
11951            local_selections[0].range,
11952            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
11953        );
11954
11955        // moves cursor back one column
11956        assert_eq!(
11957            local_selections[1].range,
11958            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
11959        );
11960        assert_eq!(
11961            local_selections[1].head,
11962            DisplayPoint::new(DisplayRow(3), 2)
11963        );
11964
11965        // leaves cursor on the max point
11966        assert_eq!(
11967            local_selections[2].range,
11968            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
11969        );
11970        assert_eq!(
11971            local_selections[2].head,
11972            DisplayPoint::new(DisplayRow(6), 0)
11973        );
11974
11975        // active lines does not include 1 (even though the range of the selection does)
11976        assert_eq!(
11977            state.active_rows.keys().cloned().collect::<Vec<_>>(),
11978            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
11979        );
11980    }
11981
11982    #[gpui::test]
11983    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
11984        init_test(cx, |_| {});
11985
11986        let window = cx.add_window(|window, cx| {
11987            let buffer = MultiBuffer::build_simple("", cx);
11988            Editor::new(EditorMode::full(), buffer, None, window, cx)
11989        });
11990        let cx = &mut VisualTestContext::from_window(*window, cx);
11991        let editor = window.root(cx).unwrap();
11992        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
11993        window
11994            .update(cx, |editor, window, cx| {
11995                editor.set_placeholder_text("hello", window, cx);
11996                editor.insert_blocks(
11997                    [BlockProperties {
11998                        style: BlockStyle::Fixed,
11999                        placement: BlockPlacement::Above(Anchor::min()),
12000                        height: Some(3),
12001                        render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
12002                        priority: 0,
12003                    }],
12004                    None,
12005                    cx,
12006                );
12007
12008                // Blur the editor so that it displays placeholder text.
12009                window.blur();
12010            })
12011            .unwrap();
12012
12013        let (_, state) = cx.draw(
12014            point(px(500.), px(500.)),
12015            size(px(500.), px(500.)),
12016            |_, _| EditorElement::new(&editor, style),
12017        );
12018        assert_eq!(state.position_map.line_layouts.len(), 4);
12019        assert_eq!(state.line_numbers.len(), 1);
12020        assert_eq!(
12021            state
12022                .line_numbers
12023                .get(&MultiBufferRow(0))
12024                .map(|line_number| line_number
12025                    .segments
12026                    .first()
12027                    .unwrap()
12028                    .shaped_line
12029                    .text
12030                    .as_ref()),
12031            Some("1")
12032        );
12033    }
12034
12035    #[gpui::test]
12036    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
12037        const TAB_SIZE: u32 = 4;
12038
12039        let input_text = "\t \t|\t| a b";
12040        let expected_invisibles = vec![
12041            Invisible::Tab {
12042                line_start_offset: 0,
12043                line_end_offset: TAB_SIZE as usize,
12044            },
12045            Invisible::Whitespace {
12046                line_offset: TAB_SIZE as usize,
12047            },
12048            Invisible::Tab {
12049                line_start_offset: TAB_SIZE as usize + 1,
12050                line_end_offset: TAB_SIZE as usize * 2,
12051            },
12052            Invisible::Tab {
12053                line_start_offset: TAB_SIZE as usize * 2 + 1,
12054                line_end_offset: TAB_SIZE as usize * 3,
12055            },
12056            Invisible::Whitespace {
12057                line_offset: TAB_SIZE as usize * 3 + 1,
12058            },
12059            Invisible::Whitespace {
12060                line_offset: TAB_SIZE as usize * 3 + 3,
12061            },
12062        ];
12063        assert_eq!(
12064            expected_invisibles.len(),
12065            input_text
12066                .chars()
12067                .filter(|initial_char| initial_char.is_whitespace())
12068                .count(),
12069            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
12070        );
12071
12072        for show_line_numbers in [true, false] {
12073            init_test(cx, |s| {
12074                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12075                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
12076            });
12077
12078            let actual_invisibles = collect_invisibles_from_new_editor(
12079                cx,
12080                EditorMode::full(),
12081                input_text,
12082                px(500.0),
12083                show_line_numbers,
12084            );
12085
12086            assert_eq!(expected_invisibles, actual_invisibles);
12087        }
12088    }
12089
12090    #[gpui::test]
12091    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
12092        init_test(cx, |s| {
12093            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12094            s.defaults.tab_size = NonZeroU32::new(4);
12095        });
12096
12097        for editor_mode_without_invisibles in [
12098            EditorMode::SingleLine,
12099            EditorMode::AutoHeight {
12100                min_lines: 1,
12101                max_lines: Some(100),
12102            },
12103        ] {
12104            for show_line_numbers in [true, false] {
12105                let invisibles = collect_invisibles_from_new_editor(
12106                    cx,
12107                    editor_mode_without_invisibles.clone(),
12108                    "\t\t\t| | a b",
12109                    px(500.0),
12110                    show_line_numbers,
12111                );
12112                assert!(
12113                    invisibles.is_empty(),
12114                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
12115                );
12116            }
12117        }
12118    }
12119
12120    #[gpui::test]
12121    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
12122        let tab_size = 4;
12123        let input_text = "a\tbcd     ".repeat(9);
12124        let repeated_invisibles = [
12125            Invisible::Tab {
12126                line_start_offset: 1,
12127                line_end_offset: tab_size as usize,
12128            },
12129            Invisible::Whitespace {
12130                line_offset: tab_size as usize + 3,
12131            },
12132            Invisible::Whitespace {
12133                line_offset: tab_size as usize + 4,
12134            },
12135            Invisible::Whitespace {
12136                line_offset: tab_size as usize + 5,
12137            },
12138            Invisible::Whitespace {
12139                line_offset: tab_size as usize + 6,
12140            },
12141            Invisible::Whitespace {
12142                line_offset: tab_size as usize + 7,
12143            },
12144        ];
12145        let expected_invisibles = std::iter::once(repeated_invisibles)
12146            .cycle()
12147            .take(9)
12148            .flatten()
12149            .collect::<Vec<_>>();
12150        assert_eq!(
12151            expected_invisibles.len(),
12152            input_text
12153                .chars()
12154                .filter(|initial_char| initial_char.is_whitespace())
12155                .count(),
12156            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
12157        );
12158        info!("Expected invisibles: {expected_invisibles:?}");
12159
12160        init_test(cx, |_| {});
12161
12162        // Put the same string with repeating whitespace pattern into editors of various size,
12163        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
12164        let resize_step = 10.0;
12165        let mut editor_width = 200.0;
12166        while editor_width <= 1000.0 {
12167            for show_line_numbers in [true, false] {
12168                update_test_language_settings(cx, |s| {
12169                    s.defaults.tab_size = NonZeroU32::new(tab_size);
12170                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12171                    s.defaults.preferred_line_length = Some(editor_width as u32);
12172                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
12173                });
12174
12175                let actual_invisibles = collect_invisibles_from_new_editor(
12176                    cx,
12177                    EditorMode::full(),
12178                    &input_text,
12179                    px(editor_width),
12180                    show_line_numbers,
12181                );
12182
12183                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
12184                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
12185                let mut i = 0;
12186                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
12187                    i = actual_index;
12188                    match expected_invisibles.get(i) {
12189                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
12190                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
12191                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
12192                            _ => {
12193                                panic!(
12194                                    "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
12195                                )
12196                            }
12197                        },
12198                        None => {
12199                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
12200                        }
12201                    }
12202                }
12203                let missing_expected_invisibles = &expected_invisibles[i + 1..];
12204                assert!(
12205                    missing_expected_invisibles.is_empty(),
12206                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
12207                );
12208
12209                editor_width += resize_step;
12210            }
12211        }
12212    }
12213
12214    fn collect_invisibles_from_new_editor(
12215        cx: &mut TestAppContext,
12216        editor_mode: EditorMode,
12217        input_text: &str,
12218        editor_width: Pixels,
12219        show_line_numbers: bool,
12220    ) -> Vec<Invisible> {
12221        info!(
12222            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
12223            f32::from(editor_width)
12224        );
12225        let window = cx.add_window(|window, cx| {
12226            let buffer = MultiBuffer::build_simple(input_text, cx);
12227            Editor::new(editor_mode, buffer, None, window, cx)
12228        });
12229        let cx = &mut VisualTestContext::from_window(*window, cx);
12230        let editor = window.root(cx).unwrap();
12231
12232        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12233        window
12234            .update(cx, |editor, _, cx| {
12235                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12236                editor.set_wrap_width(Some(editor_width), cx);
12237                editor.set_show_line_numbers(show_line_numbers, cx);
12238            })
12239            .unwrap();
12240        let (_, state) = cx.draw(
12241            point(px(500.), px(500.)),
12242            size(px(500.), px(500.)),
12243            |_, _| EditorElement::new(&editor, style),
12244        );
12245        state
12246            .position_map
12247            .line_layouts
12248            .iter()
12249            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
12250            .cloned()
12251            .collect()
12252    }
12253
12254    #[gpui::test]
12255    fn test_merge_overlapping_ranges() {
12256        let base_bg = Hsla::white();
12257        let color1 = Hsla {
12258            h: 0.0,
12259            s: 0.5,
12260            l: 0.5,
12261            a: 0.5,
12262        };
12263        let color2 = Hsla {
12264            h: 120.0,
12265            s: 0.5,
12266            l: 0.5,
12267            a: 0.5,
12268        };
12269
12270        let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
12271        let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
12272            v.iter()
12273                .map(|(r, _)| (r.start.column(), r.end.column()))
12274                .collect()
12275        };
12276
12277        // Test overlapping ranges blend colors
12278        let overlapping = vec![
12279            (display_point(5)..display_point(15), color1),
12280            (display_point(10)..display_point(20), color2),
12281        ];
12282        let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
12283        assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
12284
12285        // Test middle segment should have blended color
12286        let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
12287        assert_eq!(result[1].1, blended);
12288
12289        // Test adjacent same-color ranges merge
12290        let adjacent_same = vec![
12291            (display_point(5)..display_point(10), color1),
12292            (display_point(10)..display_point(15), color1),
12293        ];
12294        let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
12295        assert_eq!(cols(&result), vec![(5, 15)]);
12296
12297        // Test contained range splits
12298        let contained = vec![
12299            (display_point(5)..display_point(20), color1),
12300            (display_point(10)..display_point(15), color2),
12301        ];
12302        let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
12303        assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
12304
12305        // Test multiple overlaps split at every boundary
12306        let color3 = Hsla {
12307            h: 240.0,
12308            s: 0.5,
12309            l: 0.5,
12310            a: 0.5,
12311        };
12312        let complex = vec![
12313            (display_point(5)..display_point(12), color1),
12314            (display_point(8)..display_point(16), color2),
12315            (display_point(10)..display_point(14), color3),
12316        ];
12317        let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
12318        assert_eq!(
12319            cols(&result),
12320            vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
12321        );
12322    }
12323
12324    #[gpui::test]
12325    fn test_bg_segments_per_row() {
12326        let base_bg = Hsla::white();
12327
12328        // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
12329        {
12330            let selection_color = Hsla {
12331                h: 200.0,
12332                s: 0.5,
12333                l: 0.5,
12334                a: 0.5,
12335            };
12336            let player_color = PlayerColor {
12337                cursor: selection_color,
12338                background: selection_color,
12339                selection: selection_color,
12340            };
12341
12342            let spanning_selection = SelectionLayout {
12343                head: DisplayPoint::new(DisplayRow(3), 7),
12344                cursor_shape: CursorShape::Bar,
12345                is_newest: true,
12346                is_local: true,
12347                range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
12348                active_rows: DisplayRow(1)..DisplayRow(4),
12349                user_name: None,
12350            };
12351
12352            let selections = vec![(player_color, vec![spanning_selection])];
12353            let result = EditorElement::bg_segments_per_row(
12354                DisplayRow(0)..DisplayRow(5),
12355                &selections,
12356                &[],
12357                base_bg,
12358            );
12359
12360            assert_eq!(result.len(), 5);
12361            assert!(result[0].is_empty());
12362            assert_eq!(result[1].len(), 1);
12363            assert_eq!(result[2].len(), 1);
12364            assert_eq!(result[3].len(), 1);
12365            assert!(result[4].is_empty());
12366
12367            assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
12368            assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
12369            assert_eq!(result[1][0].0.end.column(), u32::MAX);
12370            assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
12371            assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
12372            assert_eq!(result[2][0].0.end.column(), u32::MAX);
12373            assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
12374            assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
12375        }
12376
12377        // Case B: selection ends exactly at the start of row 3, excluding row 3
12378        {
12379            let selection_color = Hsla {
12380                h: 120.0,
12381                s: 0.5,
12382                l: 0.5,
12383                a: 0.5,
12384            };
12385            let player_color = PlayerColor {
12386                cursor: selection_color,
12387                background: selection_color,
12388                selection: selection_color,
12389            };
12390
12391            let selection = SelectionLayout {
12392                head: DisplayPoint::new(DisplayRow(2), 0),
12393                cursor_shape: CursorShape::Bar,
12394                is_newest: true,
12395                is_local: true,
12396                range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
12397                active_rows: DisplayRow(1)..DisplayRow(3),
12398                user_name: None,
12399            };
12400
12401            let selections = vec![(player_color, vec![selection])];
12402            let result = EditorElement::bg_segments_per_row(
12403                DisplayRow(0)..DisplayRow(4),
12404                &selections,
12405                &[],
12406                base_bg,
12407            );
12408
12409            assert_eq!(result.len(), 4);
12410            assert!(result[0].is_empty());
12411            assert_eq!(result[1].len(), 1);
12412            assert_eq!(result[2].len(), 1);
12413            assert!(result[3].is_empty());
12414
12415            assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
12416            assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
12417            assert_eq!(result[1][0].0.end.column(), u32::MAX);
12418            assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
12419            assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
12420            assert_eq!(result[2][0].0.end.column(), u32::MAX);
12421        }
12422    }
12423
12424    #[cfg(test)]
12425    fn generate_test_run(len: usize, color: Hsla) -> TextRun {
12426        TextRun {
12427            len,
12428            color,
12429            ..Default::default()
12430        }
12431    }
12432
12433    #[gpui::test]
12434    fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
12435        init_test(cx, |_| {});
12436
12437        let dx = |start: u32, end: u32| {
12438            DisplayPoint::new(DisplayRow(0), start)..DisplayPoint::new(DisplayRow(0), end)
12439        };
12440
12441        let text_color = Hsla {
12442            h: 210.0,
12443            s: 0.1,
12444            l: 0.4,
12445            a: 1.0,
12446        };
12447        let bg_1 = Hsla {
12448            h: 30.0,
12449            s: 0.6,
12450            l: 0.8,
12451            a: 1.0,
12452        };
12453        let bg_2 = Hsla {
12454            h: 200.0,
12455            s: 0.6,
12456            l: 0.2,
12457            a: 1.0,
12458        };
12459        let min_contrast = 45.0;
12460        let adjusted_bg1 = ensure_minimum_contrast(text_color, bg_1, min_contrast);
12461        let adjusted_bg2 = ensure_minimum_contrast(text_color, bg_2, min_contrast);
12462
12463        // Case A: single run; disjoint segments inside the run
12464        {
12465            let runs = vec![generate_test_run(20, text_color)];
12466            let segs = vec![(dx(5, 10), bg_1), (dx(12, 16), bg_2)];
12467            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
12468            // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
12469            assert_eq!(
12470                out.iter().map(|r| r.len).collect::<Vec<_>>(),
12471                vec![5, 5, 2, 4, 4]
12472            );
12473            assert_eq!(out[0].color, text_color);
12474            assert_eq!(out[1].color, adjusted_bg1);
12475            assert_eq!(out[2].color, text_color);
12476            assert_eq!(out[3].color, adjusted_bg2);
12477            assert_eq!(out[4].color, text_color);
12478        }
12479
12480        // Case B: multiple runs; segment extends to end of line (u32::MAX)
12481        {
12482            let runs = vec![
12483                generate_test_run(8, text_color),
12484                generate_test_run(7, text_color),
12485            ];
12486            let segs = vec![(dx(6, u32::MAX), bg_1)];
12487            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
12488            // Expected slices across runs: [0,6) [6,8) | [0,7)
12489            assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
12490            assert_eq!(out[0].color, text_color);
12491            assert_eq!(out[1].color, adjusted_bg1);
12492            assert_eq!(out[2].color, adjusted_bg1);
12493        }
12494
12495        // Case C: multi-byte characters
12496        {
12497            // for text: "Hello 🌍 δΈ–η•Œ!"
12498            let runs = vec![
12499                generate_test_run(5, text_color), // "Hello"
12500                generate_test_run(6, text_color), // " 🌍 "
12501                generate_test_run(6, text_color), // "δΈ–η•Œ"
12502                generate_test_run(1, text_color), // "!"
12503            ];
12504            // selecting "🌍 δΈ–"
12505            let segs = vec![(dx(6, 14), bg_1)];
12506            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
12507            // "Hello" | " " | "🌍 " | "δΈ–" | "η•Œ" | "!"
12508            assert_eq!(
12509                out.iter().map(|r| r.len).collect::<Vec<_>>(),
12510                vec![5, 1, 5, 3, 3, 1]
12511            );
12512            assert_eq!(out[0].color, text_color); // "Hello"
12513            assert_eq!(out[2].color, adjusted_bg1); // "🌍 "
12514            assert_eq!(out[3].color, adjusted_bg1); // "δΈ–"
12515            assert_eq!(out[4].color, text_color); // "η•Œ"
12516            assert_eq!(out[5].color, text_color); // "!"
12517        }
12518
12519        // Case D: split multiple consecutive text runs with segments
12520        {
12521            let segs = vec![
12522                (dx(2, 4), bg_1),   // selecting "cd"
12523                (dx(4, 8), bg_2),   // selecting "efgh"
12524                (dx(9, 11), bg_1),  // selecting "jk"
12525                (dx(12, 16), bg_2), // selecting "mnop"
12526                (dx(18, 19), bg_1), // selecting "s"
12527            ];
12528
12529            // for text: "abcdef"
12530            let runs = vec![
12531                generate_test_run(2, text_color), // ab
12532                generate_test_run(4, text_color), // cdef
12533            ];
12534            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
12535            // new splits "ab", "cd", "ef"
12536            assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![2, 2, 2]);
12537            assert_eq!(out[0].color, text_color);
12538            assert_eq!(out[1].color, adjusted_bg1);
12539            assert_eq!(out[2].color, adjusted_bg2);
12540
12541            // for text: "ghijklmn"
12542            let runs = vec![
12543                generate_test_run(3, text_color), // ghi
12544                generate_test_run(2, text_color), // jk
12545                generate_test_run(3, text_color), // lmn
12546            ];
12547            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 6); // 2 + 4 from first run
12548            // new splits "gh", "i", "jk", "l", "mn"
12549            assert_eq!(
12550                out.iter().map(|r| r.len).collect::<Vec<_>>(),
12551                vec![2, 1, 2, 1, 2]
12552            );
12553            assert_eq!(out[0].color, adjusted_bg2);
12554            assert_eq!(out[1].color, text_color);
12555            assert_eq!(out[2].color, adjusted_bg1);
12556            assert_eq!(out[3].color, text_color);
12557            assert_eq!(out[4].color, adjusted_bg2);
12558
12559            // for text: "opqrs"
12560            let runs = vec![
12561                generate_test_run(1, text_color), // o
12562                generate_test_run(4, text_color), // pqrs
12563            ];
12564            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 14); // 6 + 3 + 2 + 3 from first two runs
12565            // new splits "o", "p", "qr", "s"
12566            assert_eq!(
12567                out.iter().map(|r| r.len).collect::<Vec<_>>(),
12568                vec![1, 1, 2, 1]
12569            );
12570            assert_eq!(out[0].color, adjusted_bg2);
12571            assert_eq!(out[1].color, adjusted_bg2);
12572            assert_eq!(out[2].color, text_color);
12573            assert_eq!(out[3].color, adjusted_bg1);
12574        }
12575    }
12576}