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