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