element.rs

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