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