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