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