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                if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
 7676                    delta = delta.coalesce(event.delta);
 7677
 7678                    if event.modifiers.secondary()
 7679                        && editor.read(cx).enable_mouse_wheel_zoom
 7680                        && EditorSettings::get_global(cx).mouse_wheel_zoom
 7681                    {
 7682                        let delta_y = match event.delta {
 7683                            ScrollDelta::Pixels(pixels) => pixels.y.into(),
 7684                            ScrollDelta::Lines(lines) => lines.y,
 7685                        };
 7686
 7687                        if delta_y > 0.0 {
 7688                            theme_settings::increase_buffer_font_size(cx);
 7689                        } else if delta_y < 0.0 {
 7690                            theme_settings::decrease_buffer_font_size(cx);
 7691                        }
 7692
 7693                        cx.stop_propagation();
 7694                    } else {
 7695                        let scroll_sensitivity = {
 7696                            if event.modifiers.alt {
 7697                                fast_scroll_sensitivity
 7698                            } else {
 7699                                base_scroll_sensitivity
 7700                            }
 7701                        };
 7702
 7703                        editor.update(cx, |editor, cx| {
 7704                            let line_height = position_map.line_height;
 7705                            let glyph_width = position_map.em_layout_width;
 7706                            let (delta, axis) = match delta {
 7707                                gpui::ScrollDelta::Pixels(mut pixels) => {
 7708                                    //Trackpad
 7709                                    let axis =
 7710                                        position_map.snapshot.ongoing_scroll.filter(&mut pixels);
 7711                                    (pixels, axis)
 7712                                }
 7713
 7714                                gpui::ScrollDelta::Lines(lines) => {
 7715                                    //Not trackpad
 7716                                    let pixels =
 7717                                        point(lines.x * glyph_width, lines.y * line_height);
 7718                                    (pixels, None)
 7719                                }
 7720                            };
 7721
 7722                            let current_scroll_position = position_map.snapshot.scroll_position();
 7723                            let x = (current_scroll_position.x
 7724                                * ScrollPixelOffset::from(glyph_width)
 7725                                - ScrollPixelOffset::from(delta.x * scroll_sensitivity))
 7726                                / ScrollPixelOffset::from(glyph_width);
 7727                            let y = (current_scroll_position.y
 7728                                * ScrollPixelOffset::from(line_height)
 7729                                - ScrollPixelOffset::from(delta.y * scroll_sensitivity))
 7730                                / ScrollPixelOffset::from(line_height);
 7731                            let mut scroll_position =
 7732                                point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
 7733                            let forbid_vertical_scroll =
 7734                                editor.scroll_manager.forbid_vertical_scroll();
 7735                            if forbid_vertical_scroll {
 7736                                scroll_position.y = current_scroll_position.y;
 7737                            }
 7738
 7739                            if scroll_position != current_scroll_position {
 7740                                editor.scroll(scroll_position, axis, window, cx);
 7741                                cx.stop_propagation();
 7742                            } else if y < 0. {
 7743                                // Due to clamping, we may fail to detect cases of overscroll to the top;
 7744                                // We want the scroll manager to get an update in such cases and detect the change of direction
 7745                                // on the next frame.
 7746                                cx.notify();
 7747                            }
 7748                        });
 7749                    }
 7750                }
 7751            }
 7752        });
 7753    }
 7754
 7755    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
 7756        if layout.mode.is_minimap() {
 7757            return;
 7758        }
 7759
 7760        self.paint_scroll_wheel_listener(layout, window, cx);
 7761
 7762        window.on_mouse_event({
 7763            let position_map = layout.position_map.clone();
 7764            let editor = self.editor.clone();
 7765            let line_numbers = layout.line_numbers.clone();
 7766
 7767            move |event: &MouseDownEvent, phase, window, cx| {
 7768                if phase == DispatchPhase::Bubble {
 7769                    match event.button {
 7770                        MouseButton::Left => editor.update(cx, |editor, cx| {
 7771                            let pending_mouse_down = editor
 7772                                .pending_mouse_down
 7773                                .get_or_insert_with(Default::default)
 7774                                .clone();
 7775
 7776                            *pending_mouse_down.borrow_mut() = Some(event.clone());
 7777
 7778                            Self::mouse_left_down(
 7779                                editor,
 7780                                event,
 7781                                &position_map,
 7782                                line_numbers.as_ref(),
 7783                                window,
 7784                                cx,
 7785                            );
 7786                        }),
 7787                        MouseButton::Right => editor.update(cx, |editor, cx| {
 7788                            Self::mouse_right_down(editor, event, &position_map, window, cx);
 7789                        }),
 7790                        MouseButton::Middle => editor.update(cx, |editor, cx| {
 7791                            Self::mouse_middle_down(editor, event, &position_map, window, cx);
 7792                        }),
 7793                        _ => {}
 7794                    };
 7795                }
 7796            }
 7797        });
 7798
 7799        window.on_mouse_event({
 7800            let editor = self.editor.clone();
 7801            let position_map = layout.position_map.clone();
 7802
 7803            move |event: &MouseUpEvent, phase, window, cx| {
 7804                if phase == DispatchPhase::Bubble {
 7805                    editor.update(cx, |editor, cx| {
 7806                        Self::mouse_up(editor, event, &position_map, window, cx)
 7807                    });
 7808                }
 7809            }
 7810        });
 7811
 7812        window.on_mouse_event({
 7813            let editor = self.editor.clone();
 7814            let position_map = layout.position_map.clone();
 7815            let mut captured_mouse_down = None;
 7816
 7817            move |event: &MouseUpEvent, phase, window, cx| match phase {
 7818                // Clear the pending mouse down during the capture phase,
 7819                // so that it happens even if another event handler stops
 7820                // propagation.
 7821                DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
 7822                    let pending_mouse_down = editor
 7823                        .pending_mouse_down
 7824                        .get_or_insert_with(Default::default)
 7825                        .clone();
 7826
 7827                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
 7828                    if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
 7829                        captured_mouse_down = pending_mouse_down.take();
 7830                        window.refresh();
 7831                    }
 7832                }),
 7833                // Fire click handlers during the bubble phase.
 7834                DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
 7835                    if let Some(mouse_down) = captured_mouse_down.take() {
 7836                        let event = ClickEvent::Mouse(MouseClickEvent {
 7837                            down: mouse_down,
 7838                            up: event.clone(),
 7839                        });
 7840                        Self::click(editor, &event, &position_map, window, cx);
 7841                    }
 7842                }),
 7843            }
 7844        });
 7845
 7846        window.on_mouse_event({
 7847            let position_map = layout.position_map.clone();
 7848            let editor = self.editor.clone();
 7849
 7850            move |event: &MousePressureEvent, phase, window, cx| {
 7851                if phase == DispatchPhase::Bubble {
 7852                    editor.update(cx, |editor, cx| {
 7853                        Self::pressure_click(editor, &event, &position_map, window, cx);
 7854                    })
 7855                }
 7856            }
 7857        });
 7858
 7859        window.on_mouse_event({
 7860            let position_map = layout.position_map.clone();
 7861            let editor = self.editor.clone();
 7862            let split_side = self.split_side;
 7863
 7864            move |event: &MouseMoveEvent, phase, window, cx| {
 7865                if phase == DispatchPhase::Bubble {
 7866                    editor.update(cx, |editor, cx| {
 7867                        if editor.hover_state.focused(window, cx) {
 7868                            return;
 7869                        }
 7870                        if event.pressed_button == Some(MouseButton::Left)
 7871                            || event.pressed_button == Some(MouseButton::Middle)
 7872                        {
 7873                            Self::mouse_dragged(editor, event, &position_map, window, cx)
 7874                        }
 7875
 7876                        Self::mouse_moved(editor, event, &position_map, split_side, window, cx)
 7877                    });
 7878                }
 7879            }
 7880        });
 7881    }
 7882
 7883    fn shape_line_number(
 7884        &self,
 7885        text: SharedString,
 7886        color: Hsla,
 7887        window: &mut Window,
 7888    ) -> ShapedLine {
 7889        let run = TextRun {
 7890            len: text.len(),
 7891            font: self.style.text.font(),
 7892            color,
 7893            ..Default::default()
 7894        };
 7895        window.text_system().shape_line(
 7896            text,
 7897            self.style.text.font_size.to_pixels(window.rem_size()),
 7898            &[run],
 7899            None,
 7900        )
 7901    }
 7902
 7903    fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
 7904        let unstaged = status.has_secondary_hunk();
 7905        let unstaged_hollow = matches!(
 7906            ProjectSettings::get_global(cx).git.hunk_style,
 7907            GitHunkStyleSetting::UnstagedHollow
 7908        );
 7909
 7910        unstaged == unstaged_hollow
 7911    }
 7912
 7913    #[cfg(debug_assertions)]
 7914    fn layout_debug_ranges(
 7915        selections: &mut Vec<(PlayerColor, Vec<SelectionLayout>)>,
 7916        anchor_range: Range<Anchor>,
 7917        display_snapshot: &DisplaySnapshot,
 7918        cx: &App,
 7919    ) {
 7920        let theme = cx.theme();
 7921        text::debug::GlobalDebugRanges::with_locked(|debug_ranges| {
 7922            if debug_ranges.ranges.is_empty() {
 7923                return;
 7924            }
 7925            let buffer_snapshot = &display_snapshot.buffer_snapshot();
 7926            for (excerpt_buffer_snapshot, buffer_range, _) in
 7927                buffer_snapshot.range_to_buffer_ranges(anchor_range.start..anchor_range.end)
 7928            {
 7929                let buffer_range = excerpt_buffer_snapshot.anchor_after(buffer_range.start)
 7930                    ..excerpt_buffer_snapshot.anchor_before(buffer_range.end);
 7931                selections.extend(debug_ranges.ranges.iter().flat_map(|debug_range| {
 7932                    debug_range.ranges.iter().filter_map(|range| {
 7933                        let player_color = theme
 7934                            .players()
 7935                            .color_for_participant(debug_range.occurrence_index as u32 + 1);
 7936                        if range.start.buffer_id != excerpt_buffer_snapshot.remote_id() {
 7937                            return None;
 7938                        }
 7939                        let clipped_start = range
 7940                            .start
 7941                            .max(&buffer_range.start, &excerpt_buffer_snapshot);
 7942                        let clipped_end =
 7943                            range.end.min(&buffer_range.end, &excerpt_buffer_snapshot);
 7944                        let range = buffer_snapshot
 7945                            .buffer_anchor_range_to_anchor_range(*clipped_start..*clipped_end)?;
 7946                        let start = range.start.to_display_point(display_snapshot);
 7947                        let end = range.end.to_display_point(display_snapshot);
 7948                        let selection_layout = SelectionLayout {
 7949                            head: start,
 7950                            range: start..end,
 7951                            cursor_shape: CursorShape::Bar,
 7952                            is_newest: false,
 7953                            is_local: false,
 7954                            active_rows: start.row()..end.row(),
 7955                            user_name: Some(SharedString::new(debug_range.value.clone())),
 7956                        };
 7957                        Some((player_color, vec![selection_layout]))
 7958                    })
 7959                }));
 7960            }
 7961        });
 7962    }
 7963}
 7964
 7965pub fn render_breadcrumb_text(
 7966    mut segments: Vec<HighlightedText>,
 7967    breadcrumb_font: Option<Font>,
 7968    prefix: Option<gpui::AnyElement>,
 7969    active_item: &dyn ItemHandle,
 7970    multibuffer_header: bool,
 7971    window: &mut Window,
 7972    cx: &App,
 7973) -> gpui::AnyElement {
 7974    const MAX_SEGMENTS: usize = 12;
 7975
 7976    let element = h_flex().flex_grow().text_ui(cx);
 7977
 7978    let prefix_end_ix = cmp::min(segments.len(), MAX_SEGMENTS / 2);
 7979    let suffix_start_ix = cmp::max(
 7980        prefix_end_ix,
 7981        segments.len().saturating_sub(MAX_SEGMENTS / 2),
 7982    );
 7983
 7984    if suffix_start_ix > prefix_end_ix {
 7985        segments.splice(
 7986            prefix_end_ix..suffix_start_ix,
 7987            Some(HighlightedText {
 7988                text: "β‹―".into(),
 7989                highlights: vec![],
 7990            }),
 7991        );
 7992    }
 7993
 7994    let highlighted_segments = segments.into_iter().enumerate().map(|(index, segment)| {
 7995        let mut text_style = window.text_style();
 7996        if let Some(font) = &breadcrumb_font {
 7997            text_style.font_family = font.family.clone();
 7998            text_style.font_features = font.features.clone();
 7999            text_style.font_style = font.style;
 8000            text_style.font_weight = font.weight;
 8001        }
 8002        text_style.color = Color::Muted.color(cx);
 8003
 8004        if index == 0
 8005            && !workspace::TabBarSettings::get_global(cx).show
 8006            && active_item.is_dirty(cx)
 8007            && let Some(styled_element) = apply_dirty_filename_style(&segment, &text_style, cx)
 8008        {
 8009            return styled_element;
 8010        }
 8011
 8012        StyledText::new(segment.text.replace('\n', " "))
 8013            .with_default_highlights(&text_style, segment.highlights)
 8014            .into_any()
 8015    });
 8016
 8017    let breadcrumbs = Itertools::intersperse_with(highlighted_segments, || {
 8018        Label::new("β€Ί").color(Color::Placeholder).into_any_element()
 8019    });
 8020
 8021    let breadcrumbs_stack = h_flex()
 8022        .gap_1()
 8023        .when(multibuffer_header, |this| {
 8024            this.pl_2()
 8025                .border_l_1()
 8026                .border_color(cx.theme().colors().border.opacity(0.6))
 8027        })
 8028        .children(breadcrumbs);
 8029
 8030    let breadcrumbs = if let Some(prefix) = prefix {
 8031        h_flex().gap_1p5().child(prefix).child(breadcrumbs_stack)
 8032    } else {
 8033        breadcrumbs_stack
 8034    };
 8035
 8036    let editor = active_item
 8037        .downcast::<Editor>()
 8038        .map(|editor| editor.downgrade());
 8039
 8040    let has_project_path = active_item.project_path(cx).is_some();
 8041
 8042    match editor {
 8043        Some(editor) => element
 8044            .id("breadcrumb_container")
 8045            .when(!multibuffer_header, |this| this.overflow_x_scroll())
 8046            .child(
 8047                ButtonLike::new("toggle outline view")
 8048                    .child(breadcrumbs)
 8049                    .when(multibuffer_header, |this| {
 8050                        this.style(ButtonStyle::Transparent)
 8051                    })
 8052                    .when(!multibuffer_header, |this| {
 8053                        let focus_handle = editor.upgrade().unwrap().focus_handle(&cx);
 8054
 8055                        this.tooltip(Tooltip::element(move |_window, cx| {
 8056                            v_flex()
 8057                                .gap_1()
 8058                                .child(
 8059                                    h_flex()
 8060                                        .gap_1()
 8061                                        .justify_between()
 8062                                        .child(Label::new("Show Symbol Outline"))
 8063                                        .child(ui::KeyBinding::for_action_in(
 8064                                            &zed_actions::outline::ToggleOutline,
 8065                                            &focus_handle,
 8066                                            cx,
 8067                                        )),
 8068                                )
 8069                                .when(has_project_path, |this| {
 8070                                    this.child(
 8071                                        h_flex()
 8072                                            .gap_1()
 8073                                            .justify_between()
 8074                                            .pt_1()
 8075                                            .border_t_1()
 8076                                            .border_color(cx.theme().colors().border_variant)
 8077                                            .child(Label::new("Right-Click to Copy Path")),
 8078                                    )
 8079                                })
 8080                                .into_any_element()
 8081                        }))
 8082                        .on_click({
 8083                            let editor = editor.clone();
 8084                            move |_, window, cx| {
 8085                                if let Some((editor, callback)) = editor
 8086                                    .upgrade()
 8087                                    .zip(zed_actions::outline::TOGGLE_OUTLINE.get())
 8088                                {
 8089                                    callback(editor.to_any_view(), window, cx);
 8090                                }
 8091                            }
 8092                        })
 8093                        .when(has_project_path, |this| {
 8094                            this.on_right_click({
 8095                                let editor = editor.clone();
 8096                                move |_, _, cx| {
 8097                                    if let Some(abs_path) = editor.upgrade().and_then(|editor| {
 8098                                        editor.update(cx, |editor, cx| {
 8099                                            editor.target_file_abs_path(cx)
 8100                                        })
 8101                                    }) {
 8102                                        if let Some(path_str) = abs_path.to_str() {
 8103                                            cx.write_to_clipboard(ClipboardItem::new_string(
 8104                                                path_str.to_string(),
 8105                                            ));
 8106                                        }
 8107                                    }
 8108                                }
 8109                            })
 8110                        })
 8111                    }),
 8112            )
 8113            .into_any_element(),
 8114        None => element
 8115            .h(rems_from_px(22.)) // Match the height and padding of the `ButtonLike` in the other arm.
 8116            .pl_1()
 8117            .child(breadcrumbs)
 8118            .into_any_element(),
 8119    }
 8120}
 8121
 8122fn apply_dirty_filename_style(
 8123    segment: &HighlightedText,
 8124    text_style: &gpui::TextStyle,
 8125    cx: &App,
 8126) -> Option<gpui::AnyElement> {
 8127    let text = segment.text.replace('\n', " ");
 8128
 8129    let filename_position = std::path::Path::new(segment.text.as_ref())
 8130        .file_name()
 8131        .and_then(|f| {
 8132            let filename_str = f.to_string_lossy();
 8133            segment.text.rfind(filename_str.as_ref())
 8134        })?;
 8135
 8136    let bold_weight = FontWeight::BOLD;
 8137    let default_color = Color::Default.color(cx);
 8138
 8139    if filename_position == 0 {
 8140        let mut filename_style = text_style.clone();
 8141        filename_style.font_weight = bold_weight;
 8142        filename_style.color = default_color;
 8143
 8144        return Some(
 8145            StyledText::new(text)
 8146                .with_default_highlights(&filename_style, [])
 8147                .into_any(),
 8148        );
 8149    }
 8150
 8151    let highlight_style = gpui::HighlightStyle {
 8152        font_weight: Some(bold_weight),
 8153        color: Some(default_color),
 8154        ..Default::default()
 8155    };
 8156
 8157    let highlight = vec![(filename_position..text.len(), highlight_style)];
 8158    Some(
 8159        StyledText::new(text)
 8160            .with_default_highlights(text_style, highlight)
 8161            .into_any(),
 8162    )
 8163}
 8164
 8165fn file_status_label_color(file_status: Option<FileStatus>) -> Color {
 8166    file_status.map_or(Color::Default, |status| {
 8167        if status.is_conflicted() {
 8168            Color::Conflict
 8169        } else if status.is_modified() {
 8170            Color::Modified
 8171        } else if status.is_deleted() {
 8172            Color::Disabled
 8173        } else if status.is_created() {
 8174            Color::Created
 8175        } else {
 8176            Color::Default
 8177        }
 8178    })
 8179}
 8180
 8181pub(crate) fn header_jump_data(
 8182    editor_snapshot: &EditorSnapshot,
 8183    block_row_start: DisplayRow,
 8184    height: u32,
 8185    first_excerpt: &ExcerptBoundaryInfo,
 8186    latest_selection_anchors: &HashMap<BufferId, Anchor>,
 8187) -> JumpData {
 8188    let multibuffer_snapshot = editor_snapshot.buffer_snapshot();
 8189    let buffer = first_excerpt.buffer(multibuffer_snapshot);
 8190    let (jump_anchor, jump_buffer) = if let Some(anchor) =
 8191        latest_selection_anchors.get(&first_excerpt.buffer_id())
 8192        && let Some((jump_anchor, selection_buffer)) =
 8193            multibuffer_snapshot.anchor_to_buffer_anchor(*anchor)
 8194    {
 8195        (jump_anchor, selection_buffer)
 8196    } else {
 8197        (first_excerpt.range.primary.start, buffer)
 8198    };
 8199    let excerpt_start = first_excerpt.range.context.start;
 8200    let jump_position = language::ToPoint::to_point(&jump_anchor, jump_buffer);
 8201    let rows_from_excerpt_start = if jump_anchor == excerpt_start {
 8202        0
 8203    } else {
 8204        let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
 8205        jump_position.row.saturating_sub(excerpt_start_point.row)
 8206    };
 8207
 8208    let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
 8209        .saturating_sub(
 8210            editor_snapshot
 8211                .scroll_anchor
 8212                .scroll_position(&editor_snapshot.display_snapshot)
 8213                .y as u32,
 8214        );
 8215
 8216    JumpData::MultiBufferPoint {
 8217        anchor: jump_anchor,
 8218        position: jump_position,
 8219        line_offset_from_top,
 8220    }
 8221}
 8222
 8223pub(crate) fn render_buffer_header(
 8224    editor: &Entity<Editor>,
 8225    for_excerpt: &ExcerptBoundaryInfo,
 8226    is_folded: bool,
 8227    is_selected: bool,
 8228    is_sticky: bool,
 8229    jump_data: JumpData,
 8230    window: &mut Window,
 8231    cx: &mut App,
 8232) -> impl IntoElement {
 8233    let editor_read = editor.read(cx);
 8234    let multi_buffer = editor_read.buffer.read(cx);
 8235    let is_read_only = editor_read.read_only(cx);
 8236    let editor_handle: &dyn ItemHandle = editor;
 8237    let multibuffer_snapshot = multi_buffer.snapshot(cx);
 8238    let buffer = for_excerpt.buffer(&multibuffer_snapshot);
 8239
 8240    let breadcrumbs = if is_selected {
 8241        editor_read.breadcrumbs_inner(cx)
 8242    } else {
 8243        None
 8244    };
 8245
 8246    let buffer_id = for_excerpt.buffer_id();
 8247    let file_status = multi_buffer
 8248        .all_diff_hunks_expanded()
 8249        .then(|| editor_read.status_for_buffer_id(buffer_id, cx))
 8250        .flatten();
 8251    let indicator = multi_buffer.buffer(buffer_id).and_then(|buffer| {
 8252        let buffer = buffer.read(cx);
 8253        let indicator_color = match (buffer.has_conflict(), buffer.is_dirty()) {
 8254            (true, _) => Some(Color::Warning),
 8255            (_, true) => Some(Color::Accent),
 8256            (false, false) => None,
 8257        };
 8258        indicator_color.map(|indicator_color| Indicator::dot().color(indicator_color))
 8259    });
 8260
 8261    let include_root = editor_read
 8262        .project
 8263        .as_ref()
 8264        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 8265        .unwrap_or_default();
 8266    let file = buffer.file();
 8267    let can_open_excerpts = file.is_none_or(|file| file.can_open());
 8268    let path_style = file.map(|file| file.path_style(cx));
 8269    let relative_path = buffer.resolve_file_path(include_root, cx);
 8270    let (parent_path, filename) = if let Some(path) = &relative_path {
 8271        if let Some(path_style) = path_style {
 8272            let (dir, file_name) = path_style.split(path);
 8273            (dir.map(|dir| dir.to_owned()), Some(file_name.to_owned()))
 8274        } else {
 8275            (None, Some(path.clone()))
 8276        }
 8277    } else {
 8278        (None, None)
 8279    };
 8280    let focus_handle = editor_read.focus_handle(cx);
 8281    let colors = cx.theme().colors();
 8282
 8283    let header = div()
 8284        .id(("buffer-header", buffer_id.to_proto()))
 8285        .p(BUFFER_HEADER_PADDING)
 8286        .w_full()
 8287        .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
 8288        .child(
 8289            h_flex()
 8290                .group("buffer-header-group")
 8291                .size_full()
 8292                .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
 8293                .pl_1()
 8294                .pr_2()
 8295                .rounded_sm()
 8296                .gap_1p5()
 8297                .when(is_sticky, |el| el.shadow_md())
 8298                .border_1()
 8299                .map(|border| {
 8300                    let border_color =
 8301                        if is_selected && is_folded && focus_handle.contains_focused(window, cx) {
 8302                            colors.border_focused
 8303                        } else {
 8304                            colors.border
 8305                        };
 8306                    border.border_color(border_color)
 8307                })
 8308                .bg(colors.editor_subheader_background)
 8309                .hover(|style| style.bg(colors.element_hover))
 8310                .map(|header| {
 8311                    let editor = editor.clone();
 8312                    let buffer_id = for_excerpt.buffer_id();
 8313                    let toggle_chevron_icon =
 8314                        FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
 8315                    let button_size = rems_from_px(28.);
 8316
 8317                    header.child(
 8318                        div()
 8319                            .hover(|style| style.bg(colors.element_selected))
 8320                            .rounded_xs()
 8321                            .child(
 8322                                ButtonLike::new("toggle-buffer-fold")
 8323                                    .style(ButtonStyle::Transparent)
 8324                                    .height(button_size.into())
 8325                                    .width(button_size)
 8326                                    .children(toggle_chevron_icon)
 8327                                    .tooltip({
 8328                                        let focus_handle = focus_handle.clone();
 8329                                        let is_folded_for_tooltip = is_folded;
 8330                                        move |_window, cx| {
 8331                                            Tooltip::with_meta_in(
 8332                                                if is_folded_for_tooltip {
 8333                                                    "Unfold Excerpt"
 8334                                                } else {
 8335                                                    "Fold Excerpt"
 8336                                                },
 8337                                                Some(&ToggleFold),
 8338                                                format!(
 8339                                                    "{} to toggle all",
 8340                                                    text_for_keystroke(
 8341                                                        &Modifiers::alt(),
 8342                                                        "click",
 8343                                                        cx
 8344                                                    )
 8345                                                ),
 8346                                                &focus_handle,
 8347                                                cx,
 8348                                            )
 8349                                        }
 8350                                    })
 8351                                    .on_click(move |event, window, cx| {
 8352                                        if event.modifiers().alt {
 8353                                            editor.update(cx, |editor, cx| {
 8354                                                editor.toggle_fold_all(&ToggleFoldAll, window, cx);
 8355                                            });
 8356                                        } else {
 8357                                            if is_folded {
 8358                                                editor.update(cx, |editor, cx| {
 8359                                                    editor.unfold_buffer(buffer_id, cx);
 8360                                                });
 8361                                            } else {
 8362                                                editor.update(cx, |editor, cx| {
 8363                                                    editor.fold_buffer(buffer_id, cx);
 8364                                                });
 8365                                            }
 8366                                        }
 8367                                    }),
 8368                            ),
 8369                    )
 8370                })
 8371                .children(
 8372                    editor_read
 8373                        .addons
 8374                        .values()
 8375                        .filter_map(|addon| {
 8376                            addon.render_buffer_header_controls(for_excerpt, buffer, window, cx)
 8377                        })
 8378                        .take(1),
 8379                )
 8380                .when(!is_read_only, |this| {
 8381                    this.child(
 8382                        h_flex()
 8383                            .size_3()
 8384                            .justify_center()
 8385                            .flex_shrink_0()
 8386                            .children(indicator),
 8387                    )
 8388                })
 8389                .child(
 8390                    h_flex()
 8391                        .cursor_pointer()
 8392                        .id("path_header_block")
 8393                        .min_w_0()
 8394                        .size_full()
 8395                        .gap_1()
 8396                        .justify_between()
 8397                        .overflow_hidden()
 8398                        .child(h_flex().min_w_0().flex_1().gap_0p5().overflow_hidden().map(
 8399                            |path_header| {
 8400                                let filename = filename
 8401                                    .map(SharedString::from)
 8402                                    .unwrap_or_else(|| "untitled".into());
 8403
 8404                                let full_path = match parent_path.as_deref() {
 8405                                    Some(parent) if !parent.is_empty() => {
 8406                                        format!("{}{}", parent, filename.as_str())
 8407                                    }
 8408                                    _ => filename.as_str().to_string(),
 8409                                };
 8410
 8411                                path_header
 8412                                    .child(
 8413                                        ButtonLike::new("filename-button")
 8414                                            .when(ItemSettings::get_global(cx).file_icons, |this| {
 8415                                                let path = path::Path::new(filename.as_str());
 8416                                                let icon = FileIcons::get_icon(path, cx)
 8417                                                    .unwrap_or_default();
 8418
 8419                                                this.child(
 8420                                                    Icon::from_path(icon).color(Color::Muted),
 8421                                                )
 8422                                            })
 8423                                            .child(
 8424                                                Label::new(filename)
 8425                                                    .single_line()
 8426                                                    .color(file_status_label_color(file_status))
 8427                                                    .buffer_font(cx)
 8428                                                    .when(
 8429                                                        file_status.is_some_and(|s| s.is_deleted()),
 8430                                                        |label| label.strikethrough(),
 8431                                                    ),
 8432                                            )
 8433                                            .tooltip(move |_, cx| {
 8434                                                Tooltip::with_meta(
 8435                                                    "Open File",
 8436                                                    None,
 8437                                                    full_path.clone(),
 8438                                                    cx,
 8439                                                )
 8440                                            })
 8441                                            .on_click(window.listener_for(editor, {
 8442                                                let jump_data = jump_data.clone();
 8443                                                move |editor, e: &ClickEvent, window, cx| {
 8444                                                    editor.open_excerpts_common(
 8445                                                        Some(jump_data.clone()),
 8446                                                        e.modifiers().secondary(),
 8447                                                        window,
 8448                                                        cx,
 8449                                                    );
 8450                                                }
 8451                                            })),
 8452                                    )
 8453                                    .when_some(parent_path, |then, path| {
 8454                                        then.child(
 8455                                            Label::new(path)
 8456                                                .buffer_font(cx)
 8457                                                .truncate_start()
 8458                                                .color(
 8459                                                    if file_status
 8460                                                        .is_some_and(FileStatus::is_deleted)
 8461                                                    {
 8462                                                        Color::Custom(colors.text_disabled)
 8463                                                    } else {
 8464                                                        Color::Custom(colors.text_muted)
 8465                                                    },
 8466                                                ),
 8467                                        )
 8468                                    })
 8469                                    .when(!buffer.capability.editable(), |el| {
 8470                                        el.child(Icon::new(IconName::FileLock).color(Color::Muted))
 8471                                    })
 8472                                    .when_some(breadcrumbs, |then, breadcrumbs| {
 8473                                        let font = theme_settings::ThemeSettings::get_global(cx)
 8474                                            .buffer_font
 8475                                            .clone();
 8476                                        then.child(render_breadcrumb_text(
 8477                                            breadcrumbs,
 8478                                            Some(font),
 8479                                            None,
 8480                                            editor_handle,
 8481                                            true,
 8482                                            window,
 8483                                            cx,
 8484                                        ))
 8485                                    })
 8486                            },
 8487                        ))
 8488                        .when(can_open_excerpts && relative_path.is_some(), |this| {
 8489                            this.child(
 8490                                div()
 8491                                    .when(!is_selected, |this| {
 8492                                        this.visible_on_hover("buffer-header-group")
 8493                                    })
 8494                                    .child(
 8495                                        Button::new("open-file-button", "Open File")
 8496                                            .style(ButtonStyle::OutlinedGhost)
 8497                                            .when(is_selected, |this| {
 8498                                                this.key_binding(KeyBinding::for_action_in(
 8499                                                    &OpenExcerpts,
 8500                                                    &focus_handle,
 8501                                                    cx,
 8502                                                ))
 8503                                            })
 8504                                            .on_click(window.listener_for(editor, {
 8505                                                let jump_data = jump_data.clone();
 8506                                                move |editor, e: &ClickEvent, window, cx| {
 8507                                                    editor.open_excerpts_common(
 8508                                                        Some(jump_data.clone()),
 8509                                                        e.modifiers().secondary(),
 8510                                                        window,
 8511                                                        cx,
 8512                                                    );
 8513                                                }
 8514                                            })),
 8515                                    ),
 8516                            )
 8517                        })
 8518                        .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 8519                        .on_click(window.listener_for(editor, {
 8520                            let buffer_id = for_excerpt.buffer_id();
 8521                            move |editor, e: &ClickEvent, window, cx| {
 8522                                if e.modifiers().alt {
 8523                                    editor.open_excerpts_common(
 8524                                        Some(jump_data.clone()),
 8525                                        e.modifiers().secondary(),
 8526                                        window,
 8527                                        cx,
 8528                                    );
 8529                                    return;
 8530                                }
 8531
 8532                                if is_folded {
 8533                                    editor.unfold_buffer(buffer_id, cx);
 8534                                } else {
 8535                                    editor.fold_buffer(buffer_id, cx);
 8536                                }
 8537                            }
 8538                        })),
 8539                ),
 8540        );
 8541
 8542    let file = buffer.file().cloned();
 8543    let editor = editor.clone();
 8544
 8545    right_click_menu("buffer-header-context-menu")
 8546        .trigger(move |_, _, _| header)
 8547        .menu(move |window, cx| {
 8548            let menu_context = focus_handle.clone();
 8549            let editor = editor.clone();
 8550            let file = file.clone();
 8551            ContextMenu::build(window, cx, move |mut menu, window, cx| {
 8552                if let Some(file) = file
 8553                    && let Some(project) = editor.read(cx).project()
 8554                    && let Some(worktree) =
 8555                        project.read(cx).worktree_for_id(file.worktree_id(cx), cx)
 8556                {
 8557                    let path_style = file.path_style(cx);
 8558                    let worktree = worktree.read(cx);
 8559                    let relative_path = file.path();
 8560                    let entry_for_path = worktree.entry_for_path(relative_path);
 8561                    let abs_path = entry_for_path.map(|e| {
 8562                        e.canonical_path
 8563                            .as_deref()
 8564                            .map_or_else(|| worktree.absolutize(relative_path), Path::to_path_buf)
 8565                    });
 8566                    let has_relative_path = worktree.root_entry().is_some_and(Entry::is_dir);
 8567
 8568                    let parent_abs_path = abs_path
 8569                        .as_ref()
 8570                        .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
 8571                    let relative_path = has_relative_path
 8572                        .then_some(relative_path)
 8573                        .map(ToOwned::to_owned);
 8574
 8575                    let visible_in_project_panel = relative_path.is_some() && worktree.is_visible();
 8576                    let reveal_in_project_panel = entry_for_path
 8577                        .filter(|_| visible_in_project_panel)
 8578                        .map(|entry| entry.id);
 8579                    menu = menu
 8580                        .when_some(abs_path, |menu, abs_path| {
 8581                            menu.entry(
 8582                                "Copy Path",
 8583                                Some(Box::new(zed_actions::workspace::CopyPath)),
 8584                                window.handler_for(&editor, move |_, _, cx| {
 8585                                    cx.write_to_clipboard(ClipboardItem::new_string(
 8586                                        abs_path.to_string_lossy().into_owned(),
 8587                                    ));
 8588                                }),
 8589                            )
 8590                        })
 8591                        .when_some(relative_path, |menu, relative_path| {
 8592                            menu.entry(
 8593                                "Copy Relative Path",
 8594                                Some(Box::new(zed_actions::workspace::CopyRelativePath)),
 8595                                window.handler_for(&editor, move |_, _, cx| {
 8596                                    cx.write_to_clipboard(ClipboardItem::new_string(
 8597                                        relative_path.display(path_style).to_string(),
 8598                                    ));
 8599                                }),
 8600                            )
 8601                        })
 8602                        .when(
 8603                            reveal_in_project_panel.is_some() || parent_abs_path.is_some(),
 8604                            |menu| menu.separator(),
 8605                        )
 8606                        .when_some(reveal_in_project_panel, |menu, entry_id| {
 8607                            menu.entry(
 8608                                "Reveal In Project Panel",
 8609                                Some(Box::new(RevealInProjectPanel::default())),
 8610                                window.handler_for(&editor, move |editor, _, cx| {
 8611                                    if let Some(project) = &mut editor.project {
 8612                                        project.update(cx, |_, cx| {
 8613                                            cx.emit(project::Event::RevealInProjectPanel(entry_id))
 8614                                        });
 8615                                    }
 8616                                }),
 8617                            )
 8618                        })
 8619                        .when_some(parent_abs_path, |menu, parent_abs_path| {
 8620                            menu.entry(
 8621                                "Open in Terminal",
 8622                                Some(Box::new(OpenInTerminal)),
 8623                                window.handler_for(&editor, move |_, window, cx| {
 8624                                    window.dispatch_action(
 8625                                        OpenTerminal {
 8626                                            working_directory: parent_abs_path.clone(),
 8627                                            local: false,
 8628                                        }
 8629                                        .boxed_clone(),
 8630                                        cx,
 8631                                    );
 8632                                }),
 8633                            )
 8634                        });
 8635                }
 8636
 8637                menu.context(menu_context)
 8638            })
 8639        })
 8640}
 8641
 8642fn prepaint_gutter_button(
 8643    mut button: AnyElement,
 8644    row: DisplayRow,
 8645    line_height: Pixels,
 8646    gutter_dimensions: &GutterDimensions,
 8647    scroll_position: gpui::Point<ScrollOffset>,
 8648    gutter_hitbox: &Hitbox,
 8649    window: &mut Window,
 8650    cx: &mut App,
 8651) -> AnyElement {
 8652    let available_space = size(
 8653        AvailableSpace::MinContent,
 8654        AvailableSpace::Definite(line_height),
 8655    );
 8656    let indicator_size = button.layout_as_root(available_space, window, cx);
 8657    let git_gutter_width = EditorElement::gutter_strip_width(line_height)
 8658        + gutter_dimensions
 8659            .git_blame_entries_width
 8660            .unwrap_or_default();
 8661
 8662    let x = git_gutter_width + px(2.);
 8663
 8664    let mut y =
 8665        Pixels::from((row.as_f64() - scroll_position.y) * ScrollPixelOffset::from(line_height));
 8666    y += (line_height - indicator_size.height) / 2.;
 8667
 8668    button.prepaint_as_root(
 8669        gutter_hitbox.origin + point(x, y),
 8670        available_space,
 8671        window,
 8672        cx,
 8673    );
 8674    button
 8675}
 8676
 8677fn render_inline_blame_entry(
 8678    blame_entry: BlameEntry,
 8679    style: &EditorStyle,
 8680    cx: &mut App,
 8681) -> Option<AnyElement> {
 8682    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 8683    renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
 8684}
 8685
 8686fn render_blame_entry_popover(
 8687    blame_entry: BlameEntry,
 8688    scroll_handle: ScrollHandle,
 8689    commit_message: Option<ParsedCommitMessage>,
 8690    markdown: Entity<Markdown>,
 8691    workspace: WeakEntity<Workspace>,
 8692    blame: &Entity<GitBlame>,
 8693    buffer: BufferId,
 8694    window: &mut Window,
 8695    cx: &mut App,
 8696) -> Option<AnyElement> {
 8697    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 8698    let blame = blame.read(cx);
 8699    let repository = blame.repository(cx, buffer)?;
 8700    renderer.render_blame_entry_popover(
 8701        blame_entry,
 8702        scroll_handle,
 8703        commit_message,
 8704        markdown,
 8705        repository,
 8706        workspace,
 8707        window,
 8708        cx,
 8709    )
 8710}
 8711
 8712fn render_blame_entry(
 8713    ix: usize,
 8714    blame: &Entity<GitBlame>,
 8715    blame_entry: BlameEntry,
 8716    style: &EditorStyle,
 8717    last_used_color: &mut Option<(Hsla, Oid)>,
 8718    editor: Entity<Editor>,
 8719    workspace: Entity<Workspace>,
 8720    buffer: BufferId,
 8721    renderer: &dyn BlameRenderer,
 8722    window: &mut Window,
 8723    cx: &mut App,
 8724) -> Option<AnyElement> {
 8725    let index: u32 = blame_entry.sha.into();
 8726    let mut sha_color = cx.theme().players().color_for_participant(index).cursor;
 8727
 8728    // If the last color we used is the same as the one we get for this line, but
 8729    // the commit SHAs are different, then we try again to get a different color.
 8730    if let Some((color, sha)) = *last_used_color
 8731        && sha != blame_entry.sha
 8732        && color == sha_color
 8733    {
 8734        sha_color = cx.theme().players().color_for_participant(index + 1).cursor;
 8735    }
 8736    last_used_color.replace((sha_color, blame_entry.sha));
 8737
 8738    let blame = blame.read(cx);
 8739    let details = blame.details_for_entry(buffer, &blame_entry);
 8740    let repository = blame.repository(cx, buffer)?;
 8741    renderer.render_blame_entry(
 8742        &style.text,
 8743        blame_entry,
 8744        details,
 8745        repository,
 8746        workspace.downgrade(),
 8747        editor,
 8748        ix,
 8749        sha_color,
 8750        window,
 8751        cx,
 8752    )
 8753}
 8754
 8755#[derive(Debug)]
 8756pub(crate) struct LineWithInvisibles {
 8757    fragments: SmallVec<[LineFragment; 1]>,
 8758    invisibles: Vec<Invisible>,
 8759    len: usize,
 8760    pub(crate) width: Pixels,
 8761    font_size: Pixels,
 8762}
 8763
 8764enum LineFragment {
 8765    Text(ShapedLine),
 8766    Element {
 8767        id: ChunkRendererId,
 8768        element: Option<AnyElement>,
 8769        size: Size<Pixels>,
 8770        len: usize,
 8771    },
 8772}
 8773
 8774impl fmt::Debug for LineFragment {
 8775    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 8776        match self {
 8777            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
 8778            LineFragment::Element { size, len, .. } => f
 8779                .debug_struct("Element")
 8780                .field("size", size)
 8781                .field("len", len)
 8782                .finish(),
 8783        }
 8784    }
 8785}
 8786
 8787impl LineWithInvisibles {
 8788    fn from_chunks<'a>(
 8789        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
 8790        editor_style: &EditorStyle,
 8791        max_line_len: usize,
 8792        max_line_count: usize,
 8793        editor_mode: &EditorMode,
 8794        text_width: Pixels,
 8795        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 8796        bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
 8797        window: &mut Window,
 8798        cx: &mut App,
 8799    ) -> Vec<Self> {
 8800        let text_style = &editor_style.text;
 8801        let mut layouts = Vec::with_capacity(max_line_count);
 8802        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
 8803        let mut line = String::new();
 8804        let mut invisibles = Vec::new();
 8805        let mut width = Pixels::ZERO;
 8806        let mut len = 0;
 8807        let mut styles = Vec::new();
 8808        let mut non_whitespace_added = false;
 8809        let mut row = 0;
 8810        let mut line_exceeded_max_len = false;
 8811        let font_size = text_style.font_size.to_pixels(window.rem_size());
 8812        let min_contrast = EditorSettings::get_global(cx).minimum_contrast_for_highlights;
 8813
 8814        let ellipsis = SharedString::from("β‹―");
 8815
 8816        for highlighted_chunk in chunks.chain([HighlightedChunk {
 8817            text: "\n",
 8818            style: None,
 8819            is_tab: false,
 8820            is_inlay: false,
 8821            replacement: None,
 8822        }]) {
 8823            if let Some(replacement) = highlighted_chunk.replacement {
 8824                if !line.is_empty() {
 8825                    let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
 8826                    let text_runs: &[TextRun] = if segments.is_empty() {
 8827                        &styles
 8828                    } else {
 8829                        &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
 8830                    };
 8831                    let shaped_line = window.text_system().shape_line(
 8832                        line.clone().into(),
 8833                        font_size,
 8834                        text_runs,
 8835                        None,
 8836                    );
 8837                    width += shaped_line.width;
 8838                    len += shaped_line.len;
 8839                    fragments.push(LineFragment::Text(shaped_line));
 8840                    line.clear();
 8841                    styles.clear();
 8842                }
 8843
 8844                match replacement {
 8845                    ChunkReplacement::Renderer(renderer) => {
 8846                        let available_width = if renderer.constrain_width {
 8847                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
 8848                                ellipsis.clone()
 8849                            } else {
 8850                                SharedString::from(Arc::from(highlighted_chunk.text))
 8851                            };
 8852                            let shaped_line = window.text_system().shape_line(
 8853                                chunk,
 8854                                font_size,
 8855                                &[text_style.to_run(highlighted_chunk.text.len())],
 8856                                None,
 8857                            );
 8858                            AvailableSpace::Definite(shaped_line.width)
 8859                        } else {
 8860                            AvailableSpace::MinContent
 8861                        };
 8862
 8863                        let mut element = (renderer.render)(&mut ChunkRendererContext {
 8864                            context: cx,
 8865                            window,
 8866                            max_width: text_width,
 8867                        });
 8868                        let line_height = text_style.line_height_in_pixels(window.rem_size());
 8869                        let size = element.layout_as_root(
 8870                            size(available_width, AvailableSpace::Definite(line_height)),
 8871                            window,
 8872                            cx,
 8873                        );
 8874
 8875                        width += size.width;
 8876                        len += highlighted_chunk.text.len();
 8877                        fragments.push(LineFragment::Element {
 8878                            id: renderer.id,
 8879                            element: Some(element),
 8880                            size,
 8881                            len: highlighted_chunk.text.len(),
 8882                        });
 8883                    }
 8884                    ChunkReplacement::Str(x) => {
 8885                        let text_style = if let Some(style) = highlighted_chunk.style {
 8886                            Cow::Owned(text_style.clone().highlight(style))
 8887                        } else {
 8888                            Cow::Borrowed(text_style)
 8889                        };
 8890
 8891                        let run = TextRun {
 8892                            len: x.len(),
 8893                            font: text_style.font(),
 8894                            color: text_style.color,
 8895                            background_color: text_style.background_color,
 8896                            underline: text_style.underline,
 8897                            strikethrough: text_style.strikethrough,
 8898                        };
 8899                        let line_layout = window
 8900                            .text_system()
 8901                            .shape_line(x, font_size, &[run], None)
 8902                            .with_len(highlighted_chunk.text.len());
 8903
 8904                        width += line_layout.width;
 8905                        len += highlighted_chunk.text.len();
 8906                        fragments.push(LineFragment::Text(line_layout))
 8907                    }
 8908                }
 8909            } else {
 8910                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
 8911                    if ix > 0 {
 8912                        let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
 8913                        let text_runs = if segments.is_empty() {
 8914                            &styles
 8915                        } else {
 8916                            &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
 8917                        };
 8918                        let shaped_line = window.text_system().shape_line(
 8919                            line.clone().into(),
 8920                            font_size,
 8921                            text_runs,
 8922                            None,
 8923                        );
 8924                        width += shaped_line.width;
 8925                        len += shaped_line.len;
 8926                        fragments.push(LineFragment::Text(shaped_line));
 8927                        layouts.push(Self {
 8928                            width: mem::take(&mut width),
 8929                            len: mem::take(&mut len),
 8930                            fragments: mem::take(&mut fragments),
 8931                            invisibles: std::mem::take(&mut invisibles),
 8932                            font_size,
 8933                        });
 8934
 8935                        line.clear();
 8936                        styles.clear();
 8937                        row += 1;
 8938                        line_exceeded_max_len = false;
 8939                        non_whitespace_added = false;
 8940                        if row == max_line_count {
 8941                            return layouts;
 8942                        }
 8943                    }
 8944
 8945                    if !line_chunk.is_empty() && !line_exceeded_max_len {
 8946                        let text_style = if let Some(style) = highlighted_chunk.style {
 8947                            Cow::Owned(text_style.clone().highlight(style))
 8948                        } else {
 8949                            Cow::Borrowed(text_style)
 8950                        };
 8951
 8952                        if line.len() + line_chunk.len() > max_line_len {
 8953                            let mut chunk_len = max_line_len - line.len();
 8954                            while !line_chunk.is_char_boundary(chunk_len) {
 8955                                chunk_len -= 1;
 8956                            }
 8957                            line_chunk = &line_chunk[..chunk_len];
 8958                            line_exceeded_max_len = true;
 8959                        }
 8960
 8961                        styles.push(TextRun {
 8962                            len: line_chunk.len(),
 8963                            font: text_style.font(),
 8964                            color: text_style.color,
 8965                            background_color: text_style.background_color,
 8966                            underline: text_style.underline,
 8967                            strikethrough: text_style.strikethrough,
 8968                        });
 8969
 8970                        if editor_mode.is_full() && !highlighted_chunk.is_inlay {
 8971                            // Line wrap pads its contents with fake whitespaces,
 8972                            // avoid printing them
 8973                            let is_soft_wrapped = is_row_soft_wrapped(row);
 8974                            if highlighted_chunk.is_tab {
 8975                                if non_whitespace_added || !is_soft_wrapped {
 8976                                    invisibles.push(Invisible::Tab {
 8977                                        line_start_offset: line.len(),
 8978                                        line_end_offset: line.len() + line_chunk.len(),
 8979                                    });
 8980                                }
 8981                            } else {
 8982                                invisibles.extend(line_chunk.char_indices().filter_map(
 8983                                    |(index, c)| {
 8984                                        let is_whitespace = c.is_whitespace();
 8985                                        non_whitespace_added |= !is_whitespace;
 8986                                        if is_whitespace
 8987                                            && (non_whitespace_added || !is_soft_wrapped)
 8988                                        {
 8989                                            Some(Invisible::Whitespace {
 8990                                                line_offset: line.len() + index,
 8991                                            })
 8992                                        } else {
 8993                                            None
 8994                                        }
 8995                                    },
 8996                                ))
 8997                            }
 8998                        }
 8999
 9000                        line.push_str(line_chunk);
 9001                    }
 9002                }
 9003            }
 9004        }
 9005
 9006        layouts
 9007    }
 9008
 9009    /// Takes text runs and non-overlapping left-to-right background ranges with color.
 9010    /// Returns new text runs with adjusted contrast as per background ranges.
 9011    fn split_runs_by_bg_segments(
 9012        text_runs: &[TextRun],
 9013        bg_segments: &[(Range<DisplayPoint>, Hsla)],
 9014        min_contrast: f32,
 9015        start_col_offset: usize,
 9016    ) -> Vec<TextRun> {
 9017        let mut output_runs: Vec<TextRun> = Vec::with_capacity(text_runs.len());
 9018        let mut line_col = start_col_offset;
 9019        let mut segment_ix = 0usize;
 9020
 9021        for text_run in text_runs.iter() {
 9022            let run_start_col = line_col;
 9023            let run_end_col = run_start_col + text_run.len;
 9024            while segment_ix < bg_segments.len()
 9025                && (bg_segments[segment_ix].0.end.column() as usize) <= run_start_col
 9026            {
 9027                segment_ix += 1;
 9028            }
 9029            let mut cursor_col = run_start_col;
 9030            let mut local_segment_ix = segment_ix;
 9031            while local_segment_ix < bg_segments.len() {
 9032                let (range, segment_color) = &bg_segments[local_segment_ix];
 9033                let segment_start_col = range.start.column() as usize;
 9034                let segment_end_col = range.end.column() as usize;
 9035                if segment_start_col >= run_end_col {
 9036                    break;
 9037                }
 9038                if segment_start_col > cursor_col {
 9039                    let span_len = segment_start_col - cursor_col;
 9040                    output_runs.push(TextRun {
 9041                        len: span_len,
 9042                        font: text_run.font.clone(),
 9043                        color: text_run.color,
 9044                        background_color: text_run.background_color,
 9045                        underline: text_run.underline,
 9046                        strikethrough: text_run.strikethrough,
 9047                    });
 9048                    cursor_col = segment_start_col;
 9049                }
 9050                let segment_slice_end_col = segment_end_col.min(run_end_col);
 9051                if segment_slice_end_col > cursor_col {
 9052                    let new_text_color =
 9053                        ensure_minimum_contrast(text_run.color, *segment_color, min_contrast);
 9054                    output_runs.push(TextRun {
 9055                        len: segment_slice_end_col - cursor_col,
 9056                        font: text_run.font.clone(),
 9057                        color: new_text_color,
 9058                        background_color: text_run.background_color,
 9059                        underline: text_run.underline,
 9060                        strikethrough: text_run.strikethrough,
 9061                    });
 9062                    cursor_col = segment_slice_end_col;
 9063                }
 9064                if segment_end_col >= run_end_col {
 9065                    break;
 9066                }
 9067                local_segment_ix += 1;
 9068            }
 9069            if cursor_col < run_end_col {
 9070                output_runs.push(TextRun {
 9071                    len: run_end_col - cursor_col,
 9072                    font: text_run.font.clone(),
 9073                    color: text_run.color,
 9074                    background_color: text_run.background_color,
 9075                    underline: text_run.underline,
 9076                    strikethrough: text_run.strikethrough,
 9077                });
 9078            }
 9079            line_col = run_end_col;
 9080            segment_ix = local_segment_ix;
 9081        }
 9082        output_runs
 9083    }
 9084
 9085    fn prepaint(
 9086        &mut self,
 9087        line_height: Pixels,
 9088        scroll_position: gpui::Point<ScrollOffset>,
 9089        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 9090        row: DisplayRow,
 9091        content_origin: gpui::Point<Pixels>,
 9092        line_elements: &mut SmallVec<[AnyElement; 1]>,
 9093        window: &mut Window,
 9094        cx: &mut App,
 9095    ) {
 9096        let line_y = f32::from(line_height) * Pixels::from(row.as_f64() - scroll_position.y);
 9097        self.prepaint_with_custom_offset(
 9098            line_height,
 9099            scroll_pixel_position,
 9100            content_origin,
 9101            line_y,
 9102            line_elements,
 9103            window,
 9104            cx,
 9105        );
 9106    }
 9107
 9108    fn prepaint_with_custom_offset(
 9109        &mut self,
 9110        line_height: Pixels,
 9111        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 9112        content_origin: gpui::Point<Pixels>,
 9113        line_y: Pixels,
 9114        line_elements: &mut SmallVec<[AnyElement; 1]>,
 9115        window: &mut Window,
 9116        cx: &mut App,
 9117    ) {
 9118        let mut fragment_origin =
 9119            content_origin + gpui::point(Pixels::from(-scroll_pixel_position.x), line_y);
 9120        for fragment in &mut self.fragments {
 9121            match fragment {
 9122                LineFragment::Text(line) => {
 9123                    fragment_origin.x += line.width;
 9124                }
 9125                LineFragment::Element { element, size, .. } => {
 9126                    let mut element = element
 9127                        .take()
 9128                        .expect("you can't prepaint LineWithInvisibles twice");
 9129
 9130                    // Center the element vertically within the line.
 9131                    let mut element_origin = fragment_origin;
 9132                    element_origin.y += (line_height - size.height) / 2.;
 9133                    element.prepaint_at(element_origin, window, cx);
 9134                    line_elements.push(element);
 9135
 9136                    fragment_origin.x += size.width;
 9137                }
 9138            }
 9139        }
 9140    }
 9141
 9142    fn draw(
 9143        &self,
 9144        layout: &EditorLayout,
 9145        row: DisplayRow,
 9146        content_origin: gpui::Point<Pixels>,
 9147        whitespace_setting: ShowWhitespaceSetting,
 9148        selection_ranges: &[Range<DisplayPoint>],
 9149        window: &mut Window,
 9150        cx: &mut App,
 9151    ) {
 9152        self.draw_with_custom_offset(
 9153            layout,
 9154            row,
 9155            content_origin,
 9156            layout.position_map.line_height
 9157                * (row.as_f64() - layout.position_map.scroll_position.y) as f32,
 9158            whitespace_setting,
 9159            selection_ranges,
 9160            window,
 9161            cx,
 9162        );
 9163    }
 9164
 9165    fn draw_with_custom_offset(
 9166        &self,
 9167        layout: &EditorLayout,
 9168        row: DisplayRow,
 9169        content_origin: gpui::Point<Pixels>,
 9170        line_y: Pixels,
 9171        whitespace_setting: ShowWhitespaceSetting,
 9172        selection_ranges: &[Range<DisplayPoint>],
 9173        window: &mut Window,
 9174        cx: &mut App,
 9175    ) {
 9176        let line_height = layout.position_map.line_height;
 9177        let mut fragment_origin = content_origin
 9178            + gpui::point(
 9179                Pixels::from(-layout.position_map.scroll_pixel_position.x),
 9180                line_y,
 9181            );
 9182
 9183        for fragment in &self.fragments {
 9184            match fragment {
 9185                LineFragment::Text(line) => {
 9186                    line.paint(
 9187                        fragment_origin,
 9188                        line_height,
 9189                        layout.text_align,
 9190                        Some(layout.content_width),
 9191                        window,
 9192                        cx,
 9193                    )
 9194                    .log_err();
 9195                    fragment_origin.x += line.width;
 9196                }
 9197                LineFragment::Element { size, .. } => {
 9198                    fragment_origin.x += size.width;
 9199                }
 9200            }
 9201        }
 9202
 9203        self.draw_invisibles(
 9204            selection_ranges,
 9205            layout,
 9206            content_origin,
 9207            line_y,
 9208            row,
 9209            line_height,
 9210            whitespace_setting,
 9211            window,
 9212            cx,
 9213        );
 9214    }
 9215
 9216    fn draw_background(
 9217        &self,
 9218        layout: &EditorLayout,
 9219        row: DisplayRow,
 9220        content_origin: gpui::Point<Pixels>,
 9221        window: &mut Window,
 9222        cx: &mut App,
 9223    ) {
 9224        let line_height = layout.position_map.line_height;
 9225        let line_y = line_height * (row.as_f64() - layout.position_map.scroll_position.y) as f32;
 9226
 9227        let mut fragment_origin = content_origin
 9228            + gpui::point(
 9229                Pixels::from(-layout.position_map.scroll_pixel_position.x),
 9230                line_y,
 9231            );
 9232
 9233        for fragment in &self.fragments {
 9234            match fragment {
 9235                LineFragment::Text(line) => {
 9236                    line.paint_background(
 9237                        fragment_origin,
 9238                        line_height,
 9239                        layout.text_align,
 9240                        Some(layout.content_width),
 9241                        window,
 9242                        cx,
 9243                    )
 9244                    .log_err();
 9245                    fragment_origin.x += line.width;
 9246                }
 9247                LineFragment::Element { size, .. } => {
 9248                    fragment_origin.x += size.width;
 9249                }
 9250            }
 9251        }
 9252    }
 9253
 9254    fn draw_invisibles(
 9255        &self,
 9256        selection_ranges: &[Range<DisplayPoint>],
 9257        layout: &EditorLayout,
 9258        content_origin: gpui::Point<Pixels>,
 9259        line_y: Pixels,
 9260        row: DisplayRow,
 9261        line_height: Pixels,
 9262        whitespace_setting: ShowWhitespaceSetting,
 9263        window: &mut Window,
 9264        cx: &mut App,
 9265    ) {
 9266        let extract_whitespace_info = |invisible: &Invisible| {
 9267            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
 9268                Invisible::Tab {
 9269                    line_start_offset,
 9270                    line_end_offset,
 9271                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
 9272                Invisible::Whitespace { line_offset } => {
 9273                    (*line_offset, line_offset + 1, &layout.space_invisible)
 9274                }
 9275            };
 9276
 9277            let x_offset: ScrollPixelOffset = self.x_for_index(token_offset).into();
 9278            let invisible_offset: ScrollPixelOffset =
 9279                ((layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0)
 9280                    .into();
 9281            let origin = content_origin
 9282                + gpui::point(
 9283                    Pixels::from(
 9284                        x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
 9285                    ),
 9286                    line_y,
 9287                );
 9288
 9289            (
 9290                [token_offset, token_end_offset],
 9291                Box::new(move |window: &mut Window, cx: &mut App| {
 9292                    invisible_symbol
 9293                        .paint(origin, line_height, TextAlign::Left, None, window, cx)
 9294                        .log_err();
 9295                }),
 9296            )
 9297        };
 9298
 9299        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
 9300        match whitespace_setting {
 9301            ShowWhitespaceSetting::None => (),
 9302            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
 9303            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
 9304                let invisible_point = DisplayPoint::new(row, start as u32);
 9305                if !selection_ranges
 9306                    .iter()
 9307                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
 9308                {
 9309                    return;
 9310                }
 9311
 9312                paint(window, cx);
 9313            }),
 9314
 9315            ShowWhitespaceSetting::Trailing => {
 9316                let mut previous_start = self.len;
 9317                for ([start, end], paint) in invisible_iter.rev() {
 9318                    if previous_start != end {
 9319                        break;
 9320                    }
 9321                    previous_start = start;
 9322                    paint(window, cx);
 9323                }
 9324            }
 9325
 9326            // For a whitespace to be on a boundary, any of the following conditions need to be met:
 9327            // - It is a tab
 9328            // - It is adjacent to an edge (start or end)
 9329            // - It is adjacent to a whitespace (left or right)
 9330            ShowWhitespaceSetting::Boundary => {
 9331                // 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
 9332                // the above cases.
 9333                // Note: We zip in the original `invisibles` to check for tab equality
 9334                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
 9335                for (([start, end], paint), invisible) in
 9336                    invisible_iter.zip_eq(self.invisibles.iter())
 9337                {
 9338                    let should_render = match (&last_seen, invisible) {
 9339                        (_, Invisible::Tab { .. }) => true,
 9340                        (Some((_, last_end, _)), _) => *last_end == start,
 9341                        _ => false,
 9342                    };
 9343
 9344                    if should_render || start == 0 || end == self.len {
 9345                        paint(window, cx);
 9346
 9347                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
 9348                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
 9349                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
 9350                            // Note that we need to make sure that the last one is actually adjacent
 9351                            if !should_render_last && last_end == start {
 9352                                paint_last(window, cx);
 9353                            }
 9354                        }
 9355                    }
 9356
 9357                    // Manually render anything within a selection
 9358                    let invisible_point = DisplayPoint::new(row, start as u32);
 9359                    if selection_ranges.iter().any(|region| {
 9360                        region.start <= invisible_point && invisible_point < region.end
 9361                    }) {
 9362                        paint(window, cx);
 9363                    }
 9364
 9365                    last_seen = Some((should_render, end, paint));
 9366                }
 9367            }
 9368        }
 9369    }
 9370
 9371    pub fn x_for_index(&self, index: usize) -> Pixels {
 9372        let mut fragment_start_x = Pixels::ZERO;
 9373        let mut fragment_start_index = 0;
 9374
 9375        for fragment in &self.fragments {
 9376            match fragment {
 9377                LineFragment::Text(shaped_line) => {
 9378                    let fragment_end_index = fragment_start_index + shaped_line.len;
 9379                    if index < fragment_end_index {
 9380                        return fragment_start_x
 9381                            + shaped_line.x_for_index(index - fragment_start_index);
 9382                    }
 9383                    fragment_start_x += shaped_line.width;
 9384                    fragment_start_index = fragment_end_index;
 9385                }
 9386                LineFragment::Element { len, size, .. } => {
 9387                    let fragment_end_index = fragment_start_index + len;
 9388                    if index < fragment_end_index {
 9389                        return fragment_start_x;
 9390                    }
 9391                    fragment_start_x += size.width;
 9392                    fragment_start_index = fragment_end_index;
 9393                }
 9394            }
 9395        }
 9396
 9397        fragment_start_x
 9398    }
 9399
 9400    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
 9401        let mut fragment_start_x = Pixels::ZERO;
 9402        let mut fragment_start_index = 0;
 9403
 9404        for fragment in &self.fragments {
 9405            match fragment {
 9406                LineFragment::Text(shaped_line) => {
 9407                    let fragment_end_x = fragment_start_x + shaped_line.width;
 9408                    if x < fragment_end_x {
 9409                        return Some(
 9410                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
 9411                        );
 9412                    }
 9413                    fragment_start_x = fragment_end_x;
 9414                    fragment_start_index += shaped_line.len;
 9415                }
 9416                LineFragment::Element { len, size, .. } => {
 9417                    let fragment_end_x = fragment_start_x + size.width;
 9418                    if x < fragment_end_x {
 9419                        return Some(fragment_start_index);
 9420                    }
 9421                    fragment_start_index += len;
 9422                    fragment_start_x = fragment_end_x;
 9423                }
 9424            }
 9425        }
 9426
 9427        None
 9428    }
 9429
 9430    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
 9431        let mut fragment_start_index = 0;
 9432
 9433        for fragment in &self.fragments {
 9434            match fragment {
 9435                LineFragment::Text(shaped_line) => {
 9436                    let fragment_end_index = fragment_start_index + shaped_line.len;
 9437                    if index < fragment_end_index {
 9438                        return shaped_line.font_id_for_index(index - fragment_start_index);
 9439                    }
 9440                    fragment_start_index = fragment_end_index;
 9441                }
 9442                LineFragment::Element { len, .. } => {
 9443                    let fragment_end_index = fragment_start_index + len;
 9444                    if index < fragment_end_index {
 9445                        return None;
 9446                    }
 9447                    fragment_start_index = fragment_end_index;
 9448                }
 9449            }
 9450        }
 9451
 9452        None
 9453    }
 9454
 9455    pub fn alignment_offset(&self, text_align: TextAlign, content_width: Pixels) -> Pixels {
 9456        let line_width = self.width;
 9457        match text_align {
 9458            TextAlign::Left => px(0.0),
 9459            TextAlign::Center => (content_width - line_width) / 2.0,
 9460            TextAlign::Right => content_width - line_width,
 9461        }
 9462    }
 9463}
 9464
 9465#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 9466enum Invisible {
 9467    /// A tab character
 9468    ///
 9469    /// A tab character is internally represented by spaces (configured by the user's tab width)
 9470    /// aligned to the nearest column, so it's necessary to store the start and end offset for
 9471    /// adjacency checks.
 9472    Tab {
 9473        line_start_offset: usize,
 9474        line_end_offset: usize,
 9475    },
 9476    Whitespace {
 9477        line_offset: usize,
 9478    },
 9479}
 9480
 9481impl EditorElement {
 9482    /// Returns the rem size to use when rendering the [`EditorElement`].
 9483    ///
 9484    /// This allows UI elements to scale based on the `buffer_font_size`.
 9485    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
 9486        match self.editor.read(cx).mode {
 9487            EditorMode::Full {
 9488                scale_ui_elements_with_buffer_font_size: true,
 9489                ..
 9490            }
 9491            | EditorMode::Minimap { .. } => {
 9492                let buffer_font_size = self.style.text.font_size;
 9493                match buffer_font_size {
 9494                    AbsoluteLength::Pixels(pixels) => {
 9495                        let rem_size_scale = {
 9496                            // Our default UI font size is 14px on a 16px base scale.
 9497                            // This means the default UI font size is 0.875rems.
 9498                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
 9499
 9500                            // We then determine the delta between a single rem and the default font
 9501                            // size scale.
 9502                            let default_font_size_delta = 1. - default_font_size_scale;
 9503
 9504                            // Finally, we add this delta to 1rem to get the scale factor that
 9505                            // should be used to scale up the UI.
 9506                            1. + default_font_size_delta
 9507                        };
 9508
 9509                        Some(pixels * rem_size_scale)
 9510                    }
 9511                    AbsoluteLength::Rems(rems) => {
 9512                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
 9513                    }
 9514                }
 9515            }
 9516            // We currently use single-line and auto-height editors in UI contexts,
 9517            // so we don't want to scale everything with the buffer font size, as it
 9518            // ends up looking off.
 9519            _ => None,
 9520        }
 9521    }
 9522
 9523    fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
 9524        if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
 9525            parent.upgrade()
 9526        } else {
 9527            Some(self.editor.clone())
 9528        }
 9529    }
 9530}
 9531
 9532#[derive(Default)]
 9533pub struct EditorRequestLayoutState {
 9534    // We use prepaint depth to limit the number of times prepaint is
 9535    // called recursively. We need this so that we can update stale
 9536    // data for e.g. block heights in block map.
 9537    prepaint_depth: Rc<Cell<usize>>,
 9538}
 9539
 9540impl EditorRequestLayoutState {
 9541    // In ideal conditions we only need one more subsequent prepaint call for resize to take effect.
 9542    // i.e. MAX_PREPAINT_DEPTH = 2, but since moving blocks inline (place_near), more lines from
 9543    // below get exposed, and we end up querying blocks for those lines too in subsequent renders.
 9544    // Setting MAX_PREPAINT_DEPTH = 3, passes all tests. Just to be on the safe side we set it to 5, so
 9545    // that subsequent shrinking does not lead to incorrect block placing.
 9546    const MAX_PREPAINT_DEPTH: usize = 5;
 9547
 9548    fn increment_prepaint_depth(&self) -> EditorPrepaintGuard {
 9549        let depth = self.prepaint_depth.get();
 9550        self.prepaint_depth.set(depth + 1);
 9551        EditorPrepaintGuard {
 9552            prepaint_depth: self.prepaint_depth.clone(),
 9553        }
 9554    }
 9555
 9556    fn has_remaining_prepaint_depth(&self) -> bool {
 9557        self.prepaint_depth.get() < Self::MAX_PREPAINT_DEPTH
 9558    }
 9559}
 9560
 9561struct EditorPrepaintGuard {
 9562    prepaint_depth: Rc<Cell<usize>>,
 9563}
 9564
 9565impl Drop for EditorPrepaintGuard {
 9566    fn drop(&mut self) {
 9567        let depth = self.prepaint_depth.get();
 9568        self.prepaint_depth.set(depth.saturating_sub(1));
 9569    }
 9570}
 9571
 9572impl Element for EditorElement {
 9573    type RequestLayoutState = EditorRequestLayoutState;
 9574    type PrepaintState = EditorLayout;
 9575
 9576    fn id(&self) -> Option<ElementId> {
 9577        None
 9578    }
 9579
 9580    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
 9581        None
 9582    }
 9583
 9584    fn request_layout(
 9585        &mut self,
 9586        _: Option<&GlobalElementId>,
 9587        _inspector_id: Option<&gpui::InspectorElementId>,
 9588        window: &mut Window,
 9589        cx: &mut App,
 9590    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
 9591        let rem_size = self.rem_size(cx);
 9592        window.with_rem_size(rem_size, |window| {
 9593            self.editor.update(cx, |editor, cx| {
 9594                editor.set_style(self.style.clone(), window, cx);
 9595
 9596                let layout_id = match editor.mode {
 9597                    EditorMode::SingleLine => {
 9598                        let rem_size = window.rem_size();
 9599                        let height = self.style.text.line_height_in_pixels(rem_size);
 9600                        let mut style = Style::default();
 9601                        style.size.height = height.into();
 9602                        style.size.width = relative(1.).into();
 9603                        window.request_layout(style, None, cx)
 9604                    }
 9605                    EditorMode::AutoHeight {
 9606                        min_lines,
 9607                        max_lines,
 9608                    } => {
 9609                        let editor_handle = cx.entity();
 9610                        window.request_measured_layout(
 9611                            Style::default(),
 9612                            move |known_dimensions, available_space, window, cx| {
 9613                                editor_handle
 9614                                    .update(cx, |editor, cx| {
 9615                                        compute_auto_height_layout(
 9616                                            editor,
 9617                                            min_lines,
 9618                                            max_lines,
 9619                                            known_dimensions,
 9620                                            available_space.width,
 9621                                            window,
 9622                                            cx,
 9623                                        )
 9624                                    })
 9625                                    .unwrap_or_default()
 9626                            },
 9627                        )
 9628                    }
 9629                    EditorMode::Minimap { .. } => {
 9630                        let mut style = Style::default();
 9631                        style.size.width = relative(1.).into();
 9632                        style.size.height = relative(1.).into();
 9633                        window.request_layout(style, None, cx)
 9634                    }
 9635                    EditorMode::Full {
 9636                        sizing_behavior, ..
 9637                    } => {
 9638                        let mut style = Style::default();
 9639                        style.size.width = relative(1.).into();
 9640                        if sizing_behavior == SizingBehavior::SizeByContent {
 9641                            let snapshot = editor.snapshot(window, cx);
 9642                            let line_height =
 9643                                self.style.text.line_height_in_pixels(window.rem_size());
 9644                            let scroll_height =
 9645                                (snapshot.max_point().row().next_row().0 as f32) * line_height;
 9646                            style.size.height = scroll_height.into();
 9647                        } else {
 9648                            style.size.height = relative(1.).into();
 9649                        }
 9650                        window.request_layout(style, None, cx)
 9651                    }
 9652                };
 9653
 9654                (layout_id, EditorRequestLayoutState::default())
 9655            })
 9656        })
 9657    }
 9658
 9659    fn prepaint(
 9660        &mut self,
 9661        _: Option<&GlobalElementId>,
 9662        _inspector_id: Option<&gpui::InspectorElementId>,
 9663        bounds: Bounds<Pixels>,
 9664        request_layout: &mut Self::RequestLayoutState,
 9665        window: &mut Window,
 9666        cx: &mut App,
 9667    ) -> Self::PrepaintState {
 9668        let _prepaint_depth_guard = request_layout.increment_prepaint_depth();
 9669        let text_style = TextStyleRefinement {
 9670            font_size: Some(self.style.text.font_size),
 9671            line_height: Some(self.style.text.line_height),
 9672            ..Default::default()
 9673        };
 9674
 9675        let is_minimap = self.editor.read(cx).mode.is_minimap();
 9676        let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
 9677
 9678        if !is_minimap {
 9679            let focus_handle = self.editor.focus_handle(cx);
 9680            window.set_view_id(self.editor.entity_id());
 9681            window.set_focus_handle(&focus_handle, cx);
 9682        }
 9683
 9684        let rem_size = self.rem_size(cx);
 9685        window.with_rem_size(rem_size, |window| {
 9686            window.with_text_style(Some(text_style), |window| {
 9687                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 9688                    let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
 9689                        (editor.snapshot(window, cx), editor.read_only(cx))
 9690                    });
 9691                    let style = &self.style;
 9692
 9693                    let rem_size = window.rem_size();
 9694                    let font_id = window.text_system().resolve_font(&style.text.font());
 9695                    let font_size = style.text.font_size.to_pixels(rem_size);
 9696                    let line_height = style.text.line_height_in_pixels(rem_size);
 9697                    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
 9698                    let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
 9699                    let em_layout_width = window.text_system().em_layout_width(font_id, font_size);
 9700                    let glyph_grid_cell = size(em_advance, line_height);
 9701
 9702                    let gutter_dimensions =
 9703                        snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
 9704                    let text_width = bounds.size.width - gutter_dimensions.width;
 9705
 9706                    let settings = EditorSettings::get_global(cx);
 9707                    let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
 9708                    let vertical_scrollbar_width = (scrollbars_shown
 9709                        && settings.scrollbar.axes.vertical
 9710                        && self.editor.read(cx).show_scrollbars.vertical)
 9711                        .then_some(style.scrollbar_width)
 9712                        .unwrap_or_default();
 9713                    let minimap_width = self
 9714                        .get_minimap_width(
 9715                            &settings.minimap,
 9716                            scrollbars_shown,
 9717                            text_width,
 9718                            em_width,
 9719                            font_size,
 9720                            rem_size,
 9721                            cx,
 9722                        )
 9723                        .unwrap_or_default();
 9724
 9725                    let right_margin = minimap_width + vertical_scrollbar_width;
 9726
 9727                    let extended_right = 2 * em_width + right_margin;
 9728                    let editor_width = text_width - gutter_dimensions.margin - extended_right;
 9729                    let editor_margins = EditorMargins {
 9730                        gutter: gutter_dimensions,
 9731                        right: right_margin,
 9732                        extended_right,
 9733                    };
 9734
 9735                    snapshot = self.editor.update(cx, |editor, cx| {
 9736                        editor.last_bounds = Some(bounds);
 9737                        editor.gutter_dimensions = gutter_dimensions;
 9738                        editor.set_visible_line_count(
 9739                            (bounds.size.height / line_height) as f64,
 9740                            window,
 9741                            cx,
 9742                        );
 9743                        editor.set_visible_column_count(f64::from(editor_width / em_advance));
 9744
 9745                        if matches!(
 9746                            editor.mode,
 9747                            EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
 9748                        ) {
 9749                            snapshot
 9750                        } else {
 9751                            let wrap_width = calculate_wrap_width(
 9752                                editor.soft_wrap_mode(cx),
 9753                                editor_width,
 9754                                em_layout_width,
 9755                            );
 9756
 9757                            if editor.set_wrap_width(wrap_width, cx) {
 9758                                editor.snapshot(window, cx)
 9759                            } else {
 9760                                snapshot
 9761                            }
 9762                        }
 9763                    });
 9764
 9765                    let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
 9766                    let gutter_hitbox = window.insert_hitbox(
 9767                        gutter_bounds(bounds, gutter_dimensions),
 9768                        HitboxBehavior::Normal,
 9769                    );
 9770                    let text_hitbox = window.insert_hitbox(
 9771                        Bounds {
 9772                            origin: gutter_hitbox.top_right(),
 9773                            size: size(text_width, bounds.size.height),
 9774                        },
 9775                        HitboxBehavior::Normal,
 9776                    );
 9777
 9778                    // Offset the content_bounds from the text_bounds by the gutter margin (which
 9779                    // is roughly half a character wide) to make hit testing work more like how we want.
 9780                    let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
 9781                    let content_origin = text_hitbox.origin + content_offset;
 9782
 9783                    let height_in_lines = f64::from(bounds.size.height / line_height);
 9784                    let max_row = snapshot.max_point().row().as_f64();
 9785
 9786                    // Calculate how much of the editor is clipped by parent containers (e.g., List).
 9787                    // This allows us to only render lines that are actually visible, which is
 9788                    // critical for performance when large AutoHeight editors are inside Lists.
 9789                    let visible_bounds = window.content_mask().bounds;
 9790                    let clipped_top = (visible_bounds.origin.y - bounds.origin.y).max(px(0.));
 9791                    let clipped_top_in_lines = f64::from(clipped_top / line_height);
 9792                    let visible_height_in_lines =
 9793                        f64::from(visible_bounds.size.height / line_height);
 9794
 9795                    // The max scroll position for the top of the window
 9796                    let scroll_beyond_last_line = self.editor.read(cx).scroll_beyond_last_line(cx);
 9797                    let max_scroll_top = match scroll_beyond_last_line {
 9798                        ScrollBeyondLastLine::OnePage => max_row,
 9799                        ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
 9800                        ScrollBeyondLastLine::VerticalScrollMargin => {
 9801                            let settings = EditorSettings::get_global(cx);
 9802                            (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
 9803                                .max(0.)
 9804                        }
 9805                    };
 9806
 9807                    let (
 9808                        autoscroll_request,
 9809                        autoscroll_containing_element,
 9810                        needs_horizontal_autoscroll,
 9811                    ) = self.editor.update(cx, |editor, cx| {
 9812                        let autoscroll_request = editor.scroll_manager.take_autoscroll_request();
 9813
 9814                        let autoscroll_containing_element =
 9815                            autoscroll_request.is_some() || editor.has_pending_selection();
 9816
 9817                        let (needs_horizontal_autoscroll, was_scrolled) = editor
 9818                            .autoscroll_vertically(
 9819                                bounds,
 9820                                line_height,
 9821                                max_scroll_top,
 9822                                autoscroll_request,
 9823                                window,
 9824                                cx,
 9825                            );
 9826                        if was_scrolled.0 {
 9827                            snapshot = editor.snapshot(window, cx);
 9828                        }
 9829                        (
 9830                            autoscroll_request,
 9831                            autoscroll_containing_element,
 9832                            needs_horizontal_autoscroll,
 9833                        )
 9834                    });
 9835
 9836                    let mut scroll_position = snapshot.scroll_position();
 9837                    // The scroll position is a fractional point, the whole number of which represents
 9838                    // the top of the window in terms of display rows.
 9839                    // We add clipped_top_in_lines to skip rows that are clipped by parent containers,
 9840                    // but we don't modify scroll_position itself since the parent handles positioning.
 9841                    let max_row = snapshot.max_point().row();
 9842                    let start_row = cmp::min(
 9843                        DisplayRow((scroll_position.y + clipped_top_in_lines).floor() as u32),
 9844                        max_row,
 9845                    );
 9846                    let end_row = cmp::min(
 9847                        (scroll_position.y + clipped_top_in_lines + visible_height_in_lines).ceil()
 9848                            as u32,
 9849                        max_row.next_row().0,
 9850                    );
 9851                    let end_row = DisplayRow(end_row);
 9852
 9853                    let row_infos = snapshot // note we only get the visual range
 9854                        .row_infos(start_row)
 9855                        .take((start_row..end_row).len())
 9856                        .collect::<Vec<RowInfo>>();
 9857                    let is_row_soft_wrapped = |row: usize| {
 9858                        row_infos
 9859                            .get(row)
 9860                            .is_none_or(|info| info.buffer_row.is_none())
 9861                    };
 9862
 9863                    let start_anchor = if start_row == Default::default() {
 9864                        Anchor::Min
 9865                    } else {
 9866                        snapshot.buffer_snapshot().anchor_before(
 9867                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
 9868                        )
 9869                    };
 9870                    let end_anchor = if end_row > max_row {
 9871                        Anchor::Max
 9872                    } else {
 9873                        snapshot.buffer_snapshot().anchor_before(
 9874                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
 9875                        )
 9876                    };
 9877
 9878                    let mut highlighted_rows = self
 9879                        .editor
 9880                        .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
 9881
 9882                    let is_light = cx.theme().appearance().is_light();
 9883
 9884                    let mut highlighted_ranges = self
 9885                        .editor_with_selections(cx)
 9886                        .map(|editor| {
 9887                            if editor == self.editor {
 9888                                editor.read(cx).background_highlights_in_range(
 9889                                    start_anchor..end_anchor,
 9890                                    &snapshot.display_snapshot,
 9891                                    cx.theme(),
 9892                                )
 9893                            } else {
 9894                                editor.update(cx, |editor, cx| {
 9895                                    let snapshot = editor.snapshot(window, cx);
 9896                                    let start_anchor = if start_row == Default::default() {
 9897                                        Anchor::Min
 9898                                    } else {
 9899                                        snapshot.buffer_snapshot().anchor_before(
 9900                                            DisplayPoint::new(start_row, 0)
 9901                                                .to_offset(&snapshot, Bias::Left),
 9902                                        )
 9903                                    };
 9904                                    let end_anchor = if end_row > max_row {
 9905                                        Anchor::Max
 9906                                    } else {
 9907                                        snapshot.buffer_snapshot().anchor_before(
 9908                                            DisplayPoint::new(end_row, 0)
 9909                                                .to_offset(&snapshot, Bias::Right),
 9910                                        )
 9911                                    };
 9912
 9913                                    editor.background_highlights_in_range(
 9914                                        start_anchor..end_anchor,
 9915                                        &snapshot.display_snapshot,
 9916                                        cx.theme(),
 9917                                    )
 9918                                })
 9919                            }
 9920                        })
 9921                        .unwrap_or_default();
 9922
 9923                    for (ix, row_info) in row_infos.iter().enumerate() {
 9924                        let Some(diff_status) = row_info.diff_status else {
 9925                            continue;
 9926                        };
 9927
 9928                        let background_color = match diff_status.kind {
 9929                            DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
 9930                            DiffHunkStatusKind::Deleted => {
 9931                                cx.theme().colors().version_control_deleted
 9932                            }
 9933                            DiffHunkStatusKind::Modified => {
 9934                                debug_panic!("modified diff status for row info");
 9935                                continue;
 9936                            }
 9937                        };
 9938
 9939                        let hunk_opacity = if is_light { 0.16 } else { 0.12 };
 9940
 9941                        let hollow_highlight = LineHighlight {
 9942                            background: (background_color.opacity(if is_light {
 9943                                0.08
 9944                            } else {
 9945                                0.06
 9946                            }))
 9947                            .into(),
 9948                            border: Some(if is_light {
 9949                                background_color.opacity(0.48)
 9950                            } else {
 9951                                background_color.opacity(0.36)
 9952                            }),
 9953                            include_gutter: true,
 9954                            type_id: None,
 9955                        };
 9956
 9957                        let filled_highlight = LineHighlight {
 9958                            background: solid_background(background_color.opacity(hunk_opacity)),
 9959                            border: None,
 9960                            include_gutter: true,
 9961                            type_id: None,
 9962                        };
 9963
 9964                        let background = if Self::diff_hunk_hollow(diff_status, cx) {
 9965                            hollow_highlight
 9966                        } else {
 9967                            filled_highlight
 9968                        };
 9969
 9970                        let base_display_point =
 9971                            DisplayPoint::new(start_row + DisplayRow(ix as u32), 0);
 9972
 9973                        highlighted_rows
 9974                            .entry(base_display_point.row())
 9975                            .or_insert(background);
 9976                    }
 9977
 9978                    // Add diff review drag selection highlight to text area
 9979                    if let Some(drag_state) = &self.editor.read(cx).diff_review_drag_state {
 9980                        let range = drag_state.row_range(&snapshot.display_snapshot);
 9981                        let start_row = range.start().0;
 9982                        let end_row = range.end().0;
 9983                        let drag_highlight_color =
 9984                            cx.theme().colors().editor_active_line_background;
 9985                        let drag_highlight = LineHighlight {
 9986                            background: solid_background(drag_highlight_color),
 9987                            border: Some(cx.theme().colors().border_focused),
 9988                            include_gutter: true,
 9989                            type_id: None,
 9990                        };
 9991                        for row_num in start_row..=end_row {
 9992                            highlighted_rows
 9993                                .entry(DisplayRow(row_num))
 9994                                .or_insert(drag_highlight);
 9995                        }
 9996                    }
 9997
 9998                    let highlighted_gutter_ranges =
 9999                        self.editor.read(cx).gutter_highlights_in_range(
10000                            start_anchor..end_anchor,
10001                            &snapshot.display_snapshot,
10002                            cx,
10003                        );
10004
10005                    let document_colors = self
10006                        .editor
10007                        .read(cx)
10008                        .colors
10009                        .as_ref()
10010                        .map(|colors| colors.editor_display_highlights(&snapshot));
10011                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
10012                        start_anchor..end_anchor,
10013                        &snapshot.display_snapshot,
10014                        cx,
10015                    );
10016
10017                    let (local_selections, selected_buffer_ids, latest_selection_anchors): (
10018                        Vec<Selection<Point>>,
10019                        Vec<BufferId>,
10020                        HashMap<BufferId, Anchor>,
10021                    ) = self
10022                        .editor_with_selections(cx)
10023                        .map(|editor| {
10024                            editor.update(cx, |editor, cx| {
10025                                let all_selections =
10026                                    editor.selections.all::<Point>(&snapshot.display_snapshot);
10027                                let all_anchor_selections =
10028                                    editor.selections.all_anchors(&snapshot.display_snapshot);
10029                                let selected_buffer_ids =
10030                                    if editor.buffer_kind(cx) == ItemBufferKind::Singleton {
10031                                        Vec::new()
10032                                    } else {
10033                                        let mut selected_buffer_ids =
10034                                            Vec::with_capacity(all_selections.len());
10035
10036                                        for selection in all_selections {
10037                                            for buffer_id in snapshot
10038                                                .buffer_snapshot()
10039                                                .buffer_ids_for_range(selection.range())
10040                                            {
10041                                                if selected_buffer_ids.last() != Some(&buffer_id) {
10042                                                    selected_buffer_ids.push(buffer_id);
10043                                                }
10044                                            }
10045                                        }
10046
10047                                        selected_buffer_ids
10048                                    };
10049
10050                                let mut selections = editor.selections.disjoint_in_range(
10051                                    start_anchor..end_anchor,
10052                                    &snapshot.display_snapshot,
10053                                );
10054                                selections
10055                                    .extend(editor.selections.pending(&snapshot.display_snapshot));
10056
10057                                let mut anchors_by_buffer: HashMap<BufferId, (usize, Anchor)> =
10058                                    HashMap::default();
10059                                for selection in all_anchor_selections.iter() {
10060                                    let head = selection.head();
10061                                    if let Some((text_anchor, _)) =
10062                                        snapshot.buffer_snapshot().anchor_to_buffer_anchor(head)
10063                                    {
10064                                        anchors_by_buffer
10065                                            .entry(text_anchor.buffer_id)
10066                                            .and_modify(|(latest_id, latest_anchor)| {
10067                                                if selection.id > *latest_id {
10068                                                    *latest_id = selection.id;
10069                                                    *latest_anchor = head;
10070                                                }
10071                                            })
10072                                            .or_insert((selection.id, head));
10073                                    }
10074                                }
10075                                let latest_selection_anchors = anchors_by_buffer
10076                                    .into_iter()
10077                                    .map(|(buffer_id, (_, anchor))| (buffer_id, anchor))
10078                                    .collect();
10079
10080                                (selections, selected_buffer_ids, latest_selection_anchors)
10081                            })
10082                        })
10083                        .unwrap_or_else(|| (Vec::new(), Vec::new(), HashMap::default()));
10084
10085                    let (selections, mut active_rows, newest_selection_head) = self
10086                        .layout_selections(
10087                            start_anchor,
10088                            end_anchor,
10089                            &local_selections,
10090                            &snapshot,
10091                            start_row,
10092                            end_row,
10093                            window,
10094                            cx,
10095                        );
10096
10097                    // relative rows are based on newest selection, even outside the visible area
10098                    let current_selection_head = self.editor.update(cx, |editor, cx| {
10099                        (editor.selections.count() != 0).then(|| {
10100                            let newest = editor
10101                                .selections
10102                                .newest::<Point>(&editor.display_snapshot(cx));
10103
10104                            SelectionLayout::new(
10105                                newest,
10106                                editor.selections.line_mode(),
10107                                editor.cursor_offset_on_selection,
10108                                editor.cursor_shape,
10109                                &snapshot,
10110                                true,
10111                                true,
10112                                None,
10113                            )
10114                            .head
10115                            .row()
10116                        })
10117                    });
10118
10119                    let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
10120                        editor.active_breakpoints(start_row..end_row, window, cx)
10121                    });
10122                    for (display_row, (_, bp, state)) in &breakpoint_rows {
10123                        if bp.is_enabled() && state.is_none_or(|s| s.verified) {
10124                            active_rows.entry(*display_row).or_default().breakpoint = true;
10125                        }
10126                    }
10127
10128                    let line_numbers = self.layout_line_numbers(
10129                        Some(&gutter_hitbox),
10130                        gutter_dimensions,
10131                        line_height,
10132                        scroll_position,
10133                        start_row..end_row,
10134                        &row_infos,
10135                        &active_rows,
10136                        current_selection_head,
10137                        &snapshot,
10138                        window,
10139                        cx,
10140                    );
10141
10142                    // We add the gutter breakpoint indicator to breakpoint_rows after painting
10143                    // line numbers so we don't paint a line number debug accent color if a user
10144                    // has their mouse over that line when a breakpoint isn't there
10145                    self.editor.update(cx, |editor, _| {
10146                        if let Some(phantom_breakpoint) = &mut editor
10147                            .gutter_breakpoint_indicator
10148                            .0
10149                            .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
10150                        {
10151                            // Is there a non-phantom breakpoint on this line?
10152                            phantom_breakpoint.collides_with_existing_breakpoint = true;
10153                            breakpoint_rows
10154                                .entry(phantom_breakpoint.display_row)
10155                                .or_insert_with(|| {
10156                                    let position = snapshot.display_point_to_anchor(
10157                                        DisplayPoint::new(phantom_breakpoint.display_row, 0),
10158                                        Bias::Right,
10159                                    );
10160                                    let breakpoint = Breakpoint::new_standard();
10161                                    phantom_breakpoint.collides_with_existing_breakpoint = false;
10162                                    (position, breakpoint, None)
10163                                });
10164                        }
10165                    });
10166
10167                    let mut expand_toggles =
10168                        window.with_element_namespace("expand_toggles", |window| {
10169                            self.layout_expand_toggles(
10170                                &gutter_hitbox,
10171                                gutter_dimensions,
10172                                em_width,
10173                                line_height,
10174                                scroll_position,
10175                                &row_infos,
10176                                window,
10177                                cx,
10178                            )
10179                        });
10180
10181                    let mut crease_toggles =
10182                        window.with_element_namespace("crease_toggles", |window| {
10183                            self.layout_crease_toggles(
10184                                start_row..end_row,
10185                                &row_infos,
10186                                &active_rows,
10187                                &snapshot,
10188                                window,
10189                                cx,
10190                            )
10191                        });
10192                    let crease_trailers =
10193                        window.with_element_namespace("crease_trailers", |window| {
10194                            self.layout_crease_trailers(
10195                                row_infos.iter().cloned(),
10196                                &snapshot,
10197                                window,
10198                                cx,
10199                            )
10200                        });
10201
10202                    let display_hunks = self.layout_gutter_diff_hunks(
10203                        line_height,
10204                        &gutter_hitbox,
10205                        start_row..end_row,
10206                        &snapshot,
10207                        window,
10208                        cx,
10209                    );
10210
10211                    Self::layout_word_diff_highlights(
10212                        &display_hunks,
10213                        &row_infos,
10214                        start_row,
10215                        &snapshot,
10216                        &mut highlighted_ranges,
10217                        cx,
10218                    );
10219
10220                    let merged_highlighted_ranges =
10221                        if let Some((_, colors)) = document_colors.as_ref() {
10222                            &highlighted_ranges
10223                                .clone()
10224                                .into_iter()
10225                                .chain(colors.clone())
10226                                .collect()
10227                        } else {
10228                            &highlighted_ranges
10229                        };
10230                    let bg_segments_per_row = Self::bg_segments_per_row(
10231                        start_row..end_row,
10232                        &selections,
10233                        &merged_highlighted_ranges,
10234                        self.style.background,
10235                    );
10236
10237                    let mut line_layouts = Self::layout_lines(
10238                        start_row..end_row,
10239                        &snapshot,
10240                        &self.style,
10241                        editor_width,
10242                        is_row_soft_wrapped,
10243                        &bg_segments_per_row,
10244                        window,
10245                        cx,
10246                    );
10247                    let new_renderer_widths = (!is_minimap).then(|| {
10248                        line_layouts
10249                            .iter()
10250                            .flat_map(|layout| &layout.fragments)
10251                            .filter_map(|fragment| {
10252                                if let LineFragment::Element { id, size, .. } = fragment {
10253                                    Some((*id, size.width))
10254                                } else {
10255                                    None
10256                                }
10257                            })
10258                    });
10259                    let renderer_widths_changed = request_layout.has_remaining_prepaint_depth()
10260                        && new_renderer_widths.is_some_and(|new_renderer_widths| {
10261                            self.editor.update(cx, |editor, cx| {
10262                                editor.update_renderer_widths(new_renderer_widths, cx)
10263                            })
10264                        });
10265                    if renderer_widths_changed {
10266                        return self.prepaint(
10267                            None,
10268                            _inspector_id,
10269                            bounds,
10270                            request_layout,
10271                            window,
10272                            cx,
10273                        );
10274                    }
10275
10276                    let longest_line_blame_width = self
10277                        .editor
10278                        .update(cx, |editor, cx| {
10279                            if !editor.show_git_blame_inline {
10280                                return None;
10281                            }
10282                            let blame = editor.blame.as_ref()?;
10283                            let (_, blame_entry) = blame
10284                                .update(cx, |blame, cx| {
10285                                    let row_infos =
10286                                        snapshot.row_infos(snapshot.longest_row()).next()?;
10287                                    blame.blame_for_rows(&[row_infos], cx).next()
10288                                })
10289                                .flatten()?;
10290                            let mut element = render_inline_blame_entry(blame_entry, style, cx)?;
10291                            let inline_blame_padding =
10292                                ProjectSettings::get_global(cx).git.inline_blame.padding as f32
10293                                    * em_advance;
10294                            Some(
10295                                element
10296                                    .layout_as_root(AvailableSpace::min_size(), window, cx)
10297                                    .width
10298                                    + inline_blame_padding,
10299                            )
10300                        })
10301                        .unwrap_or(Pixels::ZERO);
10302
10303                    let longest_line_width = layout_line(
10304                        snapshot.longest_row(),
10305                        &snapshot,
10306                        style,
10307                        editor_width,
10308                        is_row_soft_wrapped,
10309                        window,
10310                        cx,
10311                    )
10312                    .width;
10313
10314                    let scrollbar_layout_information = ScrollbarLayoutInformation::new(
10315                        text_hitbox.bounds,
10316                        glyph_grid_cell,
10317                        size(
10318                            longest_line_width,
10319                            Pixels::from(max_row.as_f64() * f64::from(line_height)),
10320                        ),
10321                        longest_line_blame_width,
10322                        EditorSettings::get_global(cx),
10323                        scroll_beyond_last_line,
10324                    );
10325
10326                    let mut scroll_width = scrollbar_layout_information.scroll_range.width;
10327
10328                    let sticky_header_excerpt = if snapshot.buffer_snapshot().show_headers() {
10329                        snapshot.sticky_header_excerpt(scroll_position.y)
10330                    } else {
10331                        None
10332                    };
10333                    let sticky_header_excerpt_id = sticky_header_excerpt
10334                        .as_ref()
10335                        .map(|top| top.excerpt.buffer_id());
10336
10337                    let buffer = snapshot.buffer_snapshot();
10338                    let start_buffer_row = MultiBufferRow(start_anchor.to_point(&buffer).row);
10339                    let end_buffer_row = MultiBufferRow(end_anchor.to_point(&buffer).row);
10340
10341                    let preliminary_scroll_pixel_position = point(
10342                        scroll_position.x * f64::from(em_layout_width),
10343                        scroll_position.y * f64::from(line_height),
10344                    );
10345                    let indent_guides = self.layout_indent_guides(
10346                        content_origin,
10347                        text_hitbox.origin,
10348                        start_buffer_row..end_buffer_row,
10349                        preliminary_scroll_pixel_position,
10350                        line_height,
10351                        &snapshot,
10352                        window,
10353                        cx,
10354                    );
10355                    let indent_guides_for_spacers = indent_guides.clone();
10356
10357                    let blocks = (!is_minimap)
10358                        .then(|| {
10359                            window.with_element_namespace("blocks", |window| {
10360                                self.render_blocks(
10361                                    start_row..end_row,
10362                                    &snapshot,
10363                                    &hitbox,
10364                                    &text_hitbox,
10365                                    editor_width,
10366                                    &mut scroll_width,
10367                                    &editor_margins,
10368                                    em_width,
10369                                    gutter_dimensions.full_width(),
10370                                    line_height,
10371                                    &mut line_layouts,
10372                                    &local_selections,
10373                                    &selected_buffer_ids,
10374                                    &latest_selection_anchors,
10375                                    is_row_soft_wrapped,
10376                                    sticky_header_excerpt_id,
10377                                    &indent_guides_for_spacers,
10378                                    window,
10379                                    cx,
10380                                )
10381                            })
10382                        })
10383                        .unwrap_or_default();
10384                    let RenderBlocksOutput {
10385                        non_spacer_blocks: mut blocks,
10386                        mut spacer_blocks,
10387                        row_block_types,
10388                        resized_blocks,
10389                    } = blocks;
10390                    if let Some(resized_blocks) = resized_blocks {
10391                        if request_layout.has_remaining_prepaint_depth() {
10392                            self.editor.update(cx, |editor, cx| {
10393                                editor.resize_blocks(
10394                                    resized_blocks,
10395                                    autoscroll_request.map(|(autoscroll, _)| autoscroll),
10396                                    cx,
10397                                )
10398                            });
10399                            return self.prepaint(
10400                                None,
10401                                _inspector_id,
10402                                bounds,
10403                                request_layout,
10404                                window,
10405                                cx,
10406                            );
10407                        } else {
10408                            debug_panic!(
10409                                "dropping block resize because prepaint depth \
10410                                 limit was reached"
10411                            );
10412                        }
10413                    }
10414
10415                    let sticky_buffer_header = if self.should_show_buffer_headers() {
10416                        sticky_header_excerpt.map(|sticky_header_excerpt| {
10417                            window.with_element_namespace("blocks", |window| {
10418                                self.layout_sticky_buffer_header(
10419                                    sticky_header_excerpt,
10420                                    scroll_position,
10421                                    line_height,
10422                                    right_margin,
10423                                    &snapshot,
10424                                    &hitbox,
10425                                    &selected_buffer_ids,
10426                                    &blocks,
10427                                    &latest_selection_anchors,
10428                                    window,
10429                                    cx,
10430                                )
10431                            })
10432                        })
10433                    } else {
10434                        None
10435                    };
10436
10437                    let scroll_max: gpui::Point<ScrollPixelOffset> = point(
10438                        ScrollPixelOffset::from(
10439                            ((scroll_width - editor_width) / em_layout_width).max(0.0),
10440                        ),
10441                        max_scroll_top,
10442                    );
10443
10444                    self.editor.update(cx, |editor, cx| {
10445                        if editor.scroll_manager.clamp_scroll_left(scroll_max.x, cx) {
10446                            scroll_position.x = scroll_max.x.min(scroll_position.x);
10447                        }
10448
10449                        if needs_horizontal_autoscroll.0
10450                            && let Some(new_scroll_position) = editor.autoscroll_horizontally(
10451                                start_row,
10452                                editor_width,
10453                                scroll_width,
10454                                em_advance,
10455                                &line_layouts,
10456                                autoscroll_request,
10457                                window,
10458                                cx,
10459                            )
10460                        {
10461                            scroll_position = new_scroll_position;
10462                        }
10463                    });
10464
10465                    let scroll_pixel_position = point(
10466                        scroll_position.x * f64::from(em_layout_width),
10467                        scroll_position.y * f64::from(line_height),
10468                    );
10469                    let sticky_headers = if !is_minimap
10470                        && is_singleton
10471                        && EditorSettings::get_global(cx).sticky_scroll.enabled
10472                    {
10473                        let relative = self.editor.read(cx).relative_line_numbers(cx);
10474                        self.layout_sticky_headers(
10475                            &snapshot,
10476                            editor_width,
10477                            is_row_soft_wrapped,
10478                            line_height,
10479                            scroll_pixel_position,
10480                            content_origin,
10481                            &gutter_dimensions,
10482                            &gutter_hitbox,
10483                            &text_hitbox,
10484                            relative,
10485                            current_selection_head,
10486                            window,
10487                            cx,
10488                        )
10489                    } else {
10490                        None
10491                    };
10492                    self.editor.update(cx, |editor, _| {
10493                        editor.scroll_manager.set_sticky_header_line_count(
10494                            sticky_headers.as_ref().map_or(0, |h| h.lines.len()),
10495                        );
10496                    });
10497                    let indent_guides =
10498                        if scroll_pixel_position != preliminary_scroll_pixel_position {
10499                            self.layout_indent_guides(
10500                                content_origin,
10501                                text_hitbox.origin,
10502                                start_buffer_row..end_buffer_row,
10503                                scroll_pixel_position,
10504                                line_height,
10505                                &snapshot,
10506                                window,
10507                                cx,
10508                            )
10509                        } else {
10510                            indent_guides
10511                        };
10512
10513                    let crease_trailers =
10514                        window.with_element_namespace("crease_trailers", |window| {
10515                            self.prepaint_crease_trailers(
10516                                crease_trailers,
10517                                &line_layouts,
10518                                line_height,
10519                                content_origin,
10520                                scroll_pixel_position,
10521                                em_width,
10522                                window,
10523                                cx,
10524                            )
10525                        });
10526
10527                    let (edit_prediction_popover, edit_prediction_popover_origin) = self
10528                        .editor
10529                        .update(cx, |editor, cx| {
10530                            editor.render_edit_prediction_popover(
10531                                &text_hitbox.bounds,
10532                                content_origin,
10533                                right_margin,
10534                                &snapshot,
10535                                start_row..end_row,
10536                                scroll_position.y,
10537                                scroll_position.y + height_in_lines,
10538                                &line_layouts,
10539                                line_height,
10540                                scroll_position,
10541                                scroll_pixel_position,
10542                                newest_selection_head,
10543                                editor_width,
10544                                style,
10545                                window,
10546                                cx,
10547                            )
10548                        })
10549                        .unzip();
10550
10551                    let mut inline_diagnostics = self.layout_inline_diagnostics(
10552                        &line_layouts,
10553                        &crease_trailers,
10554                        &row_block_types,
10555                        content_origin,
10556                        scroll_position,
10557                        scroll_pixel_position,
10558                        edit_prediction_popover_origin,
10559                        start_row,
10560                        end_row,
10561                        line_height,
10562                        em_width,
10563                        style,
10564                        window,
10565                        cx,
10566                    );
10567
10568                    let mut inline_blame_layout = None;
10569                    let mut inline_code_actions = None;
10570                    if let Some(newest_selection_head) = newest_selection_head {
10571                        let display_row = newest_selection_head.row();
10572                        if (start_row..end_row).contains(&display_row)
10573                            && !row_block_types.contains_key(&display_row)
10574                        {
10575                            inline_code_actions = self.layout_inline_code_actions(
10576                                newest_selection_head,
10577                                content_origin,
10578                                scroll_position,
10579                                scroll_pixel_position,
10580                                line_height,
10581                                &snapshot,
10582                                window,
10583                                cx,
10584                            );
10585
10586                            let line_ix = display_row.minus(start_row) as usize;
10587                            if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
10588                                row_infos.get(line_ix),
10589                                line_layouts.get(line_ix),
10590                                crease_trailers.get(line_ix),
10591                            ) {
10592                                let crease_trailer_layout = crease_trailer.as_ref();
10593                                if let Some(layout) = self.layout_inline_blame(
10594                                    display_row,
10595                                    row_info,
10596                                    line_layout,
10597                                    crease_trailer_layout,
10598                                    em_width,
10599                                    content_origin,
10600                                    scroll_position,
10601                                    scroll_pixel_position,
10602                                    line_height,
10603                                    window,
10604                                    cx,
10605                                ) {
10606                                    inline_blame_layout = Some(layout);
10607                                    // Blame overrides inline diagnostics
10608                                    inline_diagnostics.remove(&display_row);
10609                                }
10610                            } else {
10611                                log::error!(
10612                                    "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
10613                                    line_layouts.len(): {}, \
10614                                    crease_trailers.len(): {}",
10615                                    line_ix,
10616                                    row_infos.len(),
10617                                    line_layouts.len(),
10618                                    crease_trailers.len(),
10619                                );
10620                            }
10621                        }
10622                    }
10623
10624                    let blamed_display_rows = self.layout_blame_entries(
10625                        &row_infos,
10626                        em_width,
10627                        scroll_position,
10628                        line_height,
10629                        &gutter_hitbox,
10630                        gutter_dimensions.git_blame_entries_width,
10631                        window,
10632                        cx,
10633                    );
10634
10635                    let line_elements = self.prepaint_lines(
10636                        start_row,
10637                        &mut line_layouts,
10638                        line_height,
10639                        scroll_position,
10640                        scroll_pixel_position,
10641                        content_origin,
10642                        window,
10643                        cx,
10644                    );
10645
10646                    window.with_element_namespace("blocks", |window| {
10647                        self.layout_blocks(
10648                            &mut blocks,
10649                            &hitbox,
10650                            &gutter_hitbox,
10651                            line_height,
10652                            scroll_position,
10653                            scroll_pixel_position,
10654                            &editor_margins,
10655                            window,
10656                            cx,
10657                        );
10658                        self.layout_blocks(
10659                            &mut spacer_blocks,
10660                            &hitbox,
10661                            &gutter_hitbox,
10662                            line_height,
10663                            scroll_position,
10664                            scroll_pixel_position,
10665                            &editor_margins,
10666                            window,
10667                            cx,
10668                        );
10669                    });
10670
10671                    let cursors = self.collect_cursors(&snapshot, cx);
10672                    let visible_row_range = start_row..end_row;
10673                    let non_visible_cursors = cursors
10674                        .iter()
10675                        .any(|c| !visible_row_range.contains(&c.0.row()));
10676
10677                    let visible_cursors = self.layout_visible_cursors(
10678                        &snapshot,
10679                        &selections,
10680                        &row_block_types,
10681                        start_row..end_row,
10682                        &line_layouts,
10683                        &text_hitbox,
10684                        content_origin,
10685                        scroll_position,
10686                        scroll_pixel_position,
10687                        line_height,
10688                        em_width,
10689                        em_advance,
10690                        autoscroll_containing_element,
10691                        &redacted_ranges,
10692                        window,
10693                        cx,
10694                    );
10695
10696                    let scrollbars_layout = self.layout_scrollbars(
10697                        &snapshot,
10698                        &scrollbar_layout_information,
10699                        content_offset,
10700                        scroll_position,
10701                        non_visible_cursors,
10702                        right_margin,
10703                        editor_width,
10704                        window,
10705                        cx,
10706                    );
10707
10708                    let gutter_settings = EditorSettings::get_global(cx).gutter;
10709
10710                    let context_menu_layout =
10711                        if let Some(newest_selection_head) = newest_selection_head {
10712                            let newest_selection_point =
10713                                newest_selection_head.to_point(&snapshot.display_snapshot);
10714                            if (start_row..end_row).contains(&newest_selection_head.row()) {
10715                                self.layout_cursor_popovers(
10716                                    line_height,
10717                                    &text_hitbox,
10718                                    content_origin,
10719                                    right_margin,
10720                                    start_row,
10721                                    scroll_pixel_position,
10722                                    &line_layouts,
10723                                    newest_selection_head,
10724                                    newest_selection_point,
10725                                    style,
10726                                    window,
10727                                    cx,
10728                                )
10729                            } else {
10730                                None
10731                            }
10732                        } else {
10733                            None
10734                        };
10735
10736                    self.layout_gutter_menu(
10737                        line_height,
10738                        &text_hitbox,
10739                        content_origin,
10740                        right_margin,
10741                        scroll_pixel_position,
10742                        gutter_dimensions.width - gutter_dimensions.left_padding,
10743                        window,
10744                        cx,
10745                    );
10746
10747                    let test_indicators = if gutter_settings.runnables {
10748                        self.layout_run_indicators(
10749                            line_height,
10750                            start_row..end_row,
10751                            &row_infos,
10752                            scroll_position,
10753                            &gutter_dimensions,
10754                            &gutter_hitbox,
10755                            &snapshot,
10756                            &mut breakpoint_rows,
10757                            window,
10758                            cx,
10759                        )
10760                    } else {
10761                        Vec::new()
10762                    };
10763
10764                    let show_breakpoints = snapshot
10765                        .show_breakpoints
10766                        .unwrap_or(gutter_settings.breakpoints);
10767                    let breakpoints = if show_breakpoints {
10768                        self.layout_breakpoints(
10769                            line_height,
10770                            start_row..end_row,
10771                            scroll_position,
10772                            &gutter_dimensions,
10773                            &gutter_hitbox,
10774                            &snapshot,
10775                            breakpoint_rows,
10776                            &row_infos,
10777                            window,
10778                            cx,
10779                        )
10780                    } else {
10781                        Vec::new()
10782                    };
10783
10784                    let git_gutter_width = Self::gutter_strip_width(line_height)
10785                        + gutter_dimensions
10786                            .git_blame_entries_width
10787                            .unwrap_or_default();
10788                    let available_width = gutter_dimensions.left_padding - git_gutter_width;
10789
10790                    let max_line_number_length = self
10791                        .editor
10792                        .read(cx)
10793                        .buffer()
10794                        .read(cx)
10795                        .snapshot(cx)
10796                        .widest_line_number()
10797                        .ilog10()
10798                        + 1;
10799
10800                    let diff_review_button = self
10801                        .should_render_diff_review_button(
10802                            start_row..end_row,
10803                            &row_infos,
10804                            &snapshot,
10805                            cx,
10806                        )
10807                        .map(|(display_row, buffer_row)| {
10808                            let is_wide = max_line_number_length
10809                                >= EditorSettings::get_global(cx).gutter.min_line_number_digits
10810                                    as u32
10811                                && buffer_row.is_some_and(|row| {
10812                                    (row + 1).ilog10() + 1 == max_line_number_length
10813                                })
10814                                || gutter_dimensions.right_padding == px(0.);
10815
10816                            let button_width = if is_wide {
10817                                available_width - px(6.)
10818                            } else {
10819                                available_width + em_width - px(6.)
10820                            };
10821
10822                            let button = self.editor.update(cx, |editor, cx| {
10823                                editor
10824                                    .render_diff_review_button(display_row, button_width, cx)
10825                                    .into_any_element()
10826                            });
10827                            prepaint_gutter_button(
10828                                button,
10829                                display_row,
10830                                line_height,
10831                                &gutter_dimensions,
10832                                scroll_position,
10833                                &gutter_hitbox,
10834                                window,
10835                                cx,
10836                            )
10837                        });
10838
10839                    self.layout_signature_help(
10840                        &hitbox,
10841                        content_origin,
10842                        scroll_pixel_position,
10843                        newest_selection_head,
10844                        start_row,
10845                        &line_layouts,
10846                        line_height,
10847                        em_width,
10848                        context_menu_layout,
10849                        window,
10850                        cx,
10851                    );
10852
10853                    if !cx.has_active_drag() {
10854                        self.layout_hover_popovers(
10855                            &snapshot,
10856                            &hitbox,
10857                            start_row..end_row,
10858                            content_origin,
10859                            scroll_pixel_position,
10860                            &line_layouts,
10861                            line_height,
10862                            em_width,
10863                            context_menu_layout,
10864                            window,
10865                            cx,
10866                        );
10867
10868                        self.layout_blame_popover(&snapshot, &hitbox, line_height, window, cx);
10869                    }
10870
10871                    let mouse_context_menu = self.layout_mouse_context_menu(
10872                        &snapshot,
10873                        start_row..end_row,
10874                        content_origin,
10875                        window,
10876                        cx,
10877                    );
10878
10879                    window.with_element_namespace("crease_toggles", |window| {
10880                        self.prepaint_crease_toggles(
10881                            &mut crease_toggles,
10882                            line_height,
10883                            &gutter_dimensions,
10884                            gutter_settings,
10885                            scroll_pixel_position,
10886                            &gutter_hitbox,
10887                            window,
10888                            cx,
10889                        )
10890                    });
10891
10892                    window.with_element_namespace("expand_toggles", |window| {
10893                        self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
10894                    });
10895
10896                    let wrap_guides = self.layout_wrap_guides(
10897                        em_advance,
10898                        scroll_position,
10899                        content_origin,
10900                        scrollbars_layout.as_ref(),
10901                        vertical_scrollbar_width,
10902                        &hitbox,
10903                        window,
10904                        cx,
10905                    );
10906
10907                    let minimap = window.with_element_namespace("minimap", |window| {
10908                        self.layout_minimap(
10909                            &snapshot,
10910                            minimap_width,
10911                            scroll_position,
10912                            &scrollbar_layout_information,
10913                            scrollbars_layout.as_ref(),
10914                            window,
10915                            cx,
10916                        )
10917                    });
10918
10919                    let invisible_symbol_font_size = font_size / 2.;
10920                    let whitespace_map = &self
10921                        .editor
10922                        .read(cx)
10923                        .buffer
10924                        .read(cx)
10925                        .language_settings(cx)
10926                        .whitespace_map;
10927
10928                    let tab_char = whitespace_map.tab.clone();
10929                    let tab_len = tab_char.len();
10930                    let tab_invisible = window.text_system().shape_line(
10931                        tab_char,
10932                        invisible_symbol_font_size,
10933                        &[TextRun {
10934                            len: tab_len,
10935                            font: self.style.text.font(),
10936                            color: cx.theme().colors().editor_invisible,
10937                            ..Default::default()
10938                        }],
10939                        None,
10940                    );
10941
10942                    let space_char = whitespace_map.space.clone();
10943                    let space_len = space_char.len();
10944                    let space_invisible = window.text_system().shape_line(
10945                        space_char,
10946                        invisible_symbol_font_size,
10947                        &[TextRun {
10948                            len: space_len,
10949                            font: self.style.text.font(),
10950                            color: cx.theme().colors().editor_invisible,
10951                            ..Default::default()
10952                        }],
10953                        None,
10954                    );
10955
10956                    let mode = snapshot.mode.clone();
10957
10958                    let sticky_scroll_header_height = sticky_headers
10959                        .as_ref()
10960                        .and_then(|headers| headers.lines.last())
10961                        .map_or(Pixels::ZERO, |last| last.offset + line_height);
10962
10963                    let has_sticky_buffer_header =
10964                        sticky_buffer_header.is_some() || sticky_header_excerpt_id.is_some();
10965                    let sticky_header_height = if has_sticky_buffer_header {
10966                        let full_height = FILE_HEADER_HEIGHT as f32 * line_height;
10967                        let display_row = blocks
10968                            .iter()
10969                            .filter(|block| block.is_buffer_header)
10970                            .find_map(|block| {
10971                                block.row.filter(|row| row.0 > scroll_position.y as u32)
10972                            });
10973                        let offset = match display_row {
10974                            Some(display_row) => {
10975                                let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
10976                                let offset = (scroll_position.y - max_row as f64).max(0.0);
10977                                let slide_up =
10978                                    Pixels::from(offset * ScrollPixelOffset::from(line_height));
10979
10980                                (full_height - slide_up).max(Pixels::ZERO)
10981                            }
10982                            None => full_height,
10983                        };
10984                        let header_bottom_padding =
10985                            BUFFER_HEADER_PADDING.to_pixels(window.rem_size());
10986                        sticky_scroll_header_height + offset - header_bottom_padding
10987                    } else {
10988                        sticky_scroll_header_height
10989                    };
10990
10991                    let (diff_hunk_controls, diff_hunk_control_bounds) =
10992                        if is_read_only && !self.editor.read(cx).delegate_stage_and_restore {
10993                            (vec![], vec![])
10994                        } else {
10995                            self.layout_diff_hunk_controls(
10996                                start_row..end_row,
10997                                &row_infos,
10998                                &text_hitbox,
10999                                current_selection_head,
11000                                line_height,
11001                                right_margin,
11002                                scroll_pixel_position,
11003                                sticky_header_height,
11004                                &display_hunks,
11005                                &highlighted_rows,
11006                                self.editor.clone(),
11007                                window,
11008                                cx,
11009                            )
11010                        };
11011
11012                    let position_map = Rc::new(PositionMap {
11013                        size: bounds.size,
11014                        visible_row_range,
11015                        scroll_position,
11016                        scroll_pixel_position,
11017                        scroll_max,
11018                        line_layouts,
11019                        line_height,
11020                        em_width,
11021                        em_advance,
11022                        em_layout_width,
11023                        snapshot,
11024                        text_align: self.style.text.text_align,
11025                        content_width: text_hitbox.size.width,
11026                        gutter_hitbox: gutter_hitbox.clone(),
11027                        text_hitbox: text_hitbox.clone(),
11028                        inline_blame_bounds: inline_blame_layout
11029                            .as_ref()
11030                            .map(|layout| (layout.bounds, layout.buffer_id, layout.entry.clone())),
11031                        display_hunks: display_hunks.clone(),
11032                        diff_hunk_control_bounds,
11033                    });
11034
11035                    self.editor.update(cx, |editor, _| {
11036                        editor.last_position_map = Some(position_map.clone())
11037                    });
11038
11039                    EditorLayout {
11040                        mode,
11041                        position_map,
11042                        visible_display_row_range: start_row..end_row,
11043                        wrap_guides,
11044                        indent_guides,
11045                        hitbox,
11046                        gutter_hitbox,
11047                        display_hunks,
11048                        content_origin,
11049                        scrollbars_layout,
11050                        minimap,
11051                        active_rows,
11052                        highlighted_rows,
11053                        highlighted_ranges,
11054                        highlighted_gutter_ranges,
11055                        redacted_ranges,
11056                        document_colors,
11057                        line_elements,
11058                        line_numbers,
11059                        blamed_display_rows,
11060                        inline_diagnostics,
11061                        inline_blame_layout,
11062                        inline_code_actions,
11063                        blocks,
11064                        spacer_blocks,
11065                        cursors,
11066                        visible_cursors,
11067                        selections,
11068                        edit_prediction_popover,
11069                        diff_hunk_controls,
11070                        mouse_context_menu,
11071                        test_indicators,
11072                        breakpoints,
11073                        diff_review_button,
11074                        crease_toggles,
11075                        crease_trailers,
11076                        tab_invisible,
11077                        space_invisible,
11078                        sticky_buffer_header,
11079                        sticky_headers,
11080                        expand_toggles,
11081                        text_align: self.style.text.text_align,
11082                        content_width: text_hitbox.size.width,
11083                    }
11084                })
11085            })
11086        })
11087    }
11088
11089    fn paint(
11090        &mut self,
11091        _: Option<&GlobalElementId>,
11092        _inspector_id: Option<&gpui::InspectorElementId>,
11093        bounds: Bounds<gpui::Pixels>,
11094        _: &mut Self::RequestLayoutState,
11095        layout: &mut Self::PrepaintState,
11096        window: &mut Window,
11097        cx: &mut App,
11098    ) {
11099        if !layout.mode.is_minimap() {
11100            let focus_handle = self.editor.focus_handle(cx);
11101            let key_context = self
11102                .editor
11103                .update(cx, |editor, cx| editor.key_context(window, cx));
11104
11105            window.set_key_context(key_context);
11106            window.handle_input(
11107                &focus_handle,
11108                ElementInputHandler::new(bounds, self.editor.clone()),
11109                cx,
11110            );
11111            self.register_actions(window, cx);
11112            self.register_key_listeners(window, cx, layout);
11113        }
11114
11115        let text_style = TextStyleRefinement {
11116            font_size: Some(self.style.text.font_size),
11117            line_height: Some(self.style.text.line_height),
11118            ..Default::default()
11119        };
11120        let rem_size = self.rem_size(cx);
11121        window.with_rem_size(rem_size, |window| {
11122            window.with_text_style(Some(text_style), |window| {
11123                window.with_content_mask(Some(ContentMask { bounds }), |window| {
11124                    self.paint_mouse_listeners(layout, window, cx);
11125                    self.paint_background(layout, window, cx);
11126
11127                    self.paint_indent_guides(layout, window, cx);
11128
11129                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
11130                        self.paint_blamed_display_rows(layout, window, cx);
11131                        self.paint_line_numbers(layout, window, cx);
11132                    }
11133
11134                    self.paint_text(layout, window, cx);
11135
11136                    if !layout.spacer_blocks.is_empty() {
11137                        window.with_element_namespace("blocks", |window| {
11138                            self.paint_spacer_blocks(layout, window, cx);
11139                        });
11140                    }
11141
11142                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
11143                        self.paint_gutter_highlights(layout, window, cx);
11144                        self.paint_gutter_indicators(layout, window, cx);
11145                    }
11146
11147                    if !layout.blocks.is_empty() {
11148                        window.with_element_namespace("blocks", |window| {
11149                            self.paint_non_spacer_blocks(layout, window, cx);
11150                        });
11151                    }
11152
11153                    window.with_element_namespace("blocks", |window| {
11154                        if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
11155                            sticky_header.paint(window, cx)
11156                        }
11157                    });
11158
11159                    self.paint_sticky_headers(layout, window, cx);
11160                    self.paint_minimap(layout, window, cx);
11161                    self.paint_scrollbars(layout, window, cx);
11162                    self.paint_edit_prediction_popover(layout, window, cx);
11163                    self.paint_mouse_context_menu(layout, window, cx);
11164                });
11165            })
11166        })
11167    }
11168}
11169
11170pub(super) fn gutter_bounds(
11171    editor_bounds: Bounds<Pixels>,
11172    gutter_dimensions: GutterDimensions,
11173) -> Bounds<Pixels> {
11174    Bounds {
11175        origin: editor_bounds.origin,
11176        size: size(gutter_dimensions.width, editor_bounds.size.height),
11177    }
11178}
11179
11180#[derive(Clone, Copy)]
11181struct ContextMenuLayout {
11182    y_flipped: bool,
11183    bounds: Bounds<Pixels>,
11184}
11185
11186/// Holds information required for layouting the editor scrollbars.
11187struct ScrollbarLayoutInformation {
11188    /// The bounds of the editor area (excluding the content offset).
11189    editor_bounds: Bounds<Pixels>,
11190    /// The available range to scroll within the document.
11191    scroll_range: Size<Pixels>,
11192    /// The space available for one glyph in the editor.
11193    glyph_grid_cell: Size<Pixels>,
11194}
11195
11196impl ScrollbarLayoutInformation {
11197    pub fn new(
11198        editor_bounds: Bounds<Pixels>,
11199        glyph_grid_cell: Size<Pixels>,
11200        document_size: Size<Pixels>,
11201        longest_line_blame_width: Pixels,
11202        settings: &EditorSettings,
11203        scroll_beyond_last_line: ScrollBeyondLastLine,
11204    ) -> Self {
11205        let vertical_overscroll = match scroll_beyond_last_line {
11206            ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
11207            ScrollBeyondLastLine::Off => glyph_grid_cell.height,
11208            ScrollBeyondLastLine::VerticalScrollMargin => {
11209                (1.0 + settings.vertical_scroll_margin) as f32 * glyph_grid_cell.height
11210            }
11211        };
11212
11213        let overscroll = size(longest_line_blame_width, vertical_overscroll);
11214
11215        ScrollbarLayoutInformation {
11216            editor_bounds,
11217            scroll_range: document_size + overscroll,
11218            glyph_grid_cell,
11219        }
11220    }
11221}
11222
11223impl IntoElement for EditorElement {
11224    type Element = Self;
11225
11226    fn into_element(self) -> Self::Element {
11227        self
11228    }
11229}
11230
11231pub struct EditorLayout {
11232    position_map: Rc<PositionMap>,
11233    hitbox: Hitbox,
11234    gutter_hitbox: Hitbox,
11235    content_origin: gpui::Point<Pixels>,
11236    scrollbars_layout: Option<EditorScrollbars>,
11237    minimap: Option<MinimapLayout>,
11238    mode: EditorMode,
11239    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
11240    indent_guides: Option<Vec<IndentGuideLayout>>,
11241    visible_display_row_range: Range<DisplayRow>,
11242    active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
11243    highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
11244    line_elements: SmallVec<[AnyElement; 1]>,
11245    line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
11246    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
11247    blamed_display_rows: Option<Vec<AnyElement>>,
11248    inline_diagnostics: HashMap<DisplayRow, AnyElement>,
11249    inline_blame_layout: Option<InlineBlameLayout>,
11250    inline_code_actions: Option<AnyElement>,
11251    blocks: Vec<BlockLayout>,
11252    spacer_blocks: Vec<BlockLayout>,
11253    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
11254    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
11255    redacted_ranges: Vec<Range<DisplayPoint>>,
11256    cursors: Vec<(DisplayPoint, Hsla)>,
11257    visible_cursors: Vec<CursorLayout>,
11258    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
11259    test_indicators: Vec<AnyElement>,
11260    breakpoints: Vec<AnyElement>,
11261    diff_review_button: Option<AnyElement>,
11262    crease_toggles: Vec<Option<AnyElement>>,
11263    expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
11264    diff_hunk_controls: Vec<AnyElement>,
11265    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
11266    edit_prediction_popover: Option<AnyElement>,
11267    mouse_context_menu: Option<AnyElement>,
11268    tab_invisible: ShapedLine,
11269    space_invisible: ShapedLine,
11270    sticky_buffer_header: Option<AnyElement>,
11271    sticky_headers: Option<StickyHeaders>,
11272    document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
11273    text_align: TextAlign,
11274    content_width: Pixels,
11275}
11276
11277struct StickyHeaders {
11278    lines: Vec<StickyHeaderLine>,
11279    gutter_background: Hsla,
11280    content_background: Hsla,
11281    gutter_right_padding: Pixels,
11282}
11283
11284struct StickyHeaderLine {
11285    row: DisplayRow,
11286    offset: Pixels,
11287    line: Rc<LineWithInvisibles>,
11288    line_number: Option<ShapedLine>,
11289    elements: SmallVec<[AnyElement; 1]>,
11290    available_text_width: Pixels,
11291    hitbox: Hitbox,
11292}
11293
11294impl EditorLayout {
11295    fn line_end_overshoot(&self) -> Pixels {
11296        0.15 * self.position_map.line_height
11297    }
11298}
11299
11300impl StickyHeaders {
11301    fn paint(
11302        &mut self,
11303        layout: &mut EditorLayout,
11304        whitespace_setting: ShowWhitespaceSetting,
11305        window: &mut Window,
11306        cx: &mut App,
11307    ) {
11308        let line_height = layout.position_map.line_height;
11309
11310        for line in self.lines.iter_mut().rev() {
11311            window.paint_layer(
11312                Bounds::new(
11313                    layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
11314                    size(line.hitbox.size.width, line_height),
11315                ),
11316                |window| {
11317                    let gutter_bounds = Bounds::new(
11318                        layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
11319                        size(layout.gutter_hitbox.size.width, line_height),
11320                    );
11321                    window.paint_quad(fill(gutter_bounds, self.gutter_background));
11322
11323                    let text_bounds = Bounds::new(
11324                        layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset),
11325                        size(line.available_text_width, line_height),
11326                    );
11327                    window.paint_quad(fill(text_bounds, self.content_background));
11328
11329                    if line.hitbox.is_hovered(window) {
11330                        let hover_overlay = cx.theme().colors().panel_overlay_hover;
11331                        window.paint_quad(fill(gutter_bounds, hover_overlay));
11332                        window.paint_quad(fill(text_bounds, hover_overlay));
11333                    }
11334
11335                    line.paint(
11336                        layout,
11337                        self.gutter_right_padding,
11338                        line.available_text_width,
11339                        layout.content_origin,
11340                        line_height,
11341                        whitespace_setting,
11342                        window,
11343                        cx,
11344                    );
11345                },
11346            );
11347
11348            window.set_cursor_style(CursorStyle::IBeam, &line.hitbox);
11349        }
11350    }
11351}
11352
11353impl StickyHeaderLine {
11354    fn new(
11355        row: DisplayRow,
11356        offset: Pixels,
11357        mut line: LineWithInvisibles,
11358        line_number: Option<ShapedLine>,
11359        line_height: Pixels,
11360        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11361        content_origin: gpui::Point<Pixels>,
11362        gutter_hitbox: &Hitbox,
11363        text_hitbox: &Hitbox,
11364        window: &mut Window,
11365        cx: &mut App,
11366    ) -> Self {
11367        let mut elements = SmallVec::<[AnyElement; 1]>::new();
11368        line.prepaint_with_custom_offset(
11369            line_height,
11370            scroll_pixel_position,
11371            content_origin,
11372            offset,
11373            &mut elements,
11374            window,
11375            cx,
11376        );
11377
11378        let hitbox_bounds = Bounds::new(
11379            gutter_hitbox.origin + point(Pixels::ZERO, offset),
11380            size(text_hitbox.right() - gutter_hitbox.left(), line_height),
11381        );
11382        let available_text_width =
11383            (hitbox_bounds.size.width - gutter_hitbox.size.width).max(Pixels::ZERO);
11384
11385        Self {
11386            row,
11387            offset,
11388            line: Rc::new(line),
11389            line_number,
11390            elements,
11391            available_text_width,
11392            hitbox: window.insert_hitbox(hitbox_bounds, HitboxBehavior::BlockMouseExceptScroll),
11393        }
11394    }
11395
11396    fn paint(
11397        &mut self,
11398        layout: &EditorLayout,
11399        gutter_right_padding: Pixels,
11400        available_text_width: Pixels,
11401        content_origin: gpui::Point<Pixels>,
11402        line_height: Pixels,
11403        whitespace_setting: ShowWhitespaceSetting,
11404        window: &mut Window,
11405        cx: &mut App,
11406    ) {
11407        window.with_content_mask(
11408            Some(ContentMask {
11409                bounds: Bounds::new(
11410                    layout.position_map.text_hitbox.bounds.origin
11411                        + point(Pixels::ZERO, self.offset),
11412                    size(available_text_width, line_height),
11413                ),
11414            }),
11415            |window| {
11416                self.line.draw_with_custom_offset(
11417                    layout,
11418                    self.row,
11419                    content_origin,
11420                    self.offset,
11421                    whitespace_setting,
11422                    &[],
11423                    window,
11424                    cx,
11425                );
11426                for element in &mut self.elements {
11427                    element.paint(window, cx);
11428                }
11429            },
11430        );
11431
11432        if let Some(line_number) = &self.line_number {
11433            let gutter_origin = layout.gutter_hitbox.origin + point(Pixels::ZERO, self.offset);
11434            let gutter_width = layout.gutter_hitbox.size.width;
11435            let origin = point(
11436                gutter_origin.x + gutter_width - gutter_right_padding - line_number.width,
11437                gutter_origin.y,
11438            );
11439            line_number
11440                .paint(origin, line_height, TextAlign::Left, None, window, cx)
11441                .log_err();
11442        }
11443    }
11444}
11445
11446#[derive(Debug)]
11447struct LineNumberSegment {
11448    shaped_line: ShapedLine,
11449    hitbox: Option<Hitbox>,
11450}
11451
11452#[derive(Debug)]
11453struct LineNumberLayout {
11454    segments: SmallVec<[LineNumberSegment; 1]>,
11455}
11456
11457struct ColoredRange<T> {
11458    start: T,
11459    end: T,
11460    color: Hsla,
11461}
11462
11463impl Along for ScrollbarAxes {
11464    type Unit = bool;
11465
11466    fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
11467        match axis {
11468            ScrollbarAxis::Horizontal => self.horizontal,
11469            ScrollbarAxis::Vertical => self.vertical,
11470        }
11471    }
11472
11473    fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
11474        match axis {
11475            ScrollbarAxis::Horizontal => ScrollbarAxes {
11476                horizontal: f(self.horizontal),
11477                vertical: self.vertical,
11478            },
11479            ScrollbarAxis::Vertical => ScrollbarAxes {
11480                horizontal: self.horizontal,
11481                vertical: f(self.vertical),
11482            },
11483        }
11484    }
11485}
11486
11487#[derive(Clone)]
11488struct EditorScrollbars {
11489    pub vertical: Option<ScrollbarLayout>,
11490    pub horizontal: Option<ScrollbarLayout>,
11491    pub visible: bool,
11492}
11493
11494impl EditorScrollbars {
11495    pub fn from_scrollbar_axes(
11496        show_scrollbar: ScrollbarAxes,
11497        layout_information: &ScrollbarLayoutInformation,
11498        content_offset: gpui::Point<Pixels>,
11499        scroll_position: gpui::Point<f64>,
11500        scrollbar_width: Pixels,
11501        right_margin: Pixels,
11502        editor_width: Pixels,
11503        show_scrollbars: bool,
11504        scrollbar_state: Option<&ActiveScrollbarState>,
11505        window: &mut Window,
11506    ) -> Self {
11507        let ScrollbarLayoutInformation {
11508            editor_bounds,
11509            scroll_range,
11510            glyph_grid_cell,
11511        } = layout_information;
11512
11513        let viewport_size = size(editor_width, editor_bounds.size.height);
11514
11515        let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
11516            ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
11517                Corner::BottomLeft,
11518                editor_bounds.bottom_left(),
11519                size(
11520                    // The horizontal viewport size differs from the space available for the
11521                    // horizontal scrollbar, so we have to manually stitch it together here.
11522                    editor_bounds.size.width - right_margin,
11523                    scrollbar_width,
11524                ),
11525            ),
11526            ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
11527                Corner::TopRight,
11528                editor_bounds.top_right(),
11529                size(scrollbar_width, viewport_size.height),
11530            ),
11531        };
11532
11533        let mut create_scrollbar_layout = |axis| {
11534            let viewport_size = viewport_size.along(axis);
11535            let scroll_range = scroll_range.along(axis);
11536
11537            // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
11538            (show_scrollbar.along(axis)
11539                && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
11540                .then(|| {
11541                    ScrollbarLayout::new(
11542                        window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
11543                        viewport_size,
11544                        scroll_range,
11545                        glyph_grid_cell.along(axis),
11546                        content_offset.along(axis),
11547                        scroll_position.along(axis),
11548                        show_scrollbars,
11549                        axis,
11550                    )
11551                    .with_thumb_state(
11552                        scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
11553                    )
11554                })
11555        };
11556
11557        Self {
11558            vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
11559            horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
11560            visible: show_scrollbars,
11561        }
11562    }
11563
11564    pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
11565        [
11566            (&self.vertical, ScrollbarAxis::Vertical),
11567            (&self.horizontal, ScrollbarAxis::Horizontal),
11568        ]
11569        .into_iter()
11570        .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
11571    }
11572
11573    /// Returns the currently hovered scrollbar axis, if any.
11574    pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
11575        self.iter_scrollbars()
11576            .find(|s| s.0.hitbox.is_hovered(window))
11577    }
11578}
11579
11580#[derive(Clone)]
11581struct ScrollbarLayout {
11582    hitbox: Hitbox,
11583    visible_range: Range<ScrollOffset>,
11584    text_unit_size: Pixels,
11585    thumb_bounds: Option<Bounds<Pixels>>,
11586    thumb_state: ScrollbarThumbState,
11587}
11588
11589impl ScrollbarLayout {
11590    const BORDER_WIDTH: Pixels = px(1.0);
11591    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
11592    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
11593    const MIN_THUMB_SIZE: Pixels = px(25.0);
11594
11595    fn new(
11596        scrollbar_track_hitbox: Hitbox,
11597        viewport_size: Pixels,
11598        scroll_range: Pixels,
11599        glyph_space: Pixels,
11600        content_offset: Pixels,
11601        scroll_position: ScrollOffset,
11602        show_thumb: bool,
11603        axis: ScrollbarAxis,
11604    ) -> Self {
11605        let track_bounds = scrollbar_track_hitbox.bounds;
11606        // The length of the track available to the scrollbar thumb. We deliberately
11607        // exclude the content size here so that the thumb aligns with the content.
11608        let track_length = track_bounds.size.along(axis) - content_offset;
11609
11610        Self::new_with_hitbox_and_track_length(
11611            scrollbar_track_hitbox,
11612            track_length,
11613            viewport_size,
11614            scroll_range.into(),
11615            glyph_space,
11616            content_offset.into(),
11617            scroll_position,
11618            show_thumb,
11619            axis,
11620        )
11621    }
11622
11623    fn for_minimap(
11624        minimap_track_hitbox: Hitbox,
11625        visible_lines: f64,
11626        total_editor_lines: f64,
11627        minimap_line_height: Pixels,
11628        scroll_position: ScrollOffset,
11629        minimap_scroll_top: ScrollOffset,
11630        show_thumb: bool,
11631    ) -> Self {
11632        // The scrollbar thumb size is calculated as
11633        // (visible_content/total_content) Γ— scrollbar_track_length.
11634        //
11635        // For the minimap's thumb layout, we leverage this by setting the
11636        // scrollbar track length to the entire document size (using minimap line
11637        // height). This creates a thumb that exactly represents the editor
11638        // viewport scaled to minimap proportions.
11639        //
11640        // We adjust the thumb position relative to `minimap_scroll_top` to
11641        // accommodate for the deliberately oversized track.
11642        //
11643        // This approach ensures that the minimap thumb accurately reflects the
11644        // editor's current scroll position whilst nicely synchronizing the minimap
11645        // thumb and scrollbar thumb.
11646        let scroll_range = total_editor_lines * f64::from(minimap_line_height);
11647        let viewport_size = visible_lines * f64::from(minimap_line_height);
11648
11649        let track_top_offset = -minimap_scroll_top * f64::from(minimap_line_height);
11650
11651        Self::new_with_hitbox_and_track_length(
11652            minimap_track_hitbox,
11653            Pixels::from(scroll_range),
11654            Pixels::from(viewport_size),
11655            scroll_range,
11656            minimap_line_height,
11657            track_top_offset,
11658            scroll_position,
11659            show_thumb,
11660            ScrollbarAxis::Vertical,
11661        )
11662    }
11663
11664    fn new_with_hitbox_and_track_length(
11665        scrollbar_track_hitbox: Hitbox,
11666        track_length: Pixels,
11667        viewport_size: Pixels,
11668        scroll_range: f64,
11669        glyph_space: Pixels,
11670        content_offset: ScrollOffset,
11671        scroll_position: ScrollOffset,
11672        show_thumb: bool,
11673        axis: ScrollbarAxis,
11674    ) -> Self {
11675        let text_units_per_page = viewport_size.to_f64() / glyph_space.to_f64();
11676        let visible_range = scroll_position..scroll_position + text_units_per_page;
11677        let total_text_units = scroll_range / glyph_space.to_f64();
11678
11679        let thumb_percentage = text_units_per_page / total_text_units;
11680        let thumb_size = Pixels::from(ScrollOffset::from(track_length) * thumb_percentage)
11681            .max(ScrollbarLayout::MIN_THUMB_SIZE)
11682            .min(track_length);
11683
11684        let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
11685
11686        let content_larger_than_viewport = text_unit_divisor > 0.;
11687
11688        let text_unit_size = if content_larger_than_viewport {
11689            Pixels::from(ScrollOffset::from(track_length - thumb_size) / text_unit_divisor)
11690        } else {
11691            glyph_space
11692        };
11693
11694        let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
11695            Self::thumb_bounds(
11696                &scrollbar_track_hitbox,
11697                content_offset,
11698                visible_range.start,
11699                text_unit_size,
11700                thumb_size,
11701                axis,
11702            )
11703        });
11704
11705        ScrollbarLayout {
11706            hitbox: scrollbar_track_hitbox,
11707            visible_range,
11708            text_unit_size,
11709            thumb_bounds,
11710            thumb_state: Default::default(),
11711        }
11712    }
11713
11714    fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
11715        if let Some(thumb_state) = thumb_state {
11716            Self {
11717                thumb_state,
11718                ..self
11719            }
11720        } else {
11721            self
11722        }
11723    }
11724
11725    fn thumb_bounds(
11726        scrollbar_track: &Hitbox,
11727        content_offset: f64,
11728        visible_range_start: f64,
11729        text_unit_size: Pixels,
11730        thumb_size: Pixels,
11731        axis: ScrollbarAxis,
11732    ) -> Bounds<Pixels> {
11733        let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
11734            origin
11735                + Pixels::from(
11736                    content_offset + visible_range_start * ScrollOffset::from(text_unit_size),
11737                )
11738        });
11739        Bounds::new(
11740            thumb_origin,
11741            scrollbar_track.size.apply_along(axis, |_| thumb_size),
11742        )
11743    }
11744
11745    fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
11746        self.thumb_bounds
11747            .is_some_and(|bounds| bounds.contains(position))
11748    }
11749
11750    fn marker_quads_for_ranges(
11751        &self,
11752        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
11753        column: Option<usize>,
11754    ) -> Vec<PaintQuad> {
11755        struct MinMax {
11756            min: Pixels,
11757            max: Pixels,
11758        }
11759        let (x_range, height_limit) = if let Some(column) = column {
11760            let column_width = ((self.hitbox.size.width - Self::BORDER_WIDTH) / 3.0).floor();
11761            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
11762            let end = start + column_width;
11763            (
11764                Range { start, end },
11765                MinMax {
11766                    min: Self::MIN_MARKER_HEIGHT,
11767                    max: px(f32::MAX),
11768                },
11769            )
11770        } else {
11771            (
11772                Range {
11773                    start: Self::BORDER_WIDTH,
11774                    end: self.hitbox.size.width,
11775                },
11776                MinMax {
11777                    min: Self::LINE_MARKER_HEIGHT,
11778                    max: Self::LINE_MARKER_HEIGHT,
11779                },
11780            )
11781        };
11782
11783        let row_to_y = |row: DisplayRow| row.as_f64() as f32 * self.text_unit_size;
11784        let mut pixel_ranges = row_ranges
11785            .into_iter()
11786            .map(|range| {
11787                let start_y = row_to_y(range.start);
11788                let end_y = row_to_y(range.end)
11789                    + self
11790                        .text_unit_size
11791                        .max(height_limit.min)
11792                        .min(height_limit.max);
11793                ColoredRange {
11794                    start: start_y,
11795                    end: end_y,
11796                    color: range.color,
11797                }
11798            })
11799            .peekable();
11800
11801        let mut quads = Vec::new();
11802        while let Some(mut pixel_range) = pixel_ranges.next() {
11803            while let Some(next_pixel_range) = pixel_ranges.peek() {
11804                if pixel_range.end >= next_pixel_range.start - px(1.0)
11805                    && pixel_range.color == next_pixel_range.color
11806                {
11807                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
11808                    pixel_ranges.next();
11809                } else {
11810                    break;
11811                }
11812            }
11813
11814            let bounds = Bounds::from_corners(
11815                point(x_range.start, pixel_range.start),
11816                point(x_range.end, pixel_range.end),
11817            );
11818            quads.push(quad(
11819                bounds,
11820                Corners::default(),
11821                pixel_range.color,
11822                Edges::default(),
11823                Hsla::transparent_black(),
11824                BorderStyle::default(),
11825            ));
11826        }
11827
11828        quads
11829    }
11830}
11831
11832struct MinimapLayout {
11833    pub minimap: AnyElement,
11834    pub thumb_layout: ScrollbarLayout,
11835    pub minimap_scroll_top: ScrollOffset,
11836    pub minimap_line_height: Pixels,
11837    pub thumb_border_style: MinimapThumbBorder,
11838    pub max_scroll_top: ScrollOffset,
11839}
11840
11841impl MinimapLayout {
11842    /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
11843    const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
11844    /// The minimap width as a percentage of the editor width.
11845    const MINIMAP_WIDTH_PCT: f32 = 0.15;
11846    /// Calculates the scroll top offset the minimap editor has to have based on the
11847    /// current scroll progress.
11848    fn calculate_minimap_top_offset(
11849        document_lines: f64,
11850        visible_editor_lines: f64,
11851        visible_minimap_lines: f64,
11852        scroll_position: f64,
11853    ) -> ScrollOffset {
11854        let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
11855        if non_visible_document_lines == 0. {
11856            0.
11857        } else {
11858            let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
11859            scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
11860        }
11861    }
11862}
11863
11864struct CreaseTrailerLayout {
11865    element: AnyElement,
11866    bounds: Bounds<Pixels>,
11867}
11868
11869pub(crate) struct PositionMap {
11870    pub size: Size<Pixels>,
11871    pub line_height: Pixels,
11872    pub scroll_position: gpui::Point<ScrollOffset>,
11873    pub scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11874    pub scroll_max: gpui::Point<ScrollOffset>,
11875    pub em_width: Pixels,
11876    pub em_advance: Pixels,
11877    pub em_layout_width: Pixels,
11878    pub visible_row_range: Range<DisplayRow>,
11879    pub line_layouts: Vec<LineWithInvisibles>,
11880    pub snapshot: EditorSnapshot,
11881    pub text_align: TextAlign,
11882    pub content_width: Pixels,
11883    pub text_hitbox: Hitbox,
11884    pub gutter_hitbox: Hitbox,
11885    pub inline_blame_bounds: Option<(Bounds<Pixels>, BufferId, BlameEntry)>,
11886    pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
11887    pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
11888}
11889
11890#[derive(Debug, Copy, Clone)]
11891pub struct PointForPosition {
11892    pub previous_valid: DisplayPoint,
11893    pub next_valid: DisplayPoint,
11894    pub exact_unclipped: DisplayPoint,
11895    pub column_overshoot_after_line_end: u32,
11896}
11897
11898impl PointForPosition {
11899    pub fn as_valid(&self) -> Option<DisplayPoint> {
11900        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
11901            Some(self.previous_valid)
11902        } else {
11903            None
11904        }
11905    }
11906
11907    pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
11908        let Some(valid_point) = self.as_valid() else {
11909            return false;
11910        };
11911        let range = selection.range();
11912
11913        let candidate_row = valid_point.row();
11914        let candidate_col = valid_point.column();
11915
11916        let start_row = range.start.row();
11917        let start_col = range.start.column();
11918        let end_row = range.end.row();
11919        let end_col = range.end.column();
11920
11921        if candidate_row < start_row || candidate_row > end_row {
11922            false
11923        } else if start_row == end_row {
11924            candidate_col >= start_col && candidate_col < end_col
11925        } else if candidate_row == start_row {
11926            candidate_col >= start_col
11927        } else if candidate_row == end_row {
11928            candidate_col < end_col
11929        } else {
11930            true
11931        }
11932    }
11933}
11934
11935impl PositionMap {
11936    pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
11937        let text_bounds = self.text_hitbox.bounds;
11938        let scroll_position = self.snapshot.scroll_position();
11939        let position = position - text_bounds.origin;
11940        let y = position.y.max(px(0.)).min(self.size.height);
11941        let x = position.x + (scroll_position.x as f32 * self.em_layout_width);
11942        let row = ((y / self.line_height) as f64 + scroll_position.y) as u32;
11943
11944        let (column, x_overshoot_after_line_end) = if let Some(line) = self
11945            .line_layouts
11946            .get(row as usize - scroll_position.y as usize)
11947        {
11948            let alignment_offset = line.alignment_offset(self.text_align, self.content_width);
11949            let x_relative_to_text = x - alignment_offset;
11950            if let Some(ix) = line.index_for_x(x_relative_to_text) {
11951                (ix as u32, px(0.))
11952            } else {
11953                (line.len as u32, px(0.).max(x_relative_to_text - line.width))
11954            }
11955        } else {
11956            (0, x)
11957        };
11958
11959        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
11960        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
11961        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
11962
11963        let column_overshoot_after_line_end =
11964            (x_overshoot_after_line_end / self.em_layout_width) as u32;
11965        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
11966        PointForPosition {
11967            previous_valid,
11968            next_valid,
11969            exact_unclipped,
11970            column_overshoot_after_line_end,
11971        }
11972    }
11973
11974    fn point_for_position_on_line(
11975        &self,
11976        position: gpui::Point<Pixels>,
11977        row: DisplayRow,
11978        line: &LineWithInvisibles,
11979    ) -> PointForPosition {
11980        let text_bounds = self.text_hitbox.bounds;
11981        let scroll_position = self.snapshot.scroll_position();
11982        let position = position - text_bounds.origin;
11983        let x = position.x + (scroll_position.x as f32 * self.em_layout_width);
11984
11985        let alignment_offset = line.alignment_offset(self.text_align, self.content_width);
11986        let x_relative_to_text = x - alignment_offset;
11987        let (column, x_overshoot_after_line_end) =
11988            if let Some(ix) = line.index_for_x(x_relative_to_text) {
11989                (ix as u32, px(0.))
11990            } else {
11991                (line.len as u32, px(0.).max(x_relative_to_text - line.width))
11992            };
11993
11994        let mut exact_unclipped = DisplayPoint::new(row, column);
11995        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
11996        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
11997
11998        let column_overshoot_after_line_end =
11999            (x_overshoot_after_line_end / self.em_layout_width) as u32;
12000        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
12001        PointForPosition {
12002            previous_valid,
12003            next_valid,
12004            exact_unclipped,
12005            column_overshoot_after_line_end,
12006        }
12007    }
12008}
12009
12010pub(crate) struct BlockLayout {
12011    pub(crate) id: BlockId,
12012    pub(crate) x_offset: Pixels,
12013    pub(crate) row: Option<DisplayRow>,
12014    pub(crate) element: AnyElement,
12015    pub(crate) available_space: Size<AvailableSpace>,
12016    pub(crate) style: BlockStyle,
12017    pub(crate) overlaps_gutter: bool,
12018    pub(crate) is_buffer_header: bool,
12019}
12020
12021pub fn layout_line(
12022    row: DisplayRow,
12023    snapshot: &EditorSnapshot,
12024    style: &EditorStyle,
12025    text_width: Pixels,
12026    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
12027    window: &mut Window,
12028    cx: &mut App,
12029) -> LineWithInvisibles {
12030    let use_tree_sitter =
12031        !snapshot.semantic_tokens_enabled || snapshot.use_tree_sitter_for_syntax(row, cx);
12032    let language_aware = LanguageAwareStyling {
12033        tree_sitter: use_tree_sitter,
12034        diagnostics: true,
12035    };
12036    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), language_aware, style);
12037    LineWithInvisibles::from_chunks(
12038        chunks,
12039        style,
12040        MAX_LINE_LEN,
12041        1,
12042        &snapshot.mode,
12043        text_width,
12044        is_row_soft_wrapped,
12045        &[],
12046        window,
12047        cx,
12048    )
12049    .pop()
12050    .unwrap()
12051}
12052
12053#[derive(Debug, Clone)]
12054pub struct IndentGuideLayout {
12055    origin: gpui::Point<Pixels>,
12056    length: Pixels,
12057    single_indent_width: Pixels,
12058    display_row_range: Range<DisplayRow>,
12059    depth: u32,
12060    active: bool,
12061    settings: IndentGuideSettings,
12062}
12063
12064pub struct CursorLayout {
12065    origin: gpui::Point<Pixels>,
12066    block_width: Pixels,
12067    line_height: Pixels,
12068    color: Hsla,
12069    shape: CursorShape,
12070    block_text: Option<ShapedLine>,
12071    cursor_name: Option<AnyElement>,
12072}
12073
12074#[derive(Debug)]
12075pub struct CursorName {
12076    string: SharedString,
12077    color: Hsla,
12078    is_top_row: bool,
12079}
12080
12081impl CursorLayout {
12082    pub fn new(
12083        origin: gpui::Point<Pixels>,
12084        block_width: Pixels,
12085        line_height: Pixels,
12086        color: Hsla,
12087        shape: CursorShape,
12088        block_text: Option<ShapedLine>,
12089    ) -> CursorLayout {
12090        CursorLayout {
12091            origin,
12092            block_width,
12093            line_height,
12094            color,
12095            shape,
12096            block_text,
12097            cursor_name: None,
12098        }
12099    }
12100
12101    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
12102        Bounds {
12103            origin: self.origin + origin,
12104            size: size(self.block_width, self.line_height),
12105        }
12106    }
12107
12108    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
12109        match self.shape {
12110            CursorShape::Bar => Bounds {
12111                origin: self.origin + origin,
12112                size: size(px(2.0), self.line_height),
12113            },
12114            CursorShape::Block | CursorShape::Hollow => Bounds {
12115                origin: self.origin + origin,
12116                size: size(self.block_width, self.line_height),
12117            },
12118            CursorShape::Underline => Bounds {
12119                origin: self.origin
12120                    + origin
12121                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
12122                size: size(self.block_width, px(2.0)),
12123            },
12124        }
12125    }
12126
12127    pub fn layout(
12128        &mut self,
12129        origin: gpui::Point<Pixels>,
12130        cursor_name: Option<CursorName>,
12131        window: &mut Window,
12132        cx: &mut App,
12133    ) {
12134        if let Some(cursor_name) = cursor_name {
12135            let bounds = self.bounds(origin);
12136            let text_size = self.line_height / 1.5;
12137
12138            let name_origin = if cursor_name.is_top_row {
12139                point(bounds.right() - px(1.), bounds.top())
12140            } else {
12141                match self.shape {
12142                    CursorShape::Bar => point(
12143                        bounds.right() - px(2.),
12144                        bounds.top() - text_size / 2. - px(1.),
12145                    ),
12146                    _ => point(
12147                        bounds.right() - px(1.),
12148                        bounds.top() - text_size / 2. - px(1.),
12149                    ),
12150                }
12151            };
12152            let mut name_element = div()
12153                .bg(self.color)
12154                .text_size(text_size)
12155                .px_0p5()
12156                .line_height(text_size + px(2.))
12157                .text_color(cursor_name.color)
12158                .child(cursor_name.string)
12159                .into_any_element();
12160
12161            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
12162
12163            self.cursor_name = Some(name_element);
12164        }
12165    }
12166
12167    pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
12168        let bounds = self.bounds(origin);
12169
12170        //Draw background or border quad
12171        let cursor = if matches!(self.shape, CursorShape::Hollow) {
12172            outline(bounds, self.color, BorderStyle::Solid)
12173        } else {
12174            fill(bounds, self.color)
12175        };
12176
12177        if let Some(name) = &mut self.cursor_name {
12178            name.paint(window, cx);
12179        }
12180
12181        window.paint_quad(cursor);
12182
12183        if let Some(block_text) = &self.block_text {
12184            block_text
12185                .paint(
12186                    self.origin + origin,
12187                    self.line_height,
12188                    TextAlign::Left,
12189                    None,
12190                    window,
12191                    cx,
12192                )
12193                .log_err();
12194        }
12195    }
12196
12197    pub fn shape(&self) -> CursorShape {
12198        self.shape
12199    }
12200}
12201
12202#[derive(Debug)]
12203pub struct HighlightedRange {
12204    pub start_y: Pixels,
12205    pub line_height: Pixels,
12206    pub lines: Vec<HighlightedRangeLine>,
12207    pub color: Hsla,
12208    pub corner_radius: Pixels,
12209}
12210
12211#[derive(Debug)]
12212pub struct HighlightedRangeLine {
12213    pub start_x: Pixels,
12214    pub end_x: Pixels,
12215}
12216
12217impl HighlightedRange {
12218    pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
12219        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
12220            self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
12221            self.paint_lines(
12222                self.start_y + self.line_height,
12223                &self.lines[1..],
12224                fill,
12225                bounds,
12226                window,
12227            );
12228        } else {
12229            self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
12230        }
12231    }
12232
12233    fn paint_lines(
12234        &self,
12235        start_y: Pixels,
12236        lines: &[HighlightedRangeLine],
12237        fill: bool,
12238        _bounds: Bounds<Pixels>,
12239        window: &mut Window,
12240    ) {
12241        if lines.is_empty() {
12242            return;
12243        }
12244
12245        let first_line = lines.first().unwrap();
12246        let last_line = lines.last().unwrap();
12247
12248        let first_top_left = point(first_line.start_x, start_y);
12249        let first_top_right = point(first_line.end_x, start_y);
12250
12251        let curve_height = point(Pixels::ZERO, self.corner_radius);
12252        let curve_width = |start_x: Pixels, end_x: Pixels| {
12253            let max = (end_x - start_x) / 2.;
12254            let width = if max < self.corner_radius {
12255                max
12256            } else {
12257                self.corner_radius
12258            };
12259
12260            point(width, Pixels::ZERO)
12261        };
12262
12263        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
12264        let mut builder = if fill {
12265            gpui::PathBuilder::fill()
12266        } else {
12267            gpui::PathBuilder::stroke(px(1.))
12268        };
12269        builder.move_to(first_top_right - top_curve_width);
12270        builder.curve_to(first_top_right + curve_height, first_top_right);
12271
12272        let mut iter = lines.iter().enumerate().peekable();
12273        while let Some((ix, line)) = iter.next() {
12274            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
12275
12276            if let Some((_, next_line)) = iter.peek() {
12277                let next_top_right = point(next_line.end_x, bottom_right.y);
12278
12279                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
12280                    Ordering::Equal => {
12281                        builder.line_to(bottom_right);
12282                    }
12283                    Ordering::Less => {
12284                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
12285                        builder.line_to(bottom_right - curve_height);
12286                        if self.corner_radius > Pixels::ZERO {
12287                            builder.curve_to(bottom_right - curve_width, bottom_right);
12288                        }
12289                        builder.line_to(next_top_right + curve_width);
12290                        if self.corner_radius > Pixels::ZERO {
12291                            builder.curve_to(next_top_right + curve_height, next_top_right);
12292                        }
12293                    }
12294                    Ordering::Greater => {
12295                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
12296                        builder.line_to(bottom_right - curve_height);
12297                        if self.corner_radius > Pixels::ZERO {
12298                            builder.curve_to(bottom_right + curve_width, bottom_right);
12299                        }
12300                        builder.line_to(next_top_right - curve_width);
12301                        if self.corner_radius > Pixels::ZERO {
12302                            builder.curve_to(next_top_right + curve_height, next_top_right);
12303                        }
12304                    }
12305                }
12306            } else {
12307                let curve_width = curve_width(line.start_x, line.end_x);
12308                builder.line_to(bottom_right - curve_height);
12309                if self.corner_radius > Pixels::ZERO {
12310                    builder.curve_to(bottom_right - curve_width, bottom_right);
12311                }
12312
12313                let bottom_left = point(line.start_x, bottom_right.y);
12314                builder.line_to(bottom_left + curve_width);
12315                if self.corner_radius > Pixels::ZERO {
12316                    builder.curve_to(bottom_left - curve_height, bottom_left);
12317                }
12318            }
12319        }
12320
12321        if first_line.start_x > last_line.start_x {
12322            let curve_width = curve_width(last_line.start_x, first_line.start_x);
12323            let second_top_left = point(last_line.start_x, start_y + self.line_height);
12324            builder.line_to(second_top_left + curve_height);
12325            if self.corner_radius > Pixels::ZERO {
12326                builder.curve_to(second_top_left + curve_width, second_top_left);
12327            }
12328            let first_bottom_left = point(first_line.start_x, second_top_left.y);
12329            builder.line_to(first_bottom_left - curve_width);
12330            if self.corner_radius > Pixels::ZERO {
12331                builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
12332            }
12333        }
12334
12335        builder.line_to(first_top_left + curve_height);
12336        if self.corner_radius > Pixels::ZERO {
12337            builder.curve_to(first_top_left + top_curve_width, first_top_left);
12338        }
12339        builder.line_to(first_top_right - top_curve_width);
12340
12341        if let Ok(path) = builder.build() {
12342            window.paint_path(path, self.color);
12343        }
12344    }
12345}
12346
12347pub(crate) struct StickyHeader {
12348    pub sticky_row: DisplayRow,
12349    pub start_point: Point,
12350    pub offset: ScrollOffset,
12351}
12352
12353enum CursorPopoverType {
12354    CodeContextMenu,
12355    EditPrediction,
12356}
12357
12358pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12359    (delta.pow(1.2) / 100.0).min(px(3.0)).into()
12360}
12361
12362fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12363    (delta.pow(1.2) / 300.0).into()
12364}
12365
12366pub fn register_action<T: Action>(
12367    editor: &Entity<Editor>,
12368    window: &mut Window,
12369    listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
12370) {
12371    let editor = editor.clone();
12372    window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
12373        let action = action.downcast_ref().unwrap();
12374        if phase == DispatchPhase::Bubble {
12375            editor.update(cx, |editor, cx| {
12376                listener(editor, action, window, cx);
12377            })
12378        }
12379    })
12380}
12381
12382/// Shared between `prepaint` and `compute_auto_height_layout` to ensure
12383/// both full and auto-height editors compute wrap widths consistently.
12384fn calculate_wrap_width(
12385    soft_wrap: SoftWrap,
12386    editor_width: Pixels,
12387    em_width: Pixels,
12388) -> Option<Pixels> {
12389    let wrap_width_for = |column: u32| (column as f32 * em_width).ceil();
12390
12391    match soft_wrap {
12392        SoftWrap::GitDiff => None,
12393        SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
12394        SoftWrap::EditorWidth => Some(editor_width),
12395        SoftWrap::Column(column) => Some(wrap_width_for(column)),
12396        SoftWrap::Bounded(column) => Some(editor_width.min(wrap_width_for(column))),
12397    }
12398}
12399
12400fn compute_auto_height_layout(
12401    editor: &mut Editor,
12402    min_lines: usize,
12403    max_lines: Option<usize>,
12404    known_dimensions: Size<Option<Pixels>>,
12405    available_width: AvailableSpace,
12406    window: &mut Window,
12407    cx: &mut Context<Editor>,
12408) -> Option<Size<Pixels>> {
12409    let width = known_dimensions.width.or({
12410        if let AvailableSpace::Definite(available_width) = available_width {
12411            Some(available_width)
12412        } else {
12413            None
12414        }
12415    })?;
12416    if let Some(height) = known_dimensions.height {
12417        return Some(size(width, height));
12418    }
12419
12420    let style = editor.style.as_ref().unwrap();
12421    let font_id = window.text_system().resolve_font(&style.text.font());
12422    let font_size = style.text.font_size.to_pixels(window.rem_size());
12423    let line_height = style.text.line_height_in_pixels(window.rem_size());
12424    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
12425
12426    let mut snapshot = editor.snapshot(window, cx);
12427    let gutter_dimensions = snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
12428
12429    editor.gutter_dimensions = gutter_dimensions;
12430    let text_width = width - gutter_dimensions.width;
12431    let overscroll = size(em_width, px(0.));
12432
12433    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
12434    let wrap_width = calculate_wrap_width(editor.soft_wrap_mode(cx), editor_width, em_width);
12435    if wrap_width.is_some() && editor.set_wrap_width(wrap_width, cx) {
12436        snapshot = editor.snapshot(window, cx);
12437    }
12438
12439    let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
12440
12441    let min_height = line_height * min_lines as f32;
12442    let content_height = scroll_height.max(min_height);
12443
12444    let final_height = if let Some(max_lines) = max_lines {
12445        let max_height = line_height * max_lines as f32;
12446        content_height.min(max_height)
12447    } else {
12448        content_height
12449    };
12450
12451    Some(size(width, final_height))
12452}
12453
12454#[cfg(test)]
12455mod tests {
12456    use super::*;
12457    use crate::{
12458        Editor, MultiBuffer, SelectionEffects,
12459        display_map::{BlockPlacement, BlockProperties},
12460        editor_tests::{init_test, update_test_language_settings},
12461    };
12462    use gpui::{TestAppContext, VisualTestContext};
12463    use language::{Buffer, language_settings, tree_sitter_python};
12464    use log::info;
12465    use rand::{RngCore, rngs::StdRng};
12466    use std::num::NonZeroU32;
12467    use util::test::sample_text;
12468
12469    #[gpui::test]
12470    async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
12471        init_test(cx, |_| {});
12472        let window = cx.add_window(|window, cx| {
12473            let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12474            let mut editor = Editor::new(
12475                EditorMode::AutoHeight {
12476                    min_lines: 1,
12477                    max_lines: None,
12478                },
12479                buffer,
12480                None,
12481                window,
12482                cx,
12483            );
12484            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12485            editor
12486        });
12487        let cx = &mut VisualTestContext::from_window(*window, cx);
12488        let editor = window.root(cx).unwrap();
12489        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12490
12491        for x in 1..=100 {
12492            let (_, state) = cx.draw(
12493                Default::default(),
12494                size(px(200. + 0.13 * x as f32), px(500.)),
12495                |_, _| EditorElement::new(&editor, style.clone()),
12496            );
12497
12498            assert!(
12499                state.position_map.scroll_max.x == 0.,
12500                "Soft wrapped editor should have no horizontal scrolling!"
12501            );
12502        }
12503    }
12504
12505    #[gpui::test]
12506    async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
12507        init_test(cx, |_| {});
12508        let window = cx.add_window(|window, cx| {
12509            let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12510            let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
12511            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12512            editor
12513        });
12514        let cx = &mut VisualTestContext::from_window(*window, cx);
12515        let editor = window.root(cx).unwrap();
12516        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12517
12518        for x in 1..=100 {
12519            let (_, state) = cx.draw(
12520                Default::default(),
12521                size(px(200. + 0.13 * x as f32), px(500.)),
12522                |_, _| EditorElement::new(&editor, style.clone()),
12523            );
12524
12525            assert!(
12526                state.position_map.scroll_max.x == 0.,
12527                "Soft wrapped editor should have no horizontal scrolling!"
12528            );
12529        }
12530    }
12531
12532    #[gpui::test]
12533    fn test_layout_line_numbers(cx: &mut TestAppContext) {
12534        init_test(cx, |_| {});
12535        let window = cx.add_window(|window, cx| {
12536            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12537            Editor::new(EditorMode::full(), buffer, None, window, cx)
12538        });
12539
12540        let editor = window.root(cx).unwrap();
12541        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12542        let line_height = window
12543            .update(cx, |_, window, _| {
12544                style.text.line_height_in_pixels(window.rem_size())
12545            })
12546            .unwrap();
12547        let element = EditorElement::new(&editor, style);
12548        let snapshot = window
12549            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12550            .unwrap();
12551
12552        let layouts = cx
12553            .update_window(*window, |_, window, cx| {
12554                element.layout_line_numbers(
12555                    None,
12556                    GutterDimensions {
12557                        left_padding: Pixels::ZERO,
12558                        right_padding: Pixels::ZERO,
12559                        width: px(30.0),
12560                        margin: Pixels::ZERO,
12561                        git_blame_entries_width: None,
12562                    },
12563                    line_height,
12564                    gpui::Point::default(),
12565                    DisplayRow(0)..DisplayRow(6),
12566                    &(0..6)
12567                        .map(|row| RowInfo {
12568                            buffer_row: Some(row),
12569                            ..Default::default()
12570                        })
12571                        .collect::<Vec<_>>(),
12572                    &BTreeMap::default(),
12573                    Some(DisplayRow(0)),
12574                    &snapshot,
12575                    window,
12576                    cx,
12577                )
12578            })
12579            .unwrap();
12580        assert_eq!(layouts.len(), 6);
12581
12582        let relative_rows = window
12583            .update(cx, |editor, window, cx| {
12584                let snapshot = editor.snapshot(window, cx);
12585                snapshot.calculate_relative_line_numbers(
12586                    &(DisplayRow(0)..DisplayRow(6)),
12587                    DisplayRow(3),
12588                    false,
12589                )
12590            })
12591            .unwrap();
12592        assert_eq!(relative_rows[&DisplayRow(0)], 3);
12593        assert_eq!(relative_rows[&DisplayRow(1)], 2);
12594        assert_eq!(relative_rows[&DisplayRow(2)], 1);
12595        // current line has no relative number
12596        assert!(!relative_rows.contains_key(&DisplayRow(3)));
12597        assert_eq!(relative_rows[&DisplayRow(4)], 1);
12598        assert_eq!(relative_rows[&DisplayRow(5)], 2);
12599
12600        // works if cursor is before screen
12601        let relative_rows = window
12602            .update(cx, |editor, window, cx| {
12603                let snapshot = editor.snapshot(window, cx);
12604                snapshot.calculate_relative_line_numbers(
12605                    &(DisplayRow(3)..DisplayRow(6)),
12606                    DisplayRow(1),
12607                    false,
12608                )
12609            })
12610            .unwrap();
12611        assert_eq!(relative_rows.len(), 3);
12612        assert_eq!(relative_rows[&DisplayRow(3)], 2);
12613        assert_eq!(relative_rows[&DisplayRow(4)], 3);
12614        assert_eq!(relative_rows[&DisplayRow(5)], 4);
12615
12616        // works if cursor is after screen
12617        let relative_rows = window
12618            .update(cx, |editor, window, cx| {
12619                let snapshot = editor.snapshot(window, cx);
12620                snapshot.calculate_relative_line_numbers(
12621                    &(DisplayRow(0)..DisplayRow(3)),
12622                    DisplayRow(6),
12623                    false,
12624                )
12625            })
12626            .unwrap();
12627        assert_eq!(relative_rows.len(), 3);
12628        assert_eq!(relative_rows[&DisplayRow(0)], 5);
12629        assert_eq!(relative_rows[&DisplayRow(1)], 4);
12630        assert_eq!(relative_rows[&DisplayRow(2)], 3);
12631
12632        const DELETED_LINE: u32 = 3;
12633        let layouts = cx
12634            .update_window(*window, |_, window, cx| {
12635                element.layout_line_numbers(
12636                    None,
12637                    GutterDimensions {
12638                        left_padding: Pixels::ZERO,
12639                        right_padding: Pixels::ZERO,
12640                        width: px(30.0),
12641                        margin: Pixels::ZERO,
12642                        git_blame_entries_width: None,
12643                    },
12644                    line_height,
12645                    gpui::Point::default(),
12646                    DisplayRow(0)..DisplayRow(6),
12647                    &(0..6)
12648                        .map(|row| RowInfo {
12649                            buffer_row: Some(row),
12650                            diff_status: (row == DELETED_LINE).then(|| {
12651                                DiffHunkStatus::deleted(
12652                                    buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12653                                )
12654                            }),
12655                            ..Default::default()
12656                        })
12657                        .collect::<Vec<_>>(),
12658                    &BTreeMap::default(),
12659                    Some(DisplayRow(0)),
12660                    &snapshot,
12661                    window,
12662                    cx,
12663                )
12664            })
12665            .unwrap();
12666        assert_eq!(layouts.len(), 5,);
12667        assert!(
12668            layouts.get(&MultiBufferRow(DELETED_LINE)).is_none(),
12669            "Deleted line should not have a line number"
12670        );
12671    }
12672
12673    #[gpui::test]
12674    async fn test_layout_line_numbers_with_folded_lines(cx: &mut TestAppContext) {
12675        init_test(cx, |_| {});
12676
12677        let python_lang = languages::language("python", tree_sitter_python::LANGUAGE.into());
12678
12679        let window = cx.add_window(|window, cx| {
12680            let buffer = cx.new(|cx| {
12681                Buffer::local(
12682                    indoc::indoc! {"
12683                        fn test() -> int {
12684                            return 2;
12685                        }
12686
12687                        fn another_test() -> int {
12688                            # This is a very peculiar method that is hard to grasp.
12689                            return 4;
12690                        }
12691                    "},
12692                    cx,
12693                )
12694                .with_language(python_lang, cx)
12695            });
12696
12697            let buffer = MultiBuffer::build_from_buffer(buffer, cx);
12698            Editor::new(EditorMode::full(), buffer, None, window, cx)
12699        });
12700
12701        let editor = window.root(cx).unwrap();
12702        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12703        let line_height = window
12704            .update(cx, |_, window, _| {
12705                style.text.line_height_in_pixels(window.rem_size())
12706            })
12707            .unwrap();
12708        let element = EditorElement::new(&editor, style);
12709        let snapshot = window
12710            .update(cx, |editor, window, cx| {
12711                editor.fold_at(MultiBufferRow(0), window, cx);
12712                editor.snapshot(window, cx)
12713            })
12714            .unwrap();
12715
12716        let layouts = cx
12717            .update_window(*window, |_, window, cx| {
12718                element.layout_line_numbers(
12719                    None,
12720                    GutterDimensions {
12721                        left_padding: Pixels::ZERO,
12722                        right_padding: Pixels::ZERO,
12723                        width: px(30.0),
12724                        margin: Pixels::ZERO,
12725                        git_blame_entries_width: None,
12726                    },
12727                    line_height,
12728                    gpui::Point::default(),
12729                    DisplayRow(0)..DisplayRow(6),
12730                    &(0..6)
12731                        .map(|row| RowInfo {
12732                            buffer_row: Some(row),
12733                            ..Default::default()
12734                        })
12735                        .collect::<Vec<_>>(),
12736                    &BTreeMap::default(),
12737                    Some(DisplayRow(3)),
12738                    &snapshot,
12739                    window,
12740                    cx,
12741                )
12742            })
12743            .unwrap();
12744        assert_eq!(layouts.len(), 6);
12745
12746        let relative_rows = window
12747            .update(cx, |editor, window, cx| {
12748                let snapshot = editor.snapshot(window, cx);
12749                snapshot.calculate_relative_line_numbers(
12750                    &(DisplayRow(0)..DisplayRow(6)),
12751                    DisplayRow(3),
12752                    false,
12753                )
12754            })
12755            .unwrap();
12756        assert_eq!(relative_rows[&DisplayRow(0)], 3);
12757        assert_eq!(relative_rows[&DisplayRow(1)], 2);
12758        assert_eq!(relative_rows[&DisplayRow(2)], 1);
12759        // current line has no relative number
12760        assert!(!relative_rows.contains_key(&DisplayRow(3)));
12761        assert_eq!(relative_rows[&DisplayRow(4)], 1);
12762        assert_eq!(relative_rows[&DisplayRow(5)], 2);
12763    }
12764
12765    #[gpui::test]
12766    fn test_layout_line_numbers_wrapping(cx: &mut TestAppContext) {
12767        init_test(cx, |_| {});
12768        let window = cx.add_window(|window, cx| {
12769            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12770            Editor::new(EditorMode::full(), buffer, None, window, cx)
12771        });
12772
12773        update_test_language_settings(cx, &|s| {
12774            s.defaults.preferred_line_length = Some(5_u32);
12775            s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
12776        });
12777
12778        let editor = window.root(cx).unwrap();
12779        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12780        let line_height = window
12781            .update(cx, |_, window, _| {
12782                style.text.line_height_in_pixels(window.rem_size())
12783            })
12784            .unwrap();
12785        let element = EditorElement::new(&editor, style);
12786        let snapshot = window
12787            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12788            .unwrap();
12789
12790        let layouts = cx
12791            .update_window(*window, |_, window, cx| {
12792                element.layout_line_numbers(
12793                    None,
12794                    GutterDimensions {
12795                        left_padding: Pixels::ZERO,
12796                        right_padding: Pixels::ZERO,
12797                        width: px(30.0),
12798                        margin: Pixels::ZERO,
12799                        git_blame_entries_width: None,
12800                    },
12801                    line_height,
12802                    gpui::Point::default(),
12803                    DisplayRow(0)..DisplayRow(6),
12804                    &(0..6)
12805                        .map(|row| RowInfo {
12806                            buffer_row: Some(row),
12807                            ..Default::default()
12808                        })
12809                        .collect::<Vec<_>>(),
12810                    &BTreeMap::default(),
12811                    Some(DisplayRow(0)),
12812                    &snapshot,
12813                    window,
12814                    cx,
12815                )
12816            })
12817            .unwrap();
12818        assert_eq!(layouts.len(), 3);
12819
12820        let relative_rows = window
12821            .update(cx, |editor, window, cx| {
12822                let snapshot = editor.snapshot(window, cx);
12823                snapshot.calculate_relative_line_numbers(
12824                    &(DisplayRow(0)..DisplayRow(6)),
12825                    DisplayRow(3),
12826                    true,
12827                )
12828            })
12829            .unwrap();
12830
12831        assert_eq!(relative_rows[&DisplayRow(0)], 3);
12832        assert_eq!(relative_rows[&DisplayRow(1)], 2);
12833        assert_eq!(relative_rows[&DisplayRow(2)], 1);
12834        // current line has no relative number
12835        assert!(!relative_rows.contains_key(&DisplayRow(3)));
12836        assert_eq!(relative_rows[&DisplayRow(4)], 1);
12837        assert_eq!(relative_rows[&DisplayRow(5)], 2);
12838
12839        let layouts = cx
12840            .update_window(*window, |_, window, cx| {
12841                element.layout_line_numbers(
12842                    None,
12843                    GutterDimensions {
12844                        left_padding: Pixels::ZERO,
12845                        right_padding: Pixels::ZERO,
12846                        width: px(30.0),
12847                        margin: Pixels::ZERO,
12848                        git_blame_entries_width: None,
12849                    },
12850                    line_height,
12851                    gpui::Point::default(),
12852                    DisplayRow(0)..DisplayRow(6),
12853                    &(0..6)
12854                        .map(|row| RowInfo {
12855                            buffer_row: Some(row),
12856                            diff_status: Some(DiffHunkStatus::deleted(
12857                                buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12858                            )),
12859                            ..Default::default()
12860                        })
12861                        .collect::<Vec<_>>(),
12862                    &BTreeMap::from_iter([(DisplayRow(0), LineHighlightSpec::default())]),
12863                    Some(DisplayRow(0)),
12864                    &snapshot,
12865                    window,
12866                    cx,
12867                )
12868            })
12869            .unwrap();
12870        assert!(
12871            layouts.is_empty(),
12872            "Deleted lines should have no line number"
12873        );
12874
12875        let relative_rows = window
12876            .update(cx, |editor, window, cx| {
12877                let snapshot = editor.snapshot(window, cx);
12878                snapshot.calculate_relative_line_numbers(
12879                    &(DisplayRow(0)..DisplayRow(6)),
12880                    DisplayRow(3),
12881                    true,
12882                )
12883            })
12884            .unwrap();
12885
12886        // Deleted lines should still have relative numbers
12887        assert_eq!(relative_rows[&DisplayRow(0)], 3);
12888        assert_eq!(relative_rows[&DisplayRow(1)], 2);
12889        assert_eq!(relative_rows[&DisplayRow(2)], 1);
12890        // current line, even if deleted, has no relative number
12891        assert!(!relative_rows.contains_key(&DisplayRow(3)));
12892        assert_eq!(relative_rows[&DisplayRow(4)], 1);
12893        assert_eq!(relative_rows[&DisplayRow(5)], 2);
12894    }
12895
12896    #[gpui::test]
12897    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
12898        init_test(cx, |_| {});
12899
12900        let window = cx.add_window(|window, cx| {
12901            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
12902            Editor::new(EditorMode::full(), buffer, None, window, cx)
12903        });
12904        let cx = &mut VisualTestContext::from_window(*window, cx);
12905        let editor = window.root(cx).unwrap();
12906        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12907
12908        window
12909            .update(cx, |editor, window, cx| {
12910                editor.cursor_offset_on_selection = true;
12911                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
12912                    s.select_ranges([
12913                        Point::new(0, 0)..Point::new(1, 0),
12914                        Point::new(3, 2)..Point::new(3, 3),
12915                        Point::new(5, 6)..Point::new(6, 0),
12916                    ]);
12917                });
12918            })
12919            .unwrap();
12920
12921        let (_, state) = cx.draw(
12922            point(px(500.), px(500.)),
12923            size(px(500.), px(500.)),
12924            |_, _| EditorElement::new(&editor, style),
12925        );
12926
12927        assert_eq!(state.selections.len(), 1);
12928        let local_selections = &state.selections[0].1;
12929        assert_eq!(local_selections.len(), 3);
12930        // moves cursor back one line
12931        assert_eq!(
12932            local_selections[0].head,
12933            DisplayPoint::new(DisplayRow(0), 6)
12934        );
12935        assert_eq!(
12936            local_selections[0].range,
12937            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
12938        );
12939
12940        // moves cursor back one column
12941        assert_eq!(
12942            local_selections[1].range,
12943            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
12944        );
12945        assert_eq!(
12946            local_selections[1].head,
12947            DisplayPoint::new(DisplayRow(3), 2)
12948        );
12949
12950        // leaves cursor on the max point
12951        assert_eq!(
12952            local_selections[2].range,
12953            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
12954        );
12955        assert_eq!(
12956            local_selections[2].head,
12957            DisplayPoint::new(DisplayRow(6), 0)
12958        );
12959
12960        // active lines does not include 1 (even though the range of the selection does)
12961        assert_eq!(
12962            state.active_rows.keys().cloned().collect::<Vec<_>>(),
12963            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
12964        );
12965    }
12966
12967    #[gpui::test]
12968    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
12969        init_test(cx, |_| {});
12970
12971        let window = cx.add_window(|window, cx| {
12972            let buffer = MultiBuffer::build_simple("", cx);
12973            Editor::new(EditorMode::full(), buffer, None, window, cx)
12974        });
12975        let cx = &mut VisualTestContext::from_window(*window, cx);
12976        let editor = window.root(cx).unwrap();
12977        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12978        window
12979            .update(cx, |editor, window, cx| {
12980                editor.set_placeholder_text("hello", window, cx);
12981                editor.insert_blocks(
12982                    [BlockProperties {
12983                        style: BlockStyle::Fixed,
12984                        placement: BlockPlacement::Above(Anchor::Min),
12985                        height: Some(3),
12986                        render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
12987                        priority: 0,
12988                    }],
12989                    None,
12990                    cx,
12991                );
12992
12993                // Blur the editor so that it displays placeholder text.
12994                window.blur();
12995            })
12996            .unwrap();
12997
12998        let (_, state) = cx.draw(
12999            point(px(500.), px(500.)),
13000            size(px(500.), px(500.)),
13001            |_, _| EditorElement::new(&editor, style),
13002        );
13003        assert_eq!(state.position_map.line_layouts.len(), 4);
13004        assert_eq!(state.line_numbers.len(), 1);
13005        assert_eq!(
13006            state
13007                .line_numbers
13008                .get(&MultiBufferRow(0))
13009                .map(|line_number| line_number
13010                    .segments
13011                    .first()
13012                    .unwrap()
13013                    .shaped_line
13014                    .text
13015                    .as_ref()),
13016            Some("1")
13017        );
13018    }
13019
13020    #[gpui::test]
13021    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
13022        const TAB_SIZE: u32 = 4;
13023
13024        let input_text = "\t \t|\t| a b";
13025        let expected_invisibles = vec![
13026            Invisible::Tab {
13027                line_start_offset: 0,
13028                line_end_offset: TAB_SIZE as usize,
13029            },
13030            Invisible::Whitespace {
13031                line_offset: TAB_SIZE as usize,
13032            },
13033            Invisible::Tab {
13034                line_start_offset: TAB_SIZE as usize + 1,
13035                line_end_offset: TAB_SIZE as usize * 2,
13036            },
13037            Invisible::Tab {
13038                line_start_offset: TAB_SIZE as usize * 2 + 1,
13039                line_end_offset: TAB_SIZE as usize * 3,
13040            },
13041            Invisible::Whitespace {
13042                line_offset: TAB_SIZE as usize * 3 + 1,
13043            },
13044            Invisible::Whitespace {
13045                line_offset: TAB_SIZE as usize * 3 + 3,
13046            },
13047        ];
13048        assert_eq!(
13049            expected_invisibles.len(),
13050            input_text
13051                .chars()
13052                .filter(|initial_char| initial_char.is_whitespace())
13053                .count(),
13054            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
13055        );
13056
13057        for show_line_numbers in [true, false] {
13058            init_test(cx, |s| {
13059                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
13060                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
13061            });
13062
13063            let actual_invisibles = collect_invisibles_from_new_editor(
13064                cx,
13065                EditorMode::full(),
13066                input_text,
13067                px(500.0),
13068                show_line_numbers,
13069            );
13070
13071            assert_eq!(expected_invisibles, actual_invisibles);
13072        }
13073    }
13074
13075    #[gpui::test]
13076    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
13077        init_test(cx, |s| {
13078            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
13079            s.defaults.tab_size = NonZeroU32::new(4);
13080        });
13081
13082        for editor_mode_without_invisibles in [
13083            EditorMode::SingleLine,
13084            EditorMode::AutoHeight {
13085                min_lines: 1,
13086                max_lines: Some(100),
13087            },
13088        ] {
13089            for show_line_numbers in [true, false] {
13090                let invisibles = collect_invisibles_from_new_editor(
13091                    cx,
13092                    editor_mode_without_invisibles.clone(),
13093                    "\t\t\t| | a b",
13094                    px(500.0),
13095                    show_line_numbers,
13096                );
13097                assert!(
13098                    invisibles.is_empty(),
13099                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
13100                );
13101            }
13102        }
13103    }
13104
13105    #[gpui::test]
13106    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
13107        let tab_size = 4;
13108        let input_text = "a\tbcd     ".repeat(9);
13109        let repeated_invisibles = [
13110            Invisible::Tab {
13111                line_start_offset: 1,
13112                line_end_offset: tab_size as usize,
13113            },
13114            Invisible::Whitespace {
13115                line_offset: tab_size as usize + 3,
13116            },
13117            Invisible::Whitespace {
13118                line_offset: tab_size as usize + 4,
13119            },
13120            Invisible::Whitespace {
13121                line_offset: tab_size as usize + 5,
13122            },
13123            Invisible::Whitespace {
13124                line_offset: tab_size as usize + 6,
13125            },
13126            Invisible::Whitespace {
13127                line_offset: tab_size as usize + 7,
13128            },
13129        ];
13130        let expected_invisibles = std::iter::once(repeated_invisibles)
13131            .cycle()
13132            .take(9)
13133            .flatten()
13134            .collect::<Vec<_>>();
13135        assert_eq!(
13136            expected_invisibles.len(),
13137            input_text
13138                .chars()
13139                .filter(|initial_char| initial_char.is_whitespace())
13140                .count(),
13141            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
13142        );
13143        info!("Expected invisibles: {expected_invisibles:?}");
13144
13145        init_test(cx, |_| {});
13146
13147        // Put the same string with repeating whitespace pattern into editors of various size,
13148        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
13149        let resize_step = 10.0;
13150        let mut editor_width = 200.0;
13151        while editor_width <= 1000.0 {
13152            for show_line_numbers in [true, false] {
13153                update_test_language_settings(cx, &|s| {
13154                    s.defaults.tab_size = NonZeroU32::new(tab_size);
13155                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
13156                    s.defaults.preferred_line_length = Some(editor_width as u32);
13157                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
13158                });
13159
13160                let actual_invisibles = collect_invisibles_from_new_editor(
13161                    cx,
13162                    EditorMode::full(),
13163                    &input_text,
13164                    px(editor_width),
13165                    show_line_numbers,
13166                );
13167
13168                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
13169                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
13170                let mut i = 0;
13171                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
13172                    i = actual_index;
13173                    match expected_invisibles.get(i) {
13174                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
13175                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
13176                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
13177                            _ => {
13178                                panic!(
13179                                    "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
13180                                )
13181                            }
13182                        },
13183                        None => {
13184                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
13185                        }
13186                    }
13187                }
13188                let missing_expected_invisibles = &expected_invisibles[i + 1..];
13189                assert!(
13190                    missing_expected_invisibles.is_empty(),
13191                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
13192                );
13193
13194                editor_width += resize_step;
13195            }
13196        }
13197    }
13198
13199    fn collect_invisibles_from_new_editor(
13200        cx: &mut TestAppContext,
13201        editor_mode: EditorMode,
13202        input_text: &str,
13203        editor_width: Pixels,
13204        show_line_numbers: bool,
13205    ) -> Vec<Invisible> {
13206        info!(
13207            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
13208            f32::from(editor_width)
13209        );
13210        let window = cx.add_window(|window, cx| {
13211            let buffer = MultiBuffer::build_simple(input_text, cx);
13212            Editor::new(editor_mode, buffer, None, window, cx)
13213        });
13214        let cx = &mut VisualTestContext::from_window(*window, cx);
13215        let editor = window.root(cx).unwrap();
13216
13217        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
13218        window
13219            .update(cx, |editor, _, cx| {
13220                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
13221                editor.set_wrap_width(Some(editor_width), cx);
13222                editor.set_show_line_numbers(show_line_numbers, cx);
13223            })
13224            .unwrap();
13225        let (_, state) = cx.draw(
13226            point(px(500.), px(500.)),
13227            size(px(500.), px(500.)),
13228            |_, _| EditorElement::new(&editor, style),
13229        );
13230        state
13231            .position_map
13232            .line_layouts
13233            .iter()
13234            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
13235            .cloned()
13236            .collect()
13237    }
13238
13239    #[gpui::test]
13240    fn test_merge_overlapping_ranges() {
13241        let base_bg = Hsla::white();
13242        let color1 = Hsla {
13243            h: 0.0,
13244            s: 0.5,
13245            l: 0.5,
13246            a: 0.5,
13247        };
13248        let color2 = Hsla {
13249            h: 120.0,
13250            s: 0.5,
13251            l: 0.5,
13252            a: 0.5,
13253        };
13254
13255        let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
13256        let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
13257            v.iter()
13258                .map(|(r, _)| (r.start.column(), r.end.column()))
13259                .collect()
13260        };
13261
13262        // Test overlapping ranges blend colors
13263        let overlapping = vec![
13264            (display_point(5)..display_point(15), color1),
13265            (display_point(10)..display_point(20), color2),
13266        ];
13267        let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
13268        assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
13269
13270        // Test middle segment should have blended color
13271        let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
13272        assert_eq!(result[1].1, blended);
13273
13274        // Test adjacent same-color ranges merge
13275        let adjacent_same = vec![
13276            (display_point(5)..display_point(10), color1),
13277            (display_point(10)..display_point(15), color1),
13278        ];
13279        let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
13280        assert_eq!(cols(&result), vec![(5, 15)]);
13281
13282        // Test contained range splits
13283        let contained = vec![
13284            (display_point(5)..display_point(20), color1),
13285            (display_point(10)..display_point(15), color2),
13286        ];
13287        let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
13288        assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
13289
13290        // Test multiple overlaps split at every boundary
13291        let color3 = Hsla {
13292            h: 240.0,
13293            s: 0.5,
13294            l: 0.5,
13295            a: 0.5,
13296        };
13297        let complex = vec![
13298            (display_point(5)..display_point(12), color1),
13299            (display_point(8)..display_point(16), color2),
13300            (display_point(10)..display_point(14), color3),
13301        ];
13302        let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
13303        assert_eq!(
13304            cols(&result),
13305            vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
13306        );
13307    }
13308
13309    #[gpui::test]
13310    fn test_bg_segments_per_row() {
13311        let base_bg = Hsla::white();
13312
13313        // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
13314        {
13315            let selection_color = Hsla {
13316                h: 200.0,
13317                s: 0.5,
13318                l: 0.5,
13319                a: 0.5,
13320            };
13321            let player_color = PlayerColor {
13322                cursor: selection_color,
13323                background: selection_color,
13324                selection: selection_color,
13325            };
13326
13327            let spanning_selection = SelectionLayout {
13328                head: DisplayPoint::new(DisplayRow(3), 7),
13329                cursor_shape: CursorShape::Bar,
13330                is_newest: true,
13331                is_local: true,
13332                range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
13333                active_rows: DisplayRow(1)..DisplayRow(4),
13334                user_name: None,
13335            };
13336
13337            let selections = vec![(player_color, vec![spanning_selection])];
13338            let result = EditorElement::bg_segments_per_row(
13339                DisplayRow(0)..DisplayRow(5),
13340                &selections,
13341                &[],
13342                base_bg,
13343            );
13344
13345            assert_eq!(result.len(), 5);
13346            assert!(result[0].is_empty());
13347            assert_eq!(result[1].len(), 1);
13348            assert_eq!(result[2].len(), 1);
13349            assert_eq!(result[3].len(), 1);
13350            assert!(result[4].is_empty());
13351
13352            assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13353            assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13354            assert_eq!(result[1][0].0.end.column(), u32::MAX);
13355            assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13356            assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13357            assert_eq!(result[2][0].0.end.column(), u32::MAX);
13358            assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
13359            assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
13360        }
13361
13362        // Case B: selection ends exactly at the start of row 3, excluding row 3
13363        {
13364            let selection_color = Hsla {
13365                h: 120.0,
13366                s: 0.5,
13367                l: 0.5,
13368                a: 0.5,
13369            };
13370            let player_color = PlayerColor {
13371                cursor: selection_color,
13372                background: selection_color,
13373                selection: selection_color,
13374            };
13375
13376            let selection = SelectionLayout {
13377                head: DisplayPoint::new(DisplayRow(2), 0),
13378                cursor_shape: CursorShape::Bar,
13379                is_newest: true,
13380                is_local: true,
13381                range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
13382                active_rows: DisplayRow(1)..DisplayRow(3),
13383                user_name: None,
13384            };
13385
13386            let selections = vec![(player_color, vec![selection])];
13387            let result = EditorElement::bg_segments_per_row(
13388                DisplayRow(0)..DisplayRow(4),
13389                &selections,
13390                &[],
13391                base_bg,
13392            );
13393
13394            assert_eq!(result.len(), 4);
13395            assert!(result[0].is_empty());
13396            assert_eq!(result[1].len(), 1);
13397            assert_eq!(result[2].len(), 1);
13398            assert!(result[3].is_empty());
13399
13400            assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13401            assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13402            assert_eq!(result[1][0].0.end.column(), u32::MAX);
13403            assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13404            assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13405            assert_eq!(result[2][0].0.end.column(), u32::MAX);
13406        }
13407    }
13408
13409    #[cfg(test)]
13410    fn generate_test_run(len: usize, color: Hsla) -> TextRun {
13411        TextRun {
13412            len,
13413            color,
13414            ..Default::default()
13415        }
13416    }
13417
13418    #[gpui::test]
13419    fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
13420        init_test(cx, |_| {});
13421
13422        let dx = |start: u32, end: u32| {
13423            DisplayPoint::new(DisplayRow(0), start)..DisplayPoint::new(DisplayRow(0), end)
13424        };
13425
13426        let text_color = Hsla {
13427            h: 210.0,
13428            s: 0.1,
13429            l: 0.4,
13430            a: 1.0,
13431        };
13432        let bg_1 = Hsla {
13433            h: 30.0,
13434            s: 0.6,
13435            l: 0.8,
13436            a: 1.0,
13437        };
13438        let bg_2 = Hsla {
13439            h: 200.0,
13440            s: 0.6,
13441            l: 0.2,
13442            a: 1.0,
13443        };
13444        let min_contrast = 45.0;
13445        let adjusted_bg1 = ensure_minimum_contrast(text_color, bg_1, min_contrast);
13446        let adjusted_bg2 = ensure_minimum_contrast(text_color, bg_2, min_contrast);
13447
13448        // Case A: single run; disjoint segments inside the run
13449        {
13450            let runs = vec![generate_test_run(20, text_color)];
13451            let segs = vec![(dx(5, 10), bg_1), (dx(12, 16), bg_2)];
13452            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13453            // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
13454            assert_eq!(
13455                out.iter().map(|r| r.len).collect::<Vec<_>>(),
13456                vec![5, 5, 2, 4, 4]
13457            );
13458            assert_eq!(out[0].color, text_color);
13459            assert_eq!(out[1].color, adjusted_bg1);
13460            assert_eq!(out[2].color, text_color);
13461            assert_eq!(out[3].color, adjusted_bg2);
13462            assert_eq!(out[4].color, text_color);
13463        }
13464
13465        // Case B: multiple runs; segment extends to end of line (u32::MAX)
13466        {
13467            let runs = vec![
13468                generate_test_run(8, text_color),
13469                generate_test_run(7, text_color),
13470            ];
13471            let segs = vec![(dx(6, u32::MAX), bg_1)];
13472            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13473            // Expected slices across runs: [0,6) [6,8) | [0,7)
13474            assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
13475            assert_eq!(out[0].color, text_color);
13476            assert_eq!(out[1].color, adjusted_bg1);
13477            assert_eq!(out[2].color, adjusted_bg1);
13478        }
13479
13480        // Case C: multi-byte characters
13481        {
13482            // for text: "Hello 🌍 δΈ–η•Œ!"
13483            let runs = vec![
13484                generate_test_run(5, text_color), // "Hello"
13485                generate_test_run(6, text_color), // " 🌍 "
13486                generate_test_run(6, text_color), // "δΈ–η•Œ"
13487                generate_test_run(1, text_color), // "!"
13488            ];
13489            // selecting "🌍 δΈ–"
13490            let segs = vec![(dx(6, 14), bg_1)];
13491            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13492            // "Hello" | " " | "🌍 " | "δΈ–" | "η•Œ" | "!"
13493            assert_eq!(
13494                out.iter().map(|r| r.len).collect::<Vec<_>>(),
13495                vec![5, 1, 5, 3, 3, 1]
13496            );
13497            assert_eq!(out[0].color, text_color); // "Hello"
13498            assert_eq!(out[2].color, adjusted_bg1); // "🌍 "
13499            assert_eq!(out[3].color, adjusted_bg1); // "δΈ–"
13500            assert_eq!(out[4].color, text_color); // "η•Œ"
13501            assert_eq!(out[5].color, text_color); // "!"
13502        }
13503
13504        // Case D: split multiple consecutive text runs with segments
13505        {
13506            let segs = vec![
13507                (dx(2, 4), bg_1),   // selecting "cd"
13508                (dx(4, 8), bg_2),   // selecting "efgh"
13509                (dx(9, 11), bg_1),  // selecting "jk"
13510                (dx(12, 16), bg_2), // selecting "mnop"
13511                (dx(18, 19), bg_1), // selecting "s"
13512            ];
13513
13514            // for text: "abcdef"
13515            let runs = vec![
13516                generate_test_run(2, text_color), // ab
13517                generate_test_run(4, text_color), // cdef
13518            ];
13519            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13520            // new splits "ab", "cd", "ef"
13521            assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![2, 2, 2]);
13522            assert_eq!(out[0].color, text_color);
13523            assert_eq!(out[1].color, adjusted_bg1);
13524            assert_eq!(out[2].color, adjusted_bg2);
13525
13526            // for text: "ghijklmn"
13527            let runs = vec![
13528                generate_test_run(3, text_color), // ghi
13529                generate_test_run(2, text_color), // jk
13530                generate_test_run(3, text_color), // lmn
13531            ];
13532            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 6); // 2 + 4 from first run
13533            // new splits "gh", "i", "jk", "l", "mn"
13534            assert_eq!(
13535                out.iter().map(|r| r.len).collect::<Vec<_>>(),
13536                vec![2, 1, 2, 1, 2]
13537            );
13538            assert_eq!(out[0].color, adjusted_bg2);
13539            assert_eq!(out[1].color, text_color);
13540            assert_eq!(out[2].color, adjusted_bg1);
13541            assert_eq!(out[3].color, text_color);
13542            assert_eq!(out[4].color, adjusted_bg2);
13543
13544            // for text: "opqrs"
13545            let runs = vec![
13546                generate_test_run(1, text_color), // o
13547                generate_test_run(4, text_color), // pqrs
13548            ];
13549            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 14); // 6 + 3 + 2 + 3 from first two runs
13550            // new splits "o", "p", "qr", "s"
13551            assert_eq!(
13552                out.iter().map(|r| r.len).collect::<Vec<_>>(),
13553                vec![1, 1, 2, 1]
13554            );
13555            assert_eq!(out[0].color, adjusted_bg2);
13556            assert_eq!(out[1].color, adjusted_bg2);
13557            assert_eq!(out[2].color, text_color);
13558            assert_eq!(out[3].color, adjusted_bg1);
13559        }
13560    }
13561
13562    #[test]
13563    fn test_spacer_pattern_period() {
13564        // line height is smaller than target height, so we just return half the line height
13565        assert_eq!(EditorElement::spacer_pattern_period(10.0, 20.0), 5.0);
13566
13567        // line height is exactly half the target height, perfect match
13568        assert_eq!(EditorElement::spacer_pattern_period(20.0, 10.0), 10.0);
13569
13570        // line height is close to half the target height
13571        assert_eq!(EditorElement::spacer_pattern_period(20.0, 9.0), 10.0);
13572
13573        // line height is close to 1/4 the target height
13574        assert_eq!(EditorElement::spacer_pattern_period(20.0, 4.8), 5.0);
13575    }
13576
13577    #[gpui::test(iterations = 100)]
13578    fn test_random_spacer_pattern_period(mut rng: StdRng) {
13579        let line_height = rng.next_u32() as f32;
13580        let target_height = rng.next_u32() as f32;
13581
13582        let result = EditorElement::spacer_pattern_period(line_height, target_height);
13583
13584        let k = line_height / result;
13585        assert!(k - k.round() < 0.0000001); // approximately integer
13586        assert!((k.round() as u32).is_multiple_of(2));
13587    }
13588
13589    #[test]
13590    fn test_calculate_wrap_width() {
13591        let editor_width = px(800.0);
13592        let em_width = px(8.0);
13593
13594        assert_eq!(
13595            calculate_wrap_width(SoftWrap::GitDiff, editor_width, em_width),
13596            None,
13597        );
13598
13599        assert_eq!(
13600            calculate_wrap_width(SoftWrap::None, editor_width, em_width),
13601            Some(px((MAX_LINE_LEN as f32 / 2.0 * 8.0).ceil())),
13602        );
13603
13604        assert_eq!(
13605            calculate_wrap_width(SoftWrap::EditorWidth, editor_width, em_width),
13606            Some(px(800.0)),
13607        );
13608
13609        assert_eq!(
13610            calculate_wrap_width(SoftWrap::Column(72), editor_width, em_width),
13611            Some(px((72.0 * 8.0_f32).ceil())),
13612        );
13613
13614        assert_eq!(
13615            calculate_wrap_width(SoftWrap::Bounded(72), editor_width, em_width),
13616            Some(px((72.0 * 8.0_f32).ceil())),
13617        );
13618        assert_eq!(
13619            calculate_wrap_width(SoftWrap::Bounded(200), px(400.0), em_width),
13620            Some(px(400.0)),
13621        );
13622    }
13623}