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            sticky_row,
 4601            start_point,
 4602            offset,
 4603        } in rows.into_iter().rev()
 4604        {
 4605            let line = layout_line(
 4606                sticky_row,
 4607                snapshot,
 4608                &self.style,
 4609                editor_width,
 4610                is_row_soft_wrapped,
 4611                window,
 4612                cx,
 4613            );
 4614
 4615            let line_number = show_line_numbers.then(|| {
 4616                let start_display_row = start_point.to_display_point(snapshot).row();
 4617                let relative_number = relative_to
 4618                    .filter(|_| relative_line_numbers != RelativeLineNumbers::Disabled)
 4619                    .map(|base| {
 4620                        snapshot.relative_line_delta(
 4621                            base,
 4622                            start_display_row,
 4623                            relative_line_numbers == RelativeLineNumbers::Wrapped,
 4624                        )
 4625                    });
 4626                let number = relative_number
 4627                    .filter(|&delta| delta != 0)
 4628                    .map(|delta| delta.unsigned_abs() as u32)
 4629                    .unwrap_or(start_point.row + 1);
 4630                let color = cx.theme().colors().editor_line_number;
 4631                self.shape_line_number(SharedString::from(number.to_string()), color, window)
 4632            });
 4633
 4634            lines.push(StickyHeaderLine::new(
 4635                sticky_row,
 4636                line_height * offset as f32,
 4637                line,
 4638                line_number,
 4639                line_height,
 4640                scroll_pixel_position,
 4641                content_origin,
 4642                gutter_hitbox,
 4643                text_hitbox,
 4644                window,
 4645                cx,
 4646            ));
 4647        }
 4648
 4649        lines.reverse();
 4650        if lines.is_empty() {
 4651            return None;
 4652        }
 4653
 4654        Some(StickyHeaders {
 4655            lines,
 4656            gutter_background: cx.theme().colors().editor_gutter_background,
 4657            content_background: self.style.background,
 4658            gutter_right_padding: gutter_dimensions.right_padding,
 4659        })
 4660    }
 4661
 4662    pub(crate) fn sticky_headers(editor: &Editor, snapshot: &EditorSnapshot) -> Vec<StickyHeader> {
 4663        let scroll_top = snapshot.scroll_position().y;
 4664
 4665        let mut end_rows = Vec::<DisplayRow>::new();
 4666        let mut rows = Vec::<StickyHeader>::new();
 4667
 4668        for item in editor.sticky_headers.iter().flatten() {
 4669            let start_point = item.range.start.to_point(snapshot.buffer_snapshot());
 4670            let end_point = item.range.end.to_point(snapshot.buffer_snapshot());
 4671
 4672            let sticky_row = snapshot
 4673                .display_snapshot
 4674                .point_to_display_point(start_point, Bias::Left)
 4675                .row();
 4676            let end_row = snapshot
 4677                .display_snapshot
 4678                .point_to_display_point(end_point, Bias::Left)
 4679                .row();
 4680            let max_sticky_row = end_row.previous_row();
 4681            if max_sticky_row <= sticky_row {
 4682                continue;
 4683            }
 4684
 4685            while end_rows
 4686                .last()
 4687                .is_some_and(|&last_end| last_end <= sticky_row)
 4688            {
 4689                end_rows.pop();
 4690            }
 4691            let depth = end_rows.len();
 4692            let adjusted_scroll_top = scroll_top + depth as f64;
 4693
 4694            if sticky_row.as_f64() >= adjusted_scroll_top || end_row.as_f64() <= adjusted_scroll_top
 4695            {
 4696                continue;
 4697            }
 4698
 4699            let max_scroll_offset = max_sticky_row.as_f64() - scroll_top;
 4700            let offset = (depth as f64).min(max_scroll_offset);
 4701
 4702            end_rows.push(end_row);
 4703            rows.push(StickyHeader {
 4704                sticky_row,
 4705                start_point,
 4706                offset,
 4707            });
 4708        }
 4709
 4710        rows
 4711    }
 4712
 4713    fn layout_cursor_popovers(
 4714        &self,
 4715        line_height: Pixels,
 4716        text_hitbox: &Hitbox,
 4717        content_origin: gpui::Point<Pixels>,
 4718        right_margin: Pixels,
 4719        start_row: DisplayRow,
 4720        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 4721        line_layouts: &[LineWithInvisibles],
 4722        cursor: DisplayPoint,
 4723        cursor_point: Point,
 4724        style: &EditorStyle,
 4725        window: &mut Window,
 4726        cx: &mut App,
 4727    ) -> Option<ContextMenuLayout> {
 4728        let mut min_menu_height = Pixels::ZERO;
 4729        let mut max_menu_height = Pixels::ZERO;
 4730        let mut height_above_menu = Pixels::ZERO;
 4731        let height_below_menu = Pixels::ZERO;
 4732        let mut edit_prediction_popover_visible = false;
 4733        let mut context_menu_visible = false;
 4734        let context_menu_placement;
 4735
 4736        {
 4737            let editor = self.editor.read(cx);
 4738            if editor.edit_prediction_visible_in_cursor_popover(editor.has_active_edit_prediction())
 4739            {
 4740                height_above_menu +=
 4741                    editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
 4742                edit_prediction_popover_visible = true;
 4743            }
 4744
 4745            if editor.context_menu_visible()
 4746                && let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin()
 4747            {
 4748                let (min_height_in_lines, max_height_in_lines) = editor
 4749                    .context_menu_options
 4750                    .as_ref()
 4751                    .map_or((3, 12), |options| {
 4752                        (options.min_entries_visible, options.max_entries_visible)
 4753                    });
 4754
 4755                min_menu_height += line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
 4756                max_menu_height += line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
 4757                context_menu_visible = true;
 4758            }
 4759            context_menu_placement = editor
 4760                .context_menu_options
 4761                .as_ref()
 4762                .and_then(|options| options.placement.clone());
 4763        }
 4764
 4765        let visible = edit_prediction_popover_visible || context_menu_visible;
 4766        if !visible {
 4767            return None;
 4768        }
 4769
 4770        let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
 4771        let target_position = content_origin
 4772            + gpui::Point {
 4773                x: cmp::max(
 4774                    px(0.),
 4775                    Pixels::from(
 4776                        ScrollPixelOffset::from(
 4777                            cursor_row_layout.x_for_index(cursor.column() as usize),
 4778                        ) - scroll_pixel_position.x,
 4779                    ),
 4780                ),
 4781                y: cmp::max(
 4782                    px(0.),
 4783                    Pixels::from(
 4784                        cursor.row().next_row().as_f64() * ScrollPixelOffset::from(line_height)
 4785                            - scroll_pixel_position.y,
 4786                    ),
 4787                ),
 4788            };
 4789
 4790        let viewport_bounds =
 4791            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 4792                right: -right_margin - MENU_GAP,
 4793                ..Default::default()
 4794            });
 4795
 4796        let min_height = height_above_menu + min_menu_height + height_below_menu;
 4797        let max_height = height_above_menu + max_menu_height + height_below_menu;
 4798        let (laid_out_popovers, y_flipped) = self.layout_popovers_above_or_below_line(
 4799            target_position,
 4800            line_height,
 4801            min_height,
 4802            max_height,
 4803            context_menu_placement,
 4804            text_hitbox,
 4805            viewport_bounds,
 4806            window,
 4807            cx,
 4808            |height, max_width_for_stable_x, y_flipped, window, cx| {
 4809                // First layout the menu to get its size - others can be at least this wide.
 4810                let context_menu = if context_menu_visible {
 4811                    let menu_height = if y_flipped {
 4812                        height - height_below_menu
 4813                    } else {
 4814                        height - height_above_menu
 4815                    };
 4816                    let mut element = self
 4817                        .render_context_menu(line_height, menu_height, window, cx)
 4818                        .expect("Visible context menu should always render.");
 4819                    let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 4820                    Some((CursorPopoverType::CodeContextMenu, element, size))
 4821                } else {
 4822                    None
 4823                };
 4824                let min_width = context_menu
 4825                    .as_ref()
 4826                    .map_or(px(0.), |(_, _, size)| size.width);
 4827                let max_width = max_width_for_stable_x.max(
 4828                    context_menu
 4829                        .as_ref()
 4830                        .map_or(px(0.), |(_, _, size)| size.width),
 4831                );
 4832
 4833                let edit_prediction = if edit_prediction_popover_visible {
 4834                    self.editor.update(cx, move |editor, cx| {
 4835                        let mut element = editor.render_edit_prediction_cursor_popover(
 4836                            min_width,
 4837                            max_width,
 4838                            cursor_point,
 4839                            style,
 4840                            window,
 4841                            cx,
 4842                        )?;
 4843                        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 4844                        Some((CursorPopoverType::EditPrediction, element, size))
 4845                    })
 4846                } else {
 4847                    None
 4848                };
 4849                vec![edit_prediction, context_menu]
 4850                    .into_iter()
 4851                    .flatten()
 4852                    .collect::<Vec<_>>()
 4853            },
 4854        )?;
 4855
 4856        let (menu_ix, (_, menu_bounds)) = laid_out_popovers
 4857            .iter()
 4858            .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))?;
 4859        let last_ix = laid_out_popovers.len() - 1;
 4860        let menu_is_last = menu_ix == last_ix;
 4861        let first_popover_bounds = laid_out_popovers[0].1;
 4862        let last_popover_bounds = laid_out_popovers[last_ix].1;
 4863
 4864        // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
 4865        // right, and otherwise it goes below or to the right.
 4866        let mut target_bounds = Bounds::from_corners(
 4867            first_popover_bounds.origin,
 4868            last_popover_bounds.bottom_right(),
 4869        );
 4870        target_bounds.size.width = menu_bounds.size.width;
 4871
 4872        // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
 4873        // based on this is preferred for layout stability.
 4874        let mut max_target_bounds = target_bounds;
 4875        max_target_bounds.size.height = max_height;
 4876        if y_flipped {
 4877            max_target_bounds.origin.y -= max_height - target_bounds.size.height;
 4878        }
 4879
 4880        // Add spacing around `target_bounds` and `max_target_bounds`.
 4881        let mut extend_amount = Edges::all(MENU_GAP);
 4882        if y_flipped {
 4883            extend_amount.bottom = line_height;
 4884        } else {
 4885            extend_amount.top = line_height;
 4886        }
 4887        let target_bounds = target_bounds.extend(extend_amount);
 4888        let max_target_bounds = max_target_bounds.extend(extend_amount);
 4889
 4890        let must_place_above_or_below =
 4891            if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
 4892                laid_out_popovers[menu_ix + 1..]
 4893                    .iter()
 4894                    .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
 4895            } else {
 4896                false
 4897            };
 4898
 4899        let aside_bounds = self.layout_context_menu_aside(
 4900            y_flipped,
 4901            *menu_bounds,
 4902            target_bounds,
 4903            max_target_bounds,
 4904            max_menu_height,
 4905            must_place_above_or_below,
 4906            text_hitbox,
 4907            viewport_bounds,
 4908            window,
 4909            cx,
 4910        );
 4911
 4912        if let Some(menu_bounds) = laid_out_popovers.iter().find_map(|(popover_type, bounds)| {
 4913            if matches!(popover_type, CursorPopoverType::CodeContextMenu) {
 4914                Some(*bounds)
 4915            } else {
 4916                None
 4917            }
 4918        }) {
 4919            let bounds = if let Some(aside_bounds) = aside_bounds {
 4920                menu_bounds.union(&aside_bounds)
 4921            } else {
 4922                menu_bounds
 4923            };
 4924            return Some(ContextMenuLayout { y_flipped, bounds });
 4925        }
 4926
 4927        None
 4928    }
 4929
 4930    fn layout_gutter_menu(
 4931        &self,
 4932        line_height: Pixels,
 4933        text_hitbox: &Hitbox,
 4934        content_origin: gpui::Point<Pixels>,
 4935        right_margin: Pixels,
 4936        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 4937        gutter_overshoot: Pixels,
 4938        window: &mut Window,
 4939        cx: &mut App,
 4940    ) {
 4941        let editor = self.editor.read(cx);
 4942        if !editor.context_menu_visible() {
 4943            return;
 4944        }
 4945        let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
 4946            editor.context_menu_origin()
 4947        else {
 4948            return;
 4949        };
 4950        // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
 4951        // indicator than just a plain first column of the text field.
 4952        let target_position = content_origin
 4953            + gpui::Point {
 4954                x: -gutter_overshoot,
 4955                y: Pixels::from(
 4956                    gutter_row.next_row().as_f64() * ScrollPixelOffset::from(line_height)
 4957                        - scroll_pixel_position.y,
 4958                ),
 4959            };
 4960
 4961        let (min_height_in_lines, max_height_in_lines) = editor
 4962            .context_menu_options
 4963            .as_ref()
 4964            .map_or((3, 12), |options| {
 4965                (options.min_entries_visible, options.max_entries_visible)
 4966            });
 4967
 4968        let min_height = line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
 4969        let max_height = line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
 4970        let viewport_bounds =
 4971            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 4972                right: -right_margin - MENU_GAP,
 4973                ..Default::default()
 4974            });
 4975        self.layout_popovers_above_or_below_line(
 4976            target_position,
 4977            line_height,
 4978            min_height,
 4979            max_height,
 4980            editor
 4981                .context_menu_options
 4982                .as_ref()
 4983                .and_then(|options| options.placement.clone()),
 4984            text_hitbox,
 4985            viewport_bounds,
 4986            window,
 4987            cx,
 4988            move |height, _max_width_for_stable_x, _, window, cx| {
 4989                let mut element = self
 4990                    .render_context_menu(line_height, height, window, cx)
 4991                    .expect("Visible context menu should always render.");
 4992                let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 4993                vec![(CursorPopoverType::CodeContextMenu, element, size)]
 4994            },
 4995        );
 4996    }
 4997
 4998    fn layout_popovers_above_or_below_line(
 4999        &self,
 5000        target_position: gpui::Point<Pixels>,
 5001        line_height: Pixels,
 5002        min_height: Pixels,
 5003        max_height: Pixels,
 5004        placement: Option<ContextMenuPlacement>,
 5005        text_hitbox: &Hitbox,
 5006        viewport_bounds: Bounds<Pixels>,
 5007        window: &mut Window,
 5008        cx: &mut App,
 5009        make_sized_popovers: impl FnOnce(
 5010            Pixels,
 5011            Pixels,
 5012            bool,
 5013            &mut Window,
 5014            &mut App,
 5015        ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
 5016    ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
 5017        let text_style = TextStyleRefinement {
 5018            line_height: Some(DefiniteLength::Fraction(
 5019                BufferLineHeight::Comfortable.value(),
 5020            )),
 5021            ..Default::default()
 5022        };
 5023        window.with_text_style(Some(text_style), |window| {
 5024            // If the max height won't fit below and there is more space above, put it above the line.
 5025            let bottom_y_when_flipped = target_position.y - line_height;
 5026            let available_above = bottom_y_when_flipped - text_hitbox.top();
 5027            let available_below = text_hitbox.bottom() - target_position.y;
 5028            let y_overflows_below = max_height > available_below;
 5029            let mut y_flipped = match placement {
 5030                Some(ContextMenuPlacement::Above) => true,
 5031                Some(ContextMenuPlacement::Below) => false,
 5032                None => y_overflows_below && available_above > available_below,
 5033            };
 5034            let mut height = cmp::min(
 5035                max_height,
 5036                if y_flipped {
 5037                    available_above
 5038                } else {
 5039                    available_below
 5040                },
 5041            );
 5042
 5043            // If the min height doesn't fit within text bounds, instead fit within the window.
 5044            if height < min_height {
 5045                let available_above = bottom_y_when_flipped;
 5046                let available_below = viewport_bounds.bottom() - target_position.y;
 5047                let (y_flipped_override, height_override) = match placement {
 5048                    Some(ContextMenuPlacement::Above) => {
 5049                        (true, cmp::min(available_above, min_height))
 5050                    }
 5051                    Some(ContextMenuPlacement::Below) => {
 5052                        (false, cmp::min(available_below, min_height))
 5053                    }
 5054                    None => {
 5055                        if available_below > min_height {
 5056                            (false, min_height)
 5057                        } else if available_above > min_height {
 5058                            (true, min_height)
 5059                        } else if available_above > available_below {
 5060                            (true, available_above)
 5061                        } else {
 5062                            (false, available_below)
 5063                        }
 5064                    }
 5065                };
 5066                y_flipped = y_flipped_override;
 5067                height = height_override;
 5068            }
 5069
 5070            let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
 5071
 5072            // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
 5073            // for very narrow windows.
 5074            let popovers =
 5075                make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
 5076            if popovers.is_empty() {
 5077                return None;
 5078            }
 5079
 5080            let max_width = popovers
 5081                .iter()
 5082                .map(|(_, _, size)| size.width)
 5083                .max()
 5084                .unwrap_or_default();
 5085
 5086            let mut current_position = gpui::Point {
 5087                // Snap the right edge of the list to the right edge of the window if its horizontal bounds
 5088                // overflow. Include space for the scrollbar.
 5089                x: target_position
 5090                    .x
 5091                    .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
 5092                y: if y_flipped {
 5093                    bottom_y_when_flipped
 5094                } else {
 5095                    target_position.y
 5096                },
 5097            };
 5098
 5099            let mut laid_out_popovers = popovers
 5100                .into_iter()
 5101                .map(|(popover_type, element, size)| {
 5102                    if y_flipped {
 5103                        current_position.y -= size.height;
 5104                    }
 5105                    let position = current_position;
 5106                    window.defer_draw(element, current_position, 1, None);
 5107                    if !y_flipped {
 5108                        current_position.y += size.height + MENU_GAP;
 5109                    } else {
 5110                        current_position.y -= MENU_GAP;
 5111                    }
 5112                    (popover_type, Bounds::new(position, size))
 5113                })
 5114                .collect::<Vec<_>>();
 5115
 5116            if y_flipped {
 5117                laid_out_popovers.reverse();
 5118            }
 5119
 5120            Some((laid_out_popovers, y_flipped))
 5121        })
 5122    }
 5123
 5124    fn layout_context_menu_aside(
 5125        &self,
 5126        y_flipped: bool,
 5127        menu_bounds: Bounds<Pixels>,
 5128        target_bounds: Bounds<Pixels>,
 5129        max_target_bounds: Bounds<Pixels>,
 5130        max_height: Pixels,
 5131        must_place_above_or_below: bool,
 5132        text_hitbox: &Hitbox,
 5133        viewport_bounds: Bounds<Pixels>,
 5134        window: &mut Window,
 5135        cx: &mut App,
 5136    ) -> Option<Bounds<Pixels>> {
 5137        let available_within_viewport = target_bounds.space_within(&viewport_bounds);
 5138        let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
 5139            && !must_place_above_or_below
 5140        {
 5141            let max_width = cmp::min(
 5142                available_within_viewport.right - px(1.),
 5143                MENU_ASIDE_MAX_WIDTH,
 5144            );
 5145            let mut aside = self.render_context_menu_aside(
 5146                size(max_width, max_height - POPOVER_Y_PADDING),
 5147                window,
 5148                cx,
 5149            )?;
 5150            let size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
 5151            let right_position = point(target_bounds.right(), menu_bounds.origin.y);
 5152            Some((aside, right_position, size))
 5153        } else {
 5154            let max_size = size(
 5155                // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
 5156                // won't be needed here.
 5157                cmp::min(
 5158                    cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
 5159                    viewport_bounds.right(),
 5160                ),
 5161                cmp::min(
 5162                    max_height,
 5163                    cmp::max(
 5164                        available_within_viewport.top,
 5165                        available_within_viewport.bottom,
 5166                    ),
 5167                ) - POPOVER_Y_PADDING,
 5168            );
 5169            let mut aside = self.render_context_menu_aside(max_size, window, cx)?;
 5170            let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
 5171
 5172            let top_position = point(
 5173                menu_bounds.origin.x,
 5174                target_bounds.top() - actual_size.height,
 5175            );
 5176            let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
 5177
 5178            let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
 5179                // Prefer to fit on the same side of the line as the menu, then on the other side of
 5180                // the line.
 5181                if !y_flipped && wanted.height < available.bottom {
 5182                    Some(bottom_position)
 5183                } else if !y_flipped && wanted.height < available.top {
 5184                    Some(top_position)
 5185                } else if y_flipped && wanted.height < available.top {
 5186                    Some(top_position)
 5187                } else if y_flipped && wanted.height < available.bottom {
 5188                    Some(bottom_position)
 5189                } else {
 5190                    None
 5191                }
 5192            };
 5193
 5194            // Prefer choosing a direction using max sizes rather than actual size for stability.
 5195            let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
 5196            let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
 5197            let aside_position = fit_within(available_within_text, wanted)
 5198                // Fallback: fit max size in window.
 5199                .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
 5200                // Fallback: fit actual size in window.
 5201                .or_else(|| fit_within(available_within_viewport, actual_size));
 5202
 5203            aside_position.map(|position| (aside, position, actual_size))
 5204        };
 5205
 5206        // Skip drawing if it doesn't fit anywhere.
 5207        if let Some((aside, position, size)) = positioned_aside {
 5208            let aside_bounds = Bounds::new(position, size);
 5209            window.defer_draw(aside, position, 2, None);
 5210            return Some(aside_bounds);
 5211        }
 5212
 5213        None
 5214    }
 5215
 5216    fn render_context_menu(
 5217        &self,
 5218        line_height: Pixels,
 5219        height: Pixels,
 5220        window: &mut Window,
 5221        cx: &mut App,
 5222    ) -> Option<AnyElement> {
 5223        let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
 5224        self.editor.update(cx, |editor, cx| {
 5225            editor.render_context_menu(max_height_in_lines, window, cx)
 5226        })
 5227    }
 5228
 5229    fn render_context_menu_aside(
 5230        &self,
 5231        max_size: Size<Pixels>,
 5232        window: &mut Window,
 5233        cx: &mut App,
 5234    ) -> Option<AnyElement> {
 5235        if max_size.width < px(100.) || max_size.height < px(12.) {
 5236            None
 5237        } else {
 5238            self.editor.update(cx, |editor, cx| {
 5239                editor.render_context_menu_aside(max_size, window, cx)
 5240            })
 5241        }
 5242    }
 5243
 5244    fn layout_mouse_context_menu(
 5245        &self,
 5246        editor_snapshot: &EditorSnapshot,
 5247        visible_range: Range<DisplayRow>,
 5248        content_origin: gpui::Point<Pixels>,
 5249        window: &mut Window,
 5250        cx: &mut App,
 5251    ) -> Option<AnyElement> {
 5252        let position = self.editor.update(cx, |editor, cx| {
 5253            let visible_start_point = editor.display_to_pixel_point(
 5254                DisplayPoint::new(visible_range.start, 0),
 5255                editor_snapshot,
 5256                window,
 5257                cx,
 5258            )?;
 5259            let visible_end_point = editor.display_to_pixel_point(
 5260                DisplayPoint::new(visible_range.end, 0),
 5261                editor_snapshot,
 5262                window,
 5263                cx,
 5264            )?;
 5265
 5266            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
 5267            let (source_display_point, position) = match mouse_context_menu.position {
 5268                MenuPosition::PinnedToScreen(point) => (None, point),
 5269                MenuPosition::PinnedToEditor { source, offset } => {
 5270                    let source_display_point = source.to_display_point(editor_snapshot);
 5271                    let source_point =
 5272                        editor.to_pixel_point(source, editor_snapshot, window, cx)?;
 5273                    let position = content_origin + source_point + offset;
 5274                    (Some(source_display_point), position)
 5275                }
 5276            };
 5277
 5278            let source_included = source_display_point.is_none_or(|source_display_point| {
 5279                visible_range
 5280                    .to_inclusive()
 5281                    .contains(&source_display_point.row())
 5282            });
 5283            let position_included =
 5284                visible_start_point.y <= position.y && position.y <= visible_end_point.y;
 5285            if !source_included && !position_included {
 5286                None
 5287            } else {
 5288                Some(position)
 5289            }
 5290        })?;
 5291
 5292        let text_style = TextStyleRefinement {
 5293            line_height: Some(DefiniteLength::Fraction(
 5294                BufferLineHeight::Comfortable.value(),
 5295            )),
 5296            ..Default::default()
 5297        };
 5298        window.with_text_style(Some(text_style), |window| {
 5299            let mut element = self.editor.read_with(cx, |editor, _| {
 5300                let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
 5301                let context_menu = mouse_context_menu.context_menu.clone();
 5302
 5303                Some(
 5304                    deferred(
 5305                        anchored()
 5306                            .position(position)
 5307                            .child(context_menu)
 5308                            .anchor(Corner::TopLeft)
 5309                            .snap_to_window_with_margin(px(8.)),
 5310                    )
 5311                    .with_priority(1)
 5312                    .into_any(),
 5313                )
 5314            })?;
 5315
 5316            element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
 5317            Some(element)
 5318        })
 5319    }
 5320
 5321    fn layout_hover_popovers(
 5322        &self,
 5323        snapshot: &EditorSnapshot,
 5324        hitbox: &Hitbox,
 5325        visible_display_row_range: Range<DisplayRow>,
 5326        content_origin: gpui::Point<Pixels>,
 5327        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 5328        line_layouts: &[LineWithInvisibles],
 5329        line_height: Pixels,
 5330        em_width: Pixels,
 5331        context_menu_layout: Option<ContextMenuLayout>,
 5332        window: &mut Window,
 5333        cx: &mut App,
 5334    ) {
 5335        struct MeasuredHoverPopover {
 5336            element: AnyElement,
 5337            size: Size<Pixels>,
 5338            horizontal_offset: Pixels,
 5339        }
 5340
 5341        let max_size = size(
 5342            (120. * em_width) // Default size
 5343                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
 5344                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
 5345            (16. * line_height) // Default size
 5346                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
 5347                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
 5348        );
 5349
 5350        // Don't show hover popovers when context menu is open to avoid overlap
 5351        let has_context_menu = self.editor.read(cx).mouse_context_menu.is_some();
 5352        if has_context_menu {
 5353            return;
 5354        }
 5355
 5356        let hover_popovers = self.editor.update(cx, |editor, cx| {
 5357            editor.hover_state.render(
 5358                snapshot,
 5359                visible_display_row_range.clone(),
 5360                max_size,
 5361                &editor.text_layout_details(window, cx),
 5362                window,
 5363                cx,
 5364            )
 5365        });
 5366        let Some((popover_position, hover_popovers)) = hover_popovers else {
 5367            return;
 5368        };
 5369
 5370        // This is safe because we check on layout whether the required row is available
 5371        let hovered_row_layout = &line_layouts[popover_position
 5372            .row()
 5373            .minus(visible_display_row_range.start)
 5374            as usize];
 5375
 5376        // Compute Hovered Point
 5377        let x = hovered_row_layout.x_for_index(popover_position.column() as usize)
 5378            - Pixels::from(scroll_pixel_position.x);
 5379        let y = Pixels::from(
 5380            popover_position.row().as_f64() * ScrollPixelOffset::from(line_height)
 5381                - scroll_pixel_position.y,
 5382        );
 5383        let hovered_point = content_origin + point(x, y);
 5384
 5385        let mut overall_height = Pixels::ZERO;
 5386        let mut measured_hover_popovers = Vec::new();
 5387        for (position, mut hover_popover) in hover_popovers.into_iter().with_position() {
 5388            let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
 5389            let horizontal_offset =
 5390                (hitbox.top_right().x - POPOVER_RIGHT_OFFSET - (hovered_point.x + size.width))
 5391                    .min(Pixels::ZERO);
 5392            match position {
 5393                itertools::Position::Middle | itertools::Position::Last => {
 5394                    overall_height += HOVER_POPOVER_GAP
 5395                }
 5396                _ => {}
 5397            }
 5398            overall_height += size.height;
 5399            measured_hover_popovers.push(MeasuredHoverPopover {
 5400                element: hover_popover,
 5401                size,
 5402                horizontal_offset,
 5403            });
 5404        }
 5405
 5406        fn draw_occluder(
 5407            width: Pixels,
 5408            origin: gpui::Point<Pixels>,
 5409            window: &mut Window,
 5410            cx: &mut App,
 5411        ) {
 5412            let mut occlusion = div()
 5413                .size_full()
 5414                .occlude()
 5415                .on_mouse_move(|_, _, cx| cx.stop_propagation())
 5416                .into_any_element();
 5417            occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
 5418            window.defer_draw(occlusion, origin, 2, None);
 5419        }
 5420
 5421        fn place_popovers_above(
 5422            hovered_point: gpui::Point<Pixels>,
 5423            measured_hover_popovers: Vec<MeasuredHoverPopover>,
 5424            window: &mut Window,
 5425            cx: &mut App,
 5426        ) {
 5427            let mut current_y = hovered_point.y;
 5428            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 5429                let size = popover.size;
 5430                let popover_origin = point(
 5431                    hovered_point.x + popover.horizontal_offset,
 5432                    current_y - size.height,
 5433                );
 5434
 5435                window.defer_draw(popover.element, popover_origin, 2, None);
 5436                if position != itertools::Position::Last {
 5437                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
 5438                    draw_occluder(size.width, origin, window, cx);
 5439                }
 5440
 5441                current_y = popover_origin.y - HOVER_POPOVER_GAP;
 5442            }
 5443        }
 5444
 5445        fn place_popovers_below(
 5446            hovered_point: gpui::Point<Pixels>,
 5447            measured_hover_popovers: Vec<MeasuredHoverPopover>,
 5448            line_height: Pixels,
 5449            window: &mut Window,
 5450            cx: &mut App,
 5451        ) {
 5452            let mut current_y = hovered_point.y + line_height;
 5453            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 5454                let size = popover.size;
 5455                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
 5456
 5457                window.defer_draw(popover.element, popover_origin, 2, None);
 5458                if position != itertools::Position::Last {
 5459                    let origin = point(popover_origin.x, popover_origin.y + size.height);
 5460                    draw_occluder(size.width, origin, window, cx);
 5461                }
 5462
 5463                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 5464            }
 5465        }
 5466
 5467        let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
 5468            context_menu_layout
 5469                .as_ref()
 5470                .is_some_and(|menu| bounds.intersects(&menu.bounds))
 5471        };
 5472
 5473        let can_place_above = {
 5474            let mut bounds_above = Vec::new();
 5475            let mut current_y = hovered_point.y;
 5476            for popover in &measured_hover_popovers {
 5477                let size = popover.size;
 5478                let popover_origin = point(
 5479                    hovered_point.x + popover.horizontal_offset,
 5480                    current_y - size.height,
 5481                );
 5482                bounds_above.push(Bounds::new(popover_origin, size));
 5483                current_y = popover_origin.y - HOVER_POPOVER_GAP;
 5484            }
 5485            bounds_above
 5486                .iter()
 5487                .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
 5488        };
 5489
 5490        let can_place_below = || {
 5491            let mut bounds_below = Vec::new();
 5492            let mut current_y = hovered_point.y + line_height;
 5493            for popover in &measured_hover_popovers {
 5494                let size = popover.size;
 5495                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
 5496                bounds_below.push(Bounds::new(popover_origin, size));
 5497                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 5498            }
 5499            bounds_below
 5500                .iter()
 5501                .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
 5502        };
 5503
 5504        if can_place_above {
 5505            // try placing above hovered point
 5506            place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
 5507        } else if can_place_below() {
 5508            // try placing below hovered point
 5509            place_popovers_below(
 5510                hovered_point,
 5511                measured_hover_popovers,
 5512                line_height,
 5513                window,
 5514                cx,
 5515            );
 5516        } else {
 5517            // try to place popovers around the context menu
 5518            let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
 5519                let total_width = measured_hover_popovers
 5520                    .iter()
 5521                    .map(|p| p.size.width)
 5522                    .max()
 5523                    .unwrap_or(Pixels::ZERO);
 5524                let y_for_horizontal_positioning = if menu.y_flipped {
 5525                    menu.bounds.bottom() - overall_height
 5526                } else {
 5527                    menu.bounds.top()
 5528                };
 5529                let possible_origins = vec![
 5530                    // left of context menu
 5531                    point(
 5532                        menu.bounds.left() - total_width - HOVER_POPOVER_GAP,
 5533                        y_for_horizontal_positioning,
 5534                    ),
 5535                    // right of context menu
 5536                    point(
 5537                        menu.bounds.right() + HOVER_POPOVER_GAP,
 5538                        y_for_horizontal_positioning,
 5539                    ),
 5540                    // top of context menu
 5541                    point(
 5542                        menu.bounds.left(),
 5543                        menu.bounds.top() - overall_height - HOVER_POPOVER_GAP,
 5544                    ),
 5545                    // bottom of context menu
 5546                    point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
 5547                ];
 5548                possible_origins.into_iter().find(|&origin| {
 5549                    Bounds::new(origin, size(total_width, overall_height))
 5550                        .is_contained_within(hitbox)
 5551                })
 5552            });
 5553            if let Some(origin) = origin_surrounding_menu {
 5554                let mut current_y = origin.y;
 5555                for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 5556                    let size = popover.size;
 5557                    let popover_origin = point(origin.x, current_y);
 5558
 5559                    window.defer_draw(popover.element, popover_origin, 2, None);
 5560                    if position != itertools::Position::Last {
 5561                        let origin = point(popover_origin.x, popover_origin.y + size.height);
 5562                        draw_occluder(size.width, origin, window, cx);
 5563                    }
 5564
 5565                    current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 5566                }
 5567            } else {
 5568                // fallback to existing above/below cursor logic
 5569                // this might overlap menu or overflow in rare case
 5570                if can_place_above {
 5571                    place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
 5572                } else {
 5573                    place_popovers_below(
 5574                        hovered_point,
 5575                        measured_hover_popovers,
 5576                        line_height,
 5577                        window,
 5578                        cx,
 5579                    );
 5580                }
 5581            }
 5582        }
 5583    }
 5584
 5585    fn layout_word_diff_highlights(
 5586        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 5587        row_infos: &[RowInfo],
 5588        start_row: DisplayRow,
 5589        snapshot: &EditorSnapshot,
 5590        highlighted_ranges: &mut Vec<(Range<DisplayPoint>, Hsla)>,
 5591        cx: &mut App,
 5592    ) {
 5593        let colors = cx.theme().colors();
 5594
 5595        let word_highlights = display_hunks
 5596            .into_iter()
 5597            .filter_map(|(hunk, _)| match hunk {
 5598                DisplayDiffHunk::Unfolded {
 5599                    word_diffs, status, ..
 5600                } => Some((word_diffs, status)),
 5601                _ => None,
 5602            })
 5603            .filter(|(_, status)| status.is_modified())
 5604            .flat_map(|(word_diffs, _)| word_diffs)
 5605            .flat_map(|word_diff| {
 5606                let display_ranges = snapshot
 5607                    .display_snapshot
 5608                    .isomorphic_display_point_ranges_for_buffer_range(
 5609                        word_diff.start..word_diff.end,
 5610                    );
 5611
 5612                display_ranges.into_iter().filter_map(|range| {
 5613                    let start_row_offset = range.start.row().0.saturating_sub(start_row.0) as usize;
 5614
 5615                    let diff_status = row_infos
 5616                        .get(start_row_offset)
 5617                        .and_then(|row_info| row_info.diff_status)?;
 5618
 5619                    let background_color = match diff_status.kind {
 5620                        DiffHunkStatusKind::Added => colors.version_control_word_added,
 5621                        DiffHunkStatusKind::Deleted => colors.version_control_word_deleted,
 5622                        DiffHunkStatusKind::Modified => {
 5623                            debug_panic!("modified diff status for row info");
 5624                            return None;
 5625                        }
 5626                    };
 5627
 5628                    Some((range, background_color))
 5629                })
 5630            });
 5631
 5632        highlighted_ranges.extend(word_highlights);
 5633    }
 5634
 5635    fn layout_diff_hunk_controls(
 5636        &self,
 5637        row_range: Range<DisplayRow>,
 5638        row_infos: &[RowInfo],
 5639        text_hitbox: &Hitbox,
 5640        newest_cursor_row: Option<DisplayRow>,
 5641        line_height: Pixels,
 5642        right_margin: Pixels,
 5643        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 5644        sticky_header_height: Pixels,
 5645        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 5646        highlighted_rows: &BTreeMap<DisplayRow, LineHighlight>,
 5647        editor: Entity<Editor>,
 5648        window: &mut Window,
 5649        cx: &mut App,
 5650    ) -> (Vec<AnyElement>, Vec<(DisplayRow, Bounds<Pixels>)>) {
 5651        let render_diff_hunk_controls = editor.read(cx).render_diff_hunk_controls.clone();
 5652        let hovered_diff_hunk_row = editor.read(cx).hovered_diff_hunk_row;
 5653        let sticky_top = text_hitbox.bounds.top() + sticky_header_height;
 5654
 5655        let mut controls = vec![];
 5656        let mut control_bounds = vec![];
 5657
 5658        let active_rows = [hovered_diff_hunk_row, newest_cursor_row];
 5659
 5660        for (hunk, _) in display_hunks {
 5661            if let DisplayDiffHunk::Unfolded {
 5662                display_row_range,
 5663                multi_buffer_range,
 5664                status,
 5665                is_created_file,
 5666                ..
 5667            } = &hunk
 5668            {
 5669                if display_row_range.start >= row_range.end {
 5670                    // hunk is fully below the viewport
 5671                    continue;
 5672                }
 5673                if display_row_range.end <= row_range.start {
 5674                    // hunk is fully above the viewport
 5675                    continue;
 5676                }
 5677                let row_ix = display_row_range.start.0.saturating_sub(row_range.start.0);
 5678                if row_infos
 5679                    .get(row_ix as usize)
 5680                    .and_then(|row_info| row_info.diff_status)
 5681                    .is_none()
 5682                {
 5683                    continue;
 5684                }
 5685                if highlighted_rows
 5686                    .get(&display_row_range.start)
 5687                    .and_then(|highlight| highlight.type_id)
 5688                    .is_some_and(|type_id| {
 5689                        [
 5690                            TypeId::of::<ConflictsOuter>(),
 5691                            TypeId::of::<ConflictsOursMarker>(),
 5692                            TypeId::of::<ConflictsOurs>(),
 5693                            TypeId::of::<ConflictsTheirs>(),
 5694                            TypeId::of::<ConflictsTheirsMarker>(),
 5695                        ]
 5696                        .contains(&type_id)
 5697                    })
 5698                {
 5699                    continue;
 5700                }
 5701
 5702                if active_rows
 5703                    .iter()
 5704                    .any(|row| row.is_some_and(|row| display_row_range.contains(&row)))
 5705                {
 5706                    let hunk_start_y: Pixels = (display_row_range.start.as_f64()
 5707                        * ScrollPixelOffset::from(line_height)
 5708                        + ScrollPixelOffset::from(text_hitbox.bounds.top())
 5709                        - scroll_pixel_position.y)
 5710                        .into();
 5711
 5712                    let y: Pixels = if hunk_start_y >= sticky_top {
 5713                        hunk_start_y
 5714                    } else {
 5715                        let hunk_end_y: Pixels = hunk_start_y
 5716                            + (display_row_range.len() as f64
 5717                                * ScrollPixelOffset::from(line_height))
 5718                            .into();
 5719                        let max_y = hunk_end_y - line_height;
 5720                        sticky_top.min(max_y)
 5721                    };
 5722
 5723                    let mut element = render_diff_hunk_controls(
 5724                        display_row_range.start.0,
 5725                        status,
 5726                        multi_buffer_range.clone(),
 5727                        *is_created_file,
 5728                        line_height,
 5729                        &editor,
 5730                        window,
 5731                        cx,
 5732                    );
 5733                    let size =
 5734                        element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
 5735
 5736                    let x = text_hitbox.bounds.right() - right_margin - px(10.) - size.width;
 5737
 5738                    if x < text_hitbox.bounds.left() {
 5739                        continue;
 5740                    }
 5741
 5742                    let bounds = Bounds::new(gpui::Point::new(x, y), size);
 5743                    control_bounds.push((display_row_range.start, bounds));
 5744
 5745                    window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
 5746                        element.prepaint(window, cx)
 5747                    });
 5748                    controls.push(element);
 5749                }
 5750            }
 5751        }
 5752
 5753        (controls, control_bounds)
 5754    }
 5755
 5756    fn layout_signature_help(
 5757        &self,
 5758        hitbox: &Hitbox,
 5759        content_origin: gpui::Point<Pixels>,
 5760        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 5761        newest_selection_head: Option<DisplayPoint>,
 5762        start_row: DisplayRow,
 5763        line_layouts: &[LineWithInvisibles],
 5764        line_height: Pixels,
 5765        em_width: Pixels,
 5766        context_menu_layout: Option<ContextMenuLayout>,
 5767        window: &mut Window,
 5768        cx: &mut App,
 5769    ) {
 5770        if !self.editor.focus_handle(cx).is_focused(window) {
 5771            return;
 5772        }
 5773        let Some(newest_selection_head) = newest_selection_head else {
 5774            return;
 5775        };
 5776
 5777        let max_size = size(
 5778            (120. * em_width) // Default size
 5779                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
 5780                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
 5781            (16. * line_height) // Default size
 5782                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
 5783                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
 5784        );
 5785
 5786        let maybe_element = self.editor.update(cx, |editor, cx| {
 5787            if let Some(popover) = editor.signature_help_state.popover_mut() {
 5788                let element = popover.render(max_size, window, cx);
 5789                Some(element)
 5790            } else {
 5791                None
 5792            }
 5793        });
 5794        let Some(mut element) = maybe_element else {
 5795            return;
 5796        };
 5797
 5798        let selection_row = newest_selection_head.row();
 5799        let Some(cursor_row_layout) = (selection_row >= start_row)
 5800            .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
 5801            .flatten()
 5802        else {
 5803            return;
 5804        };
 5805
 5806        let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
 5807            - Pixels::from(scroll_pixel_position.x);
 5808        let target_y = Pixels::from(
 5809            selection_row.as_f64() * ScrollPixelOffset::from(line_height) - scroll_pixel_position.y,
 5810        );
 5811        let target_point = content_origin + point(target_x, target_y);
 5812
 5813        let actual_size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
 5814
 5815        let (popover_bounds_above, popover_bounds_below) = {
 5816            let horizontal_offset = (hitbox.top_right().x
 5817                - POPOVER_RIGHT_OFFSET
 5818                - (target_point.x + actual_size.width))
 5819                .min(Pixels::ZERO);
 5820            let initial_x = target_point.x + horizontal_offset;
 5821            (
 5822                Bounds::new(
 5823                    point(initial_x, target_point.y - actual_size.height),
 5824                    actual_size,
 5825                ),
 5826                Bounds::new(
 5827                    point(initial_x, target_point.y + line_height + HOVER_POPOVER_GAP),
 5828                    actual_size,
 5829                ),
 5830            )
 5831        };
 5832
 5833        let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
 5834            context_menu_layout
 5835                .as_ref()
 5836                .is_some_and(|menu| bounds.intersects(&menu.bounds))
 5837        };
 5838
 5839        let final_origin = if popover_bounds_above.is_contained_within(hitbox)
 5840            && !intersects_menu(popover_bounds_above)
 5841        {
 5842            // try placing above cursor
 5843            popover_bounds_above.origin
 5844        } else if popover_bounds_below.is_contained_within(hitbox)
 5845            && !intersects_menu(popover_bounds_below)
 5846        {
 5847            // try placing below cursor
 5848            popover_bounds_below.origin
 5849        } else {
 5850            // try surrounding context menu if exists
 5851            let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
 5852                let y_for_horizontal_positioning = if menu.y_flipped {
 5853                    menu.bounds.bottom() - actual_size.height
 5854                } else {
 5855                    menu.bounds.top()
 5856                };
 5857                let possible_origins = vec![
 5858                    // left of context menu
 5859                    point(
 5860                        menu.bounds.left() - actual_size.width - HOVER_POPOVER_GAP,
 5861                        y_for_horizontal_positioning,
 5862                    ),
 5863                    // right of context menu
 5864                    point(
 5865                        menu.bounds.right() + HOVER_POPOVER_GAP,
 5866                        y_for_horizontal_positioning,
 5867                    ),
 5868                    // top of context menu
 5869                    point(
 5870                        menu.bounds.left(),
 5871                        menu.bounds.top() - actual_size.height - HOVER_POPOVER_GAP,
 5872                    ),
 5873                    // bottom of context menu
 5874                    point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
 5875                ];
 5876                possible_origins
 5877                    .into_iter()
 5878                    .find(|&origin| Bounds::new(origin, actual_size).is_contained_within(hitbox))
 5879            });
 5880            origin_surrounding_menu.unwrap_or_else(|| {
 5881                // fallback to existing above/below cursor logic
 5882                // this might overlap menu or overflow in rare case
 5883                if popover_bounds_above.is_contained_within(hitbox) {
 5884                    popover_bounds_above.origin
 5885                } else {
 5886                    popover_bounds_below.origin
 5887                }
 5888            })
 5889        };
 5890
 5891        window.defer_draw(element, final_origin, 2, None);
 5892    }
 5893
 5894    fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
 5895        window.paint_layer(layout.hitbox.bounds, |window| {
 5896            let scroll_top = layout.position_map.snapshot.scroll_position().y;
 5897            let gutter_bg = cx.theme().colors().editor_gutter_background;
 5898            window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
 5899            window.paint_quad(fill(
 5900                layout.position_map.text_hitbox.bounds,
 5901                self.style.background,
 5902            ));
 5903
 5904            if matches!(
 5905                layout.mode,
 5906                EditorMode::Full { .. } | EditorMode::Minimap { .. }
 5907            ) {
 5908                let show_active_line_background = match layout.mode {
 5909                    EditorMode::Full {
 5910                        show_active_line_background,
 5911                        ..
 5912                    } => show_active_line_background,
 5913                    EditorMode::Minimap { .. } => true,
 5914                    _ => false,
 5915                };
 5916                let mut active_rows = layout.active_rows.iter().peekable();
 5917                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
 5918                    let mut end_row = start_row.0;
 5919                    while active_rows
 5920                        .peek()
 5921                        .is_some_and(|(active_row, has_selection)| {
 5922                            active_row.0 == end_row + 1
 5923                                && has_selection.selection == contains_non_empty_selection.selection
 5924                        })
 5925                    {
 5926                        active_rows.next().unwrap();
 5927                        end_row += 1;
 5928                    }
 5929
 5930                    if show_active_line_background && !contains_non_empty_selection.selection {
 5931                        let highlight_h_range =
 5932                            match layout.position_map.snapshot.current_line_highlight {
 5933                                CurrentLineHighlight::Gutter => Some(Range {
 5934                                    start: layout.hitbox.left(),
 5935                                    end: layout.gutter_hitbox.right(),
 5936                                }),
 5937                                CurrentLineHighlight::Line => Some(Range {
 5938                                    start: layout.position_map.text_hitbox.bounds.left(),
 5939                                    end: layout.position_map.text_hitbox.bounds.right(),
 5940                                }),
 5941                                CurrentLineHighlight::All => Some(Range {
 5942                                    start: layout.hitbox.left(),
 5943                                    end: layout.hitbox.right(),
 5944                                }),
 5945                                CurrentLineHighlight::None => None,
 5946                            };
 5947                        if let Some(range) = highlight_h_range {
 5948                            let active_line_bg = cx.theme().colors().editor_active_line_background;
 5949                            let bounds = Bounds {
 5950                                origin: point(
 5951                                    range.start,
 5952                                    layout.hitbox.origin.y
 5953                                        + Pixels::from(
 5954                                            (start_row.as_f64() - scroll_top)
 5955                                                * ScrollPixelOffset::from(
 5956                                                    layout.position_map.line_height,
 5957                                                ),
 5958                                        ),
 5959                                ),
 5960                                size: size(
 5961                                    range.end - range.start,
 5962                                    layout.position_map.line_height
 5963                                        * (end_row - start_row.0 + 1) as f32,
 5964                                ),
 5965                            };
 5966                            window.paint_quad(fill(bounds, active_line_bg));
 5967                        }
 5968                    }
 5969                }
 5970
 5971                let mut paint_highlight = |highlight_row_start: DisplayRow,
 5972                                           highlight_row_end: DisplayRow,
 5973                                           highlight: crate::LineHighlight,
 5974                                           edges| {
 5975                    let mut origin_x = layout.hitbox.left();
 5976                    let mut width = layout.hitbox.size.width;
 5977                    if !highlight.include_gutter {
 5978                        origin_x += layout.gutter_hitbox.size.width;
 5979                        width -= layout.gutter_hitbox.size.width;
 5980                    }
 5981
 5982                    let origin = point(
 5983                        origin_x,
 5984                        layout.hitbox.origin.y
 5985                            + Pixels::from(
 5986                                (highlight_row_start.as_f64() - scroll_top)
 5987                                    * ScrollPixelOffset::from(layout.position_map.line_height),
 5988                            ),
 5989                    );
 5990                    let size = size(
 5991                        width,
 5992                        layout.position_map.line_height
 5993                            * highlight_row_end.next_row().minus(highlight_row_start) as f32,
 5994                    );
 5995                    let mut quad = fill(Bounds { origin, size }, highlight.background);
 5996                    if let Some(border_color) = highlight.border {
 5997                        quad.border_color = border_color;
 5998                        quad.border_widths = edges
 5999                    }
 6000                    window.paint_quad(quad);
 6001                };
 6002
 6003                let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
 6004                    None;
 6005                for (&new_row, &new_background) in &layout.highlighted_rows {
 6006                    match &mut current_paint {
 6007                        &mut Some((current_background, ref mut current_range, mut edges)) => {
 6008                            let new_range_started = current_background != new_background
 6009                                || current_range.end.next_row() != new_row;
 6010                            if new_range_started {
 6011                                if current_range.end.next_row() == new_row {
 6012                                    edges.bottom = px(0.);
 6013                                };
 6014                                paint_highlight(
 6015                                    current_range.start,
 6016                                    current_range.end,
 6017                                    current_background,
 6018                                    edges,
 6019                                );
 6020                                let edges = Edges {
 6021                                    top: if current_range.end.next_row() != new_row {
 6022                                        px(1.)
 6023                                    } else {
 6024                                        px(0.)
 6025                                    },
 6026                                    bottom: px(1.),
 6027                                    ..Default::default()
 6028                                };
 6029                                current_paint = Some((new_background, new_row..new_row, edges));
 6030                                continue;
 6031                            } else {
 6032                                current_range.end = current_range.end.next_row();
 6033                            }
 6034                        }
 6035                        None => {
 6036                            let edges = Edges {
 6037                                top: px(1.),
 6038                                bottom: px(1.),
 6039                                ..Default::default()
 6040                            };
 6041                            current_paint = Some((new_background, new_row..new_row, edges))
 6042                        }
 6043                    };
 6044                }
 6045                if let Some((color, range, edges)) = current_paint {
 6046                    paint_highlight(range.start, range.end, color, edges);
 6047                }
 6048
 6049                for (guide_x, active) in layout.wrap_guides.iter() {
 6050                    let color = if *active {
 6051                        cx.theme().colors().editor_active_wrap_guide
 6052                    } else {
 6053                        cx.theme().colors().editor_wrap_guide
 6054                    };
 6055                    window.paint_quad(fill(
 6056                        Bounds {
 6057                            origin: point(*guide_x, layout.position_map.text_hitbox.origin.y),
 6058                            size: size(px(1.), layout.position_map.text_hitbox.size.height),
 6059                        },
 6060                        color,
 6061                    ));
 6062                }
 6063            }
 6064        })
 6065    }
 6066
 6067    fn paint_indent_guides(
 6068        &mut self,
 6069        layout: &mut EditorLayout,
 6070        window: &mut Window,
 6071        cx: &mut App,
 6072    ) {
 6073        let Some(indent_guides) = &layout.indent_guides else {
 6074            return;
 6075        };
 6076
 6077        let faded_color = |color: Hsla, alpha: f32| {
 6078            let mut faded = color;
 6079            faded.a = alpha;
 6080            faded
 6081        };
 6082
 6083        for indent_guide in indent_guides {
 6084            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
 6085            let settings = &indent_guide.settings;
 6086
 6087            // TODO fixed for now, expose them through themes later
 6088            const INDENT_AWARE_ALPHA: f32 = 0.2;
 6089            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
 6090            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
 6091            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
 6092
 6093            let line_color = match (settings.coloring, indent_guide.active) {
 6094                (IndentGuideColoring::Disabled, _) => None,
 6095                (IndentGuideColoring::Fixed, false) => {
 6096                    Some(cx.theme().colors().editor_indent_guide)
 6097                }
 6098                (IndentGuideColoring::Fixed, true) => {
 6099                    Some(cx.theme().colors().editor_indent_guide_active)
 6100                }
 6101                (IndentGuideColoring::IndentAware, false) => {
 6102                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
 6103                }
 6104                (IndentGuideColoring::IndentAware, true) => {
 6105                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
 6106                }
 6107            };
 6108
 6109            let background_color = match (settings.background_coloring, indent_guide.active) {
 6110                (IndentGuideBackgroundColoring::Disabled, _) => None,
 6111                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
 6112                    indent_accent_colors,
 6113                    INDENT_AWARE_BACKGROUND_ALPHA,
 6114                )),
 6115                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
 6116                    indent_accent_colors,
 6117                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
 6118                )),
 6119            };
 6120
 6121            let mut line_indicator_width = 0.;
 6122            if let Some(requested_line_width) = settings.visible_line_width(indent_guide.active) {
 6123                if let Some(color) = line_color {
 6124                    window.paint_quad(fill(
 6125                        Bounds {
 6126                            origin: indent_guide.origin,
 6127                            size: size(px(requested_line_width as f32), indent_guide.length),
 6128                        },
 6129                        color,
 6130                    ));
 6131                    line_indicator_width = requested_line_width as f32;
 6132                }
 6133            }
 6134
 6135            if let Some(color) = background_color {
 6136                let width = indent_guide.single_indent_width - px(line_indicator_width);
 6137                window.paint_quad(fill(
 6138                    Bounds {
 6139                        origin: point(
 6140                            indent_guide.origin.x + px(line_indicator_width),
 6141                            indent_guide.origin.y,
 6142                        ),
 6143                        size: size(width, indent_guide.length),
 6144                    },
 6145                    color,
 6146                ));
 6147            }
 6148        }
 6149    }
 6150
 6151    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6152        let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
 6153
 6154        let line_height = layout.position_map.line_height;
 6155        window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
 6156
 6157        for line_layout in layout.line_numbers.values() {
 6158            for LineNumberSegment {
 6159                shaped_line,
 6160                hitbox,
 6161            } in &line_layout.segments
 6162            {
 6163                let Some(hitbox) = hitbox else {
 6164                    continue;
 6165                };
 6166
 6167                let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
 6168                    let color = cx.theme().colors().editor_hover_line_number;
 6169
 6170                    let line = self.shape_line_number(shaped_line.text.clone(), color, window);
 6171                    line.paint(
 6172                        hitbox.origin,
 6173                        line_height,
 6174                        TextAlign::Left,
 6175                        None,
 6176                        window,
 6177                        cx,
 6178                    )
 6179                    .log_err()
 6180                } else {
 6181                    shaped_line
 6182                        .paint(
 6183                            hitbox.origin,
 6184                            line_height,
 6185                            TextAlign::Left,
 6186                            None,
 6187                            window,
 6188                            cx,
 6189                        )
 6190                        .log_err()
 6191                }) else {
 6192                    continue;
 6193                };
 6194
 6195                // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
 6196                // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
 6197                if is_singleton {
 6198                    window.set_cursor_style(CursorStyle::IBeam, hitbox);
 6199                } else {
 6200                    window.set_cursor_style(CursorStyle::PointingHand, hitbox);
 6201                }
 6202            }
 6203        }
 6204    }
 6205
 6206    fn paint_gutter_diff_hunks(
 6207        layout: &mut EditorLayout,
 6208        split_side: Option<SplitSide>,
 6209        window: &mut Window,
 6210        cx: &mut App,
 6211    ) {
 6212        if layout.display_hunks.is_empty() {
 6213            return;
 6214        }
 6215
 6216        let line_height = layout.position_map.line_height;
 6217        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6218            for (hunk, hitbox) in &layout.display_hunks {
 6219                let hunk_to_paint = match hunk {
 6220                    DisplayDiffHunk::Folded { .. } => {
 6221                        let hunk_bounds = Self::diff_hunk_bounds(
 6222                            &layout.position_map.snapshot,
 6223                            line_height,
 6224                            layout.gutter_hitbox.bounds,
 6225                            hunk,
 6226                        );
 6227                        Some((
 6228                            hunk_bounds,
 6229                            cx.theme().colors().version_control_modified,
 6230                            Corners::all(px(0.)),
 6231                            DiffHunkStatus::modified_none(),
 6232                        ))
 6233                    }
 6234                    DisplayDiffHunk::Unfolded {
 6235                        status,
 6236                        display_row_range,
 6237                        ..
 6238                    } => hitbox.as_ref().map(|hunk_hitbox| {
 6239                        let color = match split_side {
 6240                            Some(SplitSide::Left) => cx.theme().colors().version_control_deleted,
 6241                            Some(SplitSide::Right) => cx.theme().colors().version_control_added,
 6242                            None => match status.kind {
 6243                                DiffHunkStatusKind::Added => {
 6244                                    cx.theme().colors().version_control_added
 6245                                }
 6246                                DiffHunkStatusKind::Modified => {
 6247                                    cx.theme().colors().version_control_modified
 6248                                }
 6249                                DiffHunkStatusKind::Deleted => {
 6250                                    cx.theme().colors().version_control_deleted
 6251                                }
 6252                            },
 6253                        };
 6254                        match status.kind {
 6255                            DiffHunkStatusKind::Deleted if display_row_range.is_empty() => (
 6256                                Bounds::new(
 6257                                    point(
 6258                                        hunk_hitbox.origin.x - hunk_hitbox.size.width,
 6259                                        hunk_hitbox.origin.y,
 6260                                    ),
 6261                                    size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
 6262                                ),
 6263                                color,
 6264                                Corners::all(1. * line_height),
 6265                                *status,
 6266                            ),
 6267                            _ => (hunk_hitbox.bounds, color, Corners::all(px(0.)), *status),
 6268                        }
 6269                    }),
 6270                };
 6271
 6272                if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
 6273                    // Flatten the background color with the editor color to prevent
 6274                    // elements below transparent hunks from showing through
 6275                    let flattened_background_color = cx
 6276                        .theme()
 6277                        .colors()
 6278                        .editor_background
 6279                        .blend(background_color);
 6280
 6281                    if !Self::diff_hunk_hollow(status, cx) {
 6282                        window.paint_quad(quad(
 6283                            hunk_bounds,
 6284                            corner_radii,
 6285                            flattened_background_color,
 6286                            Edges::default(),
 6287                            transparent_black(),
 6288                            BorderStyle::default(),
 6289                        ));
 6290                    } else {
 6291                        let flattened_unstaged_background_color = cx
 6292                            .theme()
 6293                            .colors()
 6294                            .editor_background
 6295                            .blend(background_color.opacity(0.3));
 6296
 6297                        window.paint_quad(quad(
 6298                            hunk_bounds,
 6299                            corner_radii,
 6300                            flattened_unstaged_background_color,
 6301                            Edges::all(px(1.0)),
 6302                            flattened_background_color,
 6303                            BorderStyle::Solid,
 6304                        ));
 6305                    }
 6306                }
 6307            }
 6308        });
 6309    }
 6310
 6311    fn gutter_strip_width(line_height: Pixels) -> Pixels {
 6312        (0.275 * line_height).floor()
 6313    }
 6314
 6315    fn diff_hunk_bounds(
 6316        snapshot: &EditorSnapshot,
 6317        line_height: Pixels,
 6318        gutter_bounds: Bounds<Pixels>,
 6319        hunk: &DisplayDiffHunk,
 6320    ) -> Bounds<Pixels> {
 6321        let scroll_position = snapshot.scroll_position();
 6322        let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
 6323        let gutter_strip_width = Self::gutter_strip_width(line_height);
 6324
 6325        match hunk {
 6326            DisplayDiffHunk::Folded { display_row, .. } => {
 6327                let start_y = (display_row.as_f64() * ScrollPixelOffset::from(line_height)
 6328                    - scroll_top)
 6329                    .into();
 6330                let end_y = start_y + line_height;
 6331                let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 6332                let highlight_size = size(gutter_strip_width, end_y - start_y);
 6333                Bounds::new(highlight_origin, highlight_size)
 6334            }
 6335            DisplayDiffHunk::Unfolded {
 6336                display_row_range,
 6337                status,
 6338                ..
 6339            } => {
 6340                if status.is_deleted() && display_row_range.is_empty() {
 6341                    let row = display_row_range.start;
 6342
 6343                    let offset = ScrollPixelOffset::from(line_height / 2.);
 6344                    let start_y =
 6345                        (row.as_f64() * ScrollPixelOffset::from(line_height) - offset - scroll_top)
 6346                            .into();
 6347                    let end_y = start_y + line_height;
 6348
 6349                    let width = (0.35 * line_height).floor();
 6350                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 6351                    let highlight_size = size(width, end_y - start_y);
 6352                    Bounds::new(highlight_origin, highlight_size)
 6353                } else {
 6354                    let start_row = display_row_range.start;
 6355                    let end_row = display_row_range.end;
 6356                    // If we're in a multibuffer, row range span might include an
 6357                    // excerpt header, so if we were to draw the marker straight away,
 6358                    // the hunk might include the rows of that header.
 6359                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
 6360                    // Instead, we simply check whether the range we're dealing with includes
 6361                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
 6362                    let end_row_in_current_excerpt = snapshot
 6363                        .blocks_in_range(start_row..end_row)
 6364                        .find_map(|(start_row, block)| {
 6365                            if matches!(
 6366                                block,
 6367                                Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
 6368                            ) {
 6369                                Some(start_row)
 6370                            } else {
 6371                                None
 6372                            }
 6373                        })
 6374                        .unwrap_or(end_row);
 6375
 6376                    let start_y = (start_row.as_f64() * ScrollPixelOffset::from(line_height)
 6377                        - scroll_top)
 6378                        .into();
 6379                    let end_y = Pixels::from(
 6380                        end_row_in_current_excerpt.as_f64() * ScrollPixelOffset::from(line_height)
 6381                            - scroll_top,
 6382                    );
 6383
 6384                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 6385                    let highlight_size = size(gutter_strip_width, end_y - start_y);
 6386                    Bounds::new(highlight_origin, highlight_size)
 6387                }
 6388            }
 6389        }
 6390    }
 6391
 6392    fn paint_gutter_indicators(
 6393        &self,
 6394        layout: &mut EditorLayout,
 6395        window: &mut Window,
 6396        cx: &mut App,
 6397    ) {
 6398        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6399            window.with_element_namespace("crease_toggles", |window| {
 6400                for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
 6401                    crease_toggle.paint(window, cx);
 6402                }
 6403            });
 6404
 6405            window.with_element_namespace("expand_toggles", |window| {
 6406                for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
 6407                    expand_toggle.paint(window, cx);
 6408                }
 6409            });
 6410
 6411            for breakpoint in layout.breakpoints.iter_mut() {
 6412                breakpoint.paint(window, cx);
 6413            }
 6414
 6415            for test_indicator in layout.test_indicators.iter_mut() {
 6416                test_indicator.paint(window, cx);
 6417            }
 6418
 6419            if let Some(diff_review_button) = layout.diff_review_button.as_mut() {
 6420                diff_review_button.paint(window, cx);
 6421            }
 6422        });
 6423    }
 6424
 6425    fn paint_gutter_highlights(
 6426        &self,
 6427        layout: &mut EditorLayout,
 6428        window: &mut Window,
 6429        cx: &mut App,
 6430    ) {
 6431        for (_, hunk_hitbox) in &layout.display_hunks {
 6432            if let Some(hunk_hitbox) = hunk_hitbox
 6433                && !self
 6434                    .editor
 6435                    .read(cx)
 6436                    .buffer()
 6437                    .read(cx)
 6438                    .all_diff_hunks_expanded()
 6439            {
 6440                window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
 6441            }
 6442        }
 6443
 6444        let show_git_gutter = layout
 6445            .position_map
 6446            .snapshot
 6447            .show_git_diff_gutter
 6448            .unwrap_or_else(|| {
 6449                matches!(
 6450                    ProjectSettings::get_global(cx).git.git_gutter,
 6451                    GitGutterSetting::TrackedFiles
 6452                )
 6453            });
 6454        if show_git_gutter {
 6455            Self::paint_gutter_diff_hunks(layout, self.split_side, window, cx)
 6456        }
 6457
 6458        let highlight_width = 0.275 * layout.position_map.line_height;
 6459        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
 6460        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6461            for (range, color) in &layout.highlighted_gutter_ranges {
 6462                let start_row = if range.start.row() < layout.visible_display_row_range.start {
 6463                    layout.visible_display_row_range.start - DisplayRow(1)
 6464                } else {
 6465                    range.start.row()
 6466                };
 6467                let end_row = if range.end.row() > layout.visible_display_row_range.end {
 6468                    layout.visible_display_row_range.end + DisplayRow(1)
 6469                } else {
 6470                    range.end.row()
 6471                };
 6472
 6473                let start_y = layout.gutter_hitbox.top()
 6474                    + Pixels::from(
 6475                        start_row.0 as f64
 6476                            * ScrollPixelOffset::from(layout.position_map.line_height)
 6477                            - layout.position_map.scroll_pixel_position.y,
 6478                    );
 6479                let end_y = layout.gutter_hitbox.top()
 6480                    + Pixels::from(
 6481                        (end_row.0 + 1) as f64
 6482                            * ScrollPixelOffset::from(layout.position_map.line_height)
 6483                            - layout.position_map.scroll_pixel_position.y,
 6484                    );
 6485                let bounds = Bounds::from_corners(
 6486                    point(layout.gutter_hitbox.left(), start_y),
 6487                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
 6488                );
 6489                window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
 6490            }
 6491        });
 6492    }
 6493
 6494    fn paint_blamed_display_rows(
 6495        &self,
 6496        layout: &mut EditorLayout,
 6497        window: &mut Window,
 6498        cx: &mut App,
 6499    ) {
 6500        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
 6501            return;
 6502        };
 6503
 6504        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6505            for mut blame_element in blamed_display_rows.into_iter() {
 6506                blame_element.paint(window, cx);
 6507            }
 6508        })
 6509    }
 6510
 6511    fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6512        window.with_content_mask(
 6513            Some(ContentMask {
 6514                bounds: layout.position_map.text_hitbox.bounds,
 6515            }),
 6516            |window| {
 6517                let editor = self.editor.read(cx);
 6518                if editor.mouse_cursor_hidden {
 6519                    window.set_window_cursor_style(CursorStyle::None);
 6520                } else if let SelectionDragState::ReadyToDrag {
 6521                    mouse_down_time, ..
 6522                } = &editor.selection_drag_state
 6523                {
 6524                    let drag_and_drop_delay = Duration::from_millis(
 6525                        EditorSettings::get_global(cx)
 6526                            .drag_and_drop_selection
 6527                            .delay
 6528                            .0,
 6529                    );
 6530                    if mouse_down_time.elapsed() >= drag_and_drop_delay {
 6531                        window.set_cursor_style(
 6532                            CursorStyle::DragCopy,
 6533                            &layout.position_map.text_hitbox,
 6534                        );
 6535                    }
 6536                } else if matches!(
 6537                    editor.selection_drag_state,
 6538                    SelectionDragState::Dragging { .. }
 6539                ) {
 6540                    window
 6541                        .set_cursor_style(CursorStyle::DragCopy, &layout.position_map.text_hitbox);
 6542                } else if editor
 6543                    .hovered_link_state
 6544                    .as_ref()
 6545                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
 6546                {
 6547                    window.set_cursor_style(
 6548                        CursorStyle::PointingHand,
 6549                        &layout.position_map.text_hitbox,
 6550                    );
 6551                } else {
 6552                    window.set_cursor_style(CursorStyle::IBeam, &layout.position_map.text_hitbox);
 6553                };
 6554
 6555                self.paint_lines_background(layout, window, cx);
 6556                let invisible_display_ranges = self.paint_highlights(layout, window, cx);
 6557                self.paint_document_colors(layout, window);
 6558                self.paint_lines(&invisible_display_ranges, layout, window, cx);
 6559                self.paint_redactions(layout, window);
 6560                self.paint_cursors(layout, window, cx);
 6561                self.paint_inline_diagnostics(layout, window, cx);
 6562                self.paint_inline_blame(layout, window, cx);
 6563                self.paint_inline_code_actions(layout, window, cx);
 6564                self.paint_diff_hunk_controls(layout, window, cx);
 6565                window.with_element_namespace("crease_trailers", |window| {
 6566                    for trailer in layout.crease_trailers.iter_mut().flatten() {
 6567                        trailer.element.paint(window, cx);
 6568                    }
 6569                });
 6570            },
 6571        )
 6572    }
 6573
 6574    fn paint_highlights(
 6575        &mut self,
 6576        layout: &mut EditorLayout,
 6577        window: &mut Window,
 6578        cx: &mut App,
 6579    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
 6580        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6581            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
 6582            let line_end_overshoot = 0.15 * layout.position_map.line_height;
 6583            for (range, color) in &layout.highlighted_ranges {
 6584                self.paint_highlighted_range(
 6585                    range.clone(),
 6586                    true,
 6587                    *color,
 6588                    Pixels::ZERO,
 6589                    line_end_overshoot,
 6590                    layout,
 6591                    window,
 6592                );
 6593            }
 6594
 6595            let corner_radius = if EditorSettings::get_global(cx).rounded_selection {
 6596                0.15 * layout.position_map.line_height
 6597            } else {
 6598                Pixels::ZERO
 6599            };
 6600
 6601            for (player_color, selections) in &layout.selections {
 6602                for selection in selections.iter() {
 6603                    self.paint_highlighted_range(
 6604                        selection.range.clone(),
 6605                        true,
 6606                        player_color.selection,
 6607                        corner_radius,
 6608                        corner_radius * 2.,
 6609                        layout,
 6610                        window,
 6611                    );
 6612
 6613                    if selection.is_local && !selection.range.is_empty() {
 6614                        invisible_display_ranges.push(selection.range.clone());
 6615                    }
 6616                }
 6617            }
 6618            invisible_display_ranges
 6619        })
 6620    }
 6621
 6622    fn paint_lines(
 6623        &mut self,
 6624        invisible_display_ranges: &[Range<DisplayPoint>],
 6625        layout: &mut EditorLayout,
 6626        window: &mut Window,
 6627        cx: &mut App,
 6628    ) {
 6629        let whitespace_setting = self
 6630            .editor
 6631            .read(cx)
 6632            .buffer
 6633            .read(cx)
 6634            .language_settings(cx)
 6635            .show_whitespaces;
 6636
 6637        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
 6638            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
 6639            line_with_invisibles.draw(
 6640                layout,
 6641                row,
 6642                layout.content_origin,
 6643                whitespace_setting,
 6644                invisible_display_ranges,
 6645                window,
 6646                cx,
 6647            )
 6648        }
 6649
 6650        for line_element in &mut layout.line_elements {
 6651            line_element.paint(window, cx);
 6652        }
 6653    }
 6654
 6655    fn paint_sticky_headers(
 6656        &mut self,
 6657        layout: &mut EditorLayout,
 6658        window: &mut Window,
 6659        cx: &mut App,
 6660    ) {
 6661        let Some(mut sticky_headers) = layout.sticky_headers.take() else {
 6662            return;
 6663        };
 6664
 6665        if sticky_headers.lines.is_empty() {
 6666            layout.sticky_headers = Some(sticky_headers);
 6667            return;
 6668        }
 6669
 6670        let whitespace_setting = self
 6671            .editor
 6672            .read(cx)
 6673            .buffer
 6674            .read(cx)
 6675            .language_settings(cx)
 6676            .show_whitespaces;
 6677        sticky_headers.paint(layout, whitespace_setting, window, cx);
 6678
 6679        let sticky_header_hitboxes: Vec<Hitbox> = sticky_headers
 6680            .lines
 6681            .iter()
 6682            .map(|line| line.hitbox.clone())
 6683            .collect();
 6684        let hovered_hitbox = sticky_header_hitboxes
 6685            .iter()
 6686            .find_map(|hitbox| hitbox.is_hovered(window).then_some(hitbox.id));
 6687
 6688        window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, _cx| {
 6689            if !phase.bubble() {
 6690                return;
 6691            }
 6692
 6693            let current_hover = sticky_header_hitboxes
 6694                .iter()
 6695                .find_map(|hitbox| hitbox.is_hovered(window).then_some(hitbox.id));
 6696            if hovered_hitbox != current_hover {
 6697                window.refresh();
 6698            }
 6699        });
 6700
 6701        let position_map = layout.position_map.clone();
 6702
 6703        for (line_index, line) in sticky_headers.lines.iter().enumerate() {
 6704            let editor = self.editor.clone();
 6705            let hitbox = line.hitbox.clone();
 6706            let row = line.row;
 6707            let line_layout = line.line.clone();
 6708            let position_map = position_map.clone();
 6709            window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
 6710                if !phase.bubble() {
 6711                    return;
 6712                }
 6713
 6714                if event.button == MouseButton::Left && hitbox.is_hovered(window) {
 6715                    let point_for_position =
 6716                        position_map.point_for_position_on_line(event.position, row, &line_layout);
 6717
 6718                    editor.update(cx, |editor, cx| {
 6719                        let snapshot = editor.snapshot(window, cx);
 6720                        let anchor = snapshot
 6721                            .display_snapshot
 6722                            .display_point_to_anchor(point_for_position.previous_valid, Bias::Left);
 6723                        editor.change_selections(
 6724                            SelectionEffects::scroll(Autoscroll::top_relative(line_index)),
 6725                            window,
 6726                            cx,
 6727                            |selections| selections.select_ranges([anchor..anchor]),
 6728                        );
 6729                        cx.stop_propagation();
 6730                    });
 6731                }
 6732            });
 6733        }
 6734
 6735        let text_bounds = layout.position_map.text_hitbox.bounds;
 6736        let border_top = text_bounds.top()
 6737            + sticky_headers.lines.last().unwrap().offset
 6738            + layout.position_map.line_height;
 6739        let separator_height = px(1.);
 6740        let border_bounds = Bounds::from_corners(
 6741            point(layout.gutter_hitbox.bounds.left(), border_top),
 6742            point(text_bounds.right(), border_top + separator_height),
 6743        );
 6744        window.paint_quad(fill(border_bounds, cx.theme().colors().border_variant));
 6745
 6746        layout.sticky_headers = Some(sticky_headers);
 6747    }
 6748
 6749    fn paint_lines_background(
 6750        &mut self,
 6751        layout: &mut EditorLayout,
 6752        window: &mut Window,
 6753        cx: &mut App,
 6754    ) {
 6755        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
 6756            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
 6757            line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
 6758        }
 6759    }
 6760
 6761    fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
 6762        if layout.redacted_ranges.is_empty() {
 6763            return;
 6764        }
 6765
 6766        let line_end_overshoot = layout.line_end_overshoot();
 6767
 6768        // A softer than perfect black
 6769        let redaction_color = gpui::rgb(0x0e1111);
 6770
 6771        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6772            for range in layout.redacted_ranges.iter() {
 6773                self.paint_highlighted_range(
 6774                    range.clone(),
 6775                    true,
 6776                    redaction_color.into(),
 6777                    Pixels::ZERO,
 6778                    line_end_overshoot,
 6779                    layout,
 6780                    window,
 6781                );
 6782            }
 6783        });
 6784    }
 6785
 6786    fn paint_document_colors(&self, layout: &mut EditorLayout, window: &mut Window) {
 6787        let Some((colors_render_mode, image_colors)) = &layout.document_colors else {
 6788            return;
 6789        };
 6790        if image_colors.is_empty()
 6791            || colors_render_mode == &DocumentColorsRenderMode::None
 6792            || colors_render_mode == &DocumentColorsRenderMode::Inlay
 6793        {
 6794            return;
 6795        }
 6796
 6797        let line_end_overshoot = layout.line_end_overshoot();
 6798
 6799        for (range, color) in image_colors {
 6800            match colors_render_mode {
 6801                DocumentColorsRenderMode::Inlay | DocumentColorsRenderMode::None => return,
 6802                DocumentColorsRenderMode::Background => {
 6803                    self.paint_highlighted_range(
 6804                        range.clone(),
 6805                        true,
 6806                        *color,
 6807                        Pixels::ZERO,
 6808                        line_end_overshoot,
 6809                        layout,
 6810                        window,
 6811                    );
 6812                }
 6813                DocumentColorsRenderMode::Border => {
 6814                    self.paint_highlighted_range(
 6815                        range.clone(),
 6816                        false,
 6817                        *color,
 6818                        Pixels::ZERO,
 6819                        line_end_overshoot,
 6820                        layout,
 6821                        window,
 6822                    );
 6823                }
 6824            }
 6825        }
 6826    }
 6827
 6828    fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6829        for cursor in &mut layout.visible_cursors {
 6830            cursor.paint(layout.content_origin, window, cx);
 6831        }
 6832    }
 6833
 6834    fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6835        let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
 6836            return;
 6837        };
 6838        let any_scrollbar_dragged = self.editor.read(cx).scroll_manager.any_scrollbar_dragged();
 6839
 6840        for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
 6841            let hitbox = &scrollbar_layout.hitbox;
 6842            if scrollbars_layout.visible {
 6843                let scrollbar_edges = match axis {
 6844                    ScrollbarAxis::Horizontal => Edges {
 6845                        top: Pixels::ZERO,
 6846                        right: Pixels::ZERO,
 6847                        bottom: Pixels::ZERO,
 6848                        left: Pixels::ZERO,
 6849                    },
 6850                    ScrollbarAxis::Vertical => Edges {
 6851                        top: Pixels::ZERO,
 6852                        right: Pixels::ZERO,
 6853                        bottom: Pixels::ZERO,
 6854                        left: ScrollbarLayout::BORDER_WIDTH,
 6855                    },
 6856                };
 6857
 6858                window.paint_layer(hitbox.bounds, |window| {
 6859                    window.paint_quad(quad(
 6860                        hitbox.bounds,
 6861                        Corners::default(),
 6862                        cx.theme().colors().scrollbar_track_background,
 6863                        scrollbar_edges,
 6864                        cx.theme().colors().scrollbar_track_border,
 6865                        BorderStyle::Solid,
 6866                    ));
 6867
 6868                    if axis == ScrollbarAxis::Vertical {
 6869                        let fast_markers =
 6870                            self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
 6871                        // Refresh slow scrollbar markers in the background. Below, we
 6872                        // paint whatever markers have already been computed.
 6873                        self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, window, cx);
 6874
 6875                        let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
 6876                        for marker in markers.iter().chain(&fast_markers) {
 6877                            let mut marker = marker.clone();
 6878                            marker.bounds.origin += hitbox.origin;
 6879                            window.paint_quad(marker);
 6880                        }
 6881                    }
 6882
 6883                    if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
 6884                        let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
 6885                            ScrollbarThumbState::Dragging => {
 6886                                cx.theme().colors().scrollbar_thumb_active_background
 6887                            }
 6888                            ScrollbarThumbState::Hovered => {
 6889                                cx.theme().colors().scrollbar_thumb_hover_background
 6890                            }
 6891                            ScrollbarThumbState::Idle => {
 6892                                cx.theme().colors().scrollbar_thumb_background
 6893                            }
 6894                        };
 6895                        window.paint_quad(quad(
 6896                            thumb_bounds,
 6897                            Corners::default(),
 6898                            scrollbar_thumb_color,
 6899                            scrollbar_edges,
 6900                            cx.theme().colors().scrollbar_thumb_border,
 6901                            BorderStyle::Solid,
 6902                        ));
 6903
 6904                        if any_scrollbar_dragged {
 6905                            window.set_window_cursor_style(CursorStyle::Arrow);
 6906                        } else {
 6907                            window.set_cursor_style(CursorStyle::Arrow, hitbox);
 6908                        }
 6909                    }
 6910                })
 6911            }
 6912        }
 6913
 6914        window.on_mouse_event({
 6915            let editor = self.editor.clone();
 6916            let scrollbars_layout = scrollbars_layout.clone();
 6917
 6918            let mut mouse_position = window.mouse_position();
 6919            move |event: &MouseMoveEvent, phase, window, cx| {
 6920                if phase == DispatchPhase::Capture {
 6921                    return;
 6922                }
 6923
 6924                editor.update(cx, |editor, cx| {
 6925                    if let Some((scrollbar_layout, axis)) = event
 6926                        .pressed_button
 6927                        .filter(|button| *button == MouseButton::Left)
 6928                        .and(editor.scroll_manager.dragging_scrollbar_axis())
 6929                        .and_then(|axis| {
 6930                            scrollbars_layout
 6931                                .iter_scrollbars()
 6932                                .find(|(_, a)| *a == axis)
 6933                        })
 6934                    {
 6935                        let ScrollbarLayout {
 6936                            hitbox,
 6937                            text_unit_size,
 6938                            ..
 6939                        } = scrollbar_layout;
 6940
 6941                        let old_position = mouse_position.along(axis);
 6942                        let new_position = event.position.along(axis);
 6943                        if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
 6944                            .contains(&old_position)
 6945                        {
 6946                            let position = editor.scroll_position(cx).apply_along(axis, |p| {
 6947                                (p + ScrollOffset::from(
 6948                                    (new_position - old_position) / *text_unit_size,
 6949                                ))
 6950                                .max(0.)
 6951                            });
 6952                            editor.set_scroll_position(position, window, cx);
 6953                        }
 6954
 6955                        editor.scroll_manager.show_scrollbars(window, cx);
 6956                        cx.stop_propagation();
 6957                    } else if let Some((layout, axis)) = scrollbars_layout
 6958                        .get_hovered_axis(window)
 6959                        .filter(|_| !event.dragging())
 6960                    {
 6961                        if layout.thumb_hovered(&event.position) {
 6962                            editor
 6963                                .scroll_manager
 6964                                .set_hovered_scroll_thumb_axis(axis, cx);
 6965                        } else {
 6966                            editor.scroll_manager.reset_scrollbar_state(cx);
 6967                        }
 6968
 6969                        editor.scroll_manager.show_scrollbars(window, cx);
 6970                    } else {
 6971                        editor.scroll_manager.reset_scrollbar_state(cx);
 6972                    }
 6973
 6974                    mouse_position = event.position;
 6975                })
 6976            }
 6977        });
 6978
 6979        if any_scrollbar_dragged {
 6980            window.on_mouse_event({
 6981                let editor = self.editor.clone();
 6982                move |_: &MouseUpEvent, phase, window, cx| {
 6983                    if phase == DispatchPhase::Capture {
 6984                        return;
 6985                    }
 6986
 6987                    editor.update(cx, |editor, cx| {
 6988                        if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
 6989                            editor
 6990                                .scroll_manager
 6991                                .set_hovered_scroll_thumb_axis(axis, cx);
 6992                        } else {
 6993                            editor.scroll_manager.reset_scrollbar_state(cx);
 6994                        }
 6995                        cx.stop_propagation();
 6996                    });
 6997                }
 6998            });
 6999        } else {
 7000            window.on_mouse_event({
 7001                let editor = self.editor.clone();
 7002
 7003                move |event: &MouseDownEvent, phase, window, cx| {
 7004                    if phase == DispatchPhase::Capture {
 7005                        return;
 7006                    }
 7007                    let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
 7008                    else {
 7009                        return;
 7010                    };
 7011
 7012                    let ScrollbarLayout {
 7013                        hitbox,
 7014                        visible_range,
 7015                        text_unit_size,
 7016                        thumb_bounds,
 7017                        ..
 7018                    } = scrollbar_layout;
 7019
 7020                    let Some(thumb_bounds) = thumb_bounds else {
 7021                        return;
 7022                    };
 7023
 7024                    editor.update(cx, |editor, cx| {
 7025                        editor
 7026                            .scroll_manager
 7027                            .set_dragged_scroll_thumb_axis(axis, cx);
 7028
 7029                        let event_position = event.position.along(axis);
 7030
 7031                        if event_position < thumb_bounds.origin.along(axis)
 7032                            || thumb_bounds.bottom_right().along(axis) < event_position
 7033                        {
 7034                            let center_position = ((event_position - hitbox.origin.along(axis))
 7035                                / *text_unit_size)
 7036                                .round() as u32;
 7037                            let start_position = center_position.saturating_sub(
 7038                                (visible_range.end - visible_range.start) as u32 / 2,
 7039                            );
 7040
 7041                            let position = editor
 7042                                .scroll_position(cx)
 7043                                .apply_along(axis, |_| start_position as ScrollOffset);
 7044
 7045                            editor.set_scroll_position(position, window, cx);
 7046                        } else {
 7047                            editor.scroll_manager.show_scrollbars(window, cx);
 7048                        }
 7049
 7050                        cx.stop_propagation();
 7051                    });
 7052                }
 7053            });
 7054        }
 7055    }
 7056
 7057    fn collect_fast_scrollbar_markers(
 7058        &self,
 7059        layout: &EditorLayout,
 7060        scrollbar_layout: &ScrollbarLayout,
 7061        cx: &mut App,
 7062    ) -> Vec<PaintQuad> {
 7063        const LIMIT: usize = 100;
 7064        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
 7065            return vec![];
 7066        }
 7067        let cursor_ranges = layout
 7068            .cursors
 7069            .iter()
 7070            .map(|(point, color)| ColoredRange {
 7071                start: point.row(),
 7072                end: point.row(),
 7073                color: *color,
 7074            })
 7075            .collect_vec();
 7076        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
 7077    }
 7078
 7079    fn refresh_slow_scrollbar_markers(
 7080        &self,
 7081        layout: &EditorLayout,
 7082        scrollbar_layout: &ScrollbarLayout,
 7083        window: &mut Window,
 7084        cx: &mut App,
 7085    ) {
 7086        self.editor.update(cx, |editor, cx| {
 7087            if editor.buffer_kind(cx) != ItemBufferKind::Singleton
 7088                || !editor
 7089                    .scrollbar_marker_state
 7090                    .should_refresh(scrollbar_layout.hitbox.size)
 7091            {
 7092                return;
 7093            }
 7094
 7095            let scrollbar_layout = scrollbar_layout.clone();
 7096            let background_highlights = editor.background_highlights.clone();
 7097            let snapshot = layout.position_map.snapshot.clone();
 7098            let theme = cx.theme().clone();
 7099            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
 7100
 7101            editor.scrollbar_marker_state.dirty = false;
 7102            editor.scrollbar_marker_state.pending_refresh =
 7103                Some(cx.spawn_in(window, async move |editor, cx| {
 7104                    let scrollbar_size = scrollbar_layout.hitbox.size;
 7105                    let scrollbar_markers = cx
 7106                        .background_spawn(async move {
 7107                            let max_point = snapshot.display_snapshot.buffer_snapshot().max_point();
 7108                            let mut marker_quads = Vec::new();
 7109                            if scrollbar_settings.git_diff {
 7110                                let marker_row_ranges =
 7111                                    snapshot.buffer_snapshot().diff_hunks().map(|hunk| {
 7112                                        let start_display_row =
 7113                                            MultiBufferPoint::new(hunk.row_range.start.0, 0)
 7114                                                .to_display_point(&snapshot.display_snapshot)
 7115                                                .row();
 7116                                        let mut end_display_row =
 7117                                            MultiBufferPoint::new(hunk.row_range.end.0, 0)
 7118                                                .to_display_point(&snapshot.display_snapshot)
 7119                                                .row();
 7120                                        if end_display_row != start_display_row {
 7121                                            end_display_row.0 -= 1;
 7122                                        }
 7123                                        let color = match &hunk.status().kind {
 7124                                            DiffHunkStatusKind::Added => {
 7125                                                theme.colors().version_control_added
 7126                                            }
 7127                                            DiffHunkStatusKind::Modified => {
 7128                                                theme.colors().version_control_modified
 7129                                            }
 7130                                            DiffHunkStatusKind::Deleted => {
 7131                                                theme.colors().version_control_deleted
 7132                                            }
 7133                                        };
 7134                                        ColoredRange {
 7135                                            start: start_display_row,
 7136                                            end: end_display_row,
 7137                                            color,
 7138                                        }
 7139                                    });
 7140
 7141                                marker_quads.extend(
 7142                                    scrollbar_layout
 7143                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
 7144                                );
 7145                            }
 7146
 7147                            for (background_highlight_id, (_, background_ranges)) in
 7148                                background_highlights.iter()
 7149                            {
 7150                                let is_search_highlights = *background_highlight_id
 7151                                    == HighlightKey::BufferSearchHighlights;
 7152                                let is_text_highlights =
 7153                                    *background_highlight_id == HighlightKey::SelectedTextHighlight;
 7154                                let is_symbol_occurrences = *background_highlight_id
 7155                                    == HighlightKey::DocumentHighlightRead
 7156                                    || *background_highlight_id
 7157                                        == HighlightKey::DocumentHighlightWrite;
 7158                                if (is_search_highlights && scrollbar_settings.search_results)
 7159                                    || (is_text_highlights && scrollbar_settings.selected_text)
 7160                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
 7161                                {
 7162                                    let mut color = theme.status().info;
 7163                                    if is_symbol_occurrences {
 7164                                        color.fade_out(0.5);
 7165                                    }
 7166                                    let marker_row_ranges = background_ranges.iter().map(|range| {
 7167                                        let display_start = range
 7168                                            .start
 7169                                            .to_display_point(&snapshot.display_snapshot);
 7170                                        let display_end =
 7171                                            range.end.to_display_point(&snapshot.display_snapshot);
 7172                                        ColoredRange {
 7173                                            start: display_start.row(),
 7174                                            end: display_end.row(),
 7175                                            color,
 7176                                        }
 7177                                    });
 7178                                    marker_quads.extend(
 7179                                        scrollbar_layout
 7180                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
 7181                                    );
 7182                                }
 7183                            }
 7184
 7185                            if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
 7186                                let diagnostics = snapshot
 7187                                    .buffer_snapshot()
 7188                                    .diagnostics_in_range::<Point>(Point::zero()..max_point)
 7189                                    // Don't show diagnostics the user doesn't care about
 7190                                    .filter(|diagnostic| {
 7191                                        match (
 7192                                            scrollbar_settings.diagnostics,
 7193                                            diagnostic.diagnostic.severity,
 7194                                        ) {
 7195                                            (ScrollbarDiagnostics::All, _) => true,
 7196                                            (
 7197                                                ScrollbarDiagnostics::Error,
 7198                                                lsp::DiagnosticSeverity::ERROR,
 7199                                            ) => true,
 7200                                            (
 7201                                                ScrollbarDiagnostics::Warning,
 7202                                                lsp::DiagnosticSeverity::ERROR
 7203                                                | lsp::DiagnosticSeverity::WARNING,
 7204                                            ) => true,
 7205                                            (
 7206                                                ScrollbarDiagnostics::Information,
 7207                                                lsp::DiagnosticSeverity::ERROR
 7208                                                | lsp::DiagnosticSeverity::WARNING
 7209                                                | lsp::DiagnosticSeverity::INFORMATION,
 7210                                            ) => true,
 7211                                            (_, _) => false,
 7212                                        }
 7213                                    })
 7214                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
 7215                                    .sorted_by_key(|diagnostic| {
 7216                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
 7217                                    });
 7218
 7219                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
 7220                                    let start_display = diagnostic
 7221                                        .range
 7222                                        .start
 7223                                        .to_display_point(&snapshot.display_snapshot);
 7224                                    let end_display = diagnostic
 7225                                        .range
 7226                                        .end
 7227                                        .to_display_point(&snapshot.display_snapshot);
 7228                                    let color = match diagnostic.diagnostic.severity {
 7229                                        lsp::DiagnosticSeverity::ERROR => theme.status().error,
 7230                                        lsp::DiagnosticSeverity::WARNING => theme.status().warning,
 7231                                        lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
 7232                                        _ => theme.status().hint,
 7233                                    };
 7234                                    ColoredRange {
 7235                                        start: start_display.row(),
 7236                                        end: end_display.row(),
 7237                                        color,
 7238                                    }
 7239                                });
 7240                                marker_quads.extend(
 7241                                    scrollbar_layout
 7242                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
 7243                                );
 7244                            }
 7245
 7246                            Arc::from(marker_quads)
 7247                        })
 7248                        .await;
 7249
 7250                    editor.update(cx, |editor, cx| {
 7251                        editor.scrollbar_marker_state.markers = scrollbar_markers;
 7252                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
 7253                        editor.scrollbar_marker_state.pending_refresh = None;
 7254                        cx.notify();
 7255                    })?;
 7256
 7257                    Ok(())
 7258                }));
 7259        });
 7260    }
 7261
 7262    fn paint_highlighted_range(
 7263        &self,
 7264        range: Range<DisplayPoint>,
 7265        fill: bool,
 7266        color: Hsla,
 7267        corner_radius: Pixels,
 7268        line_end_overshoot: Pixels,
 7269        layout: &EditorLayout,
 7270        window: &mut Window,
 7271    ) {
 7272        let start_row = layout.visible_display_row_range.start;
 7273        let end_row = layout.visible_display_row_range.end;
 7274        if range.start != range.end {
 7275            let row_range = if range.end.column() == 0 {
 7276                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
 7277            } else {
 7278                cmp::max(range.start.row(), start_row)
 7279                    ..cmp::min(range.end.row().next_row(), end_row)
 7280            };
 7281
 7282            let highlighted_range = HighlightedRange {
 7283                color,
 7284                line_height: layout.position_map.line_height,
 7285                corner_radius,
 7286                start_y: layout.content_origin.y
 7287                    + Pixels::from(
 7288                        (row_range.start.as_f64() - layout.position_map.scroll_position.y)
 7289                            * ScrollOffset::from(layout.position_map.line_height),
 7290                    ),
 7291                lines: row_range
 7292                    .iter_rows()
 7293                    .map(|row| {
 7294                        let line_layout =
 7295                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
 7296                        let alignment_offset =
 7297                            line_layout.alignment_offset(layout.text_align, layout.content_width);
 7298                        HighlightedRangeLine {
 7299                            start_x: if row == range.start.row() {
 7300                                layout.content_origin.x
 7301                                    + Pixels::from(
 7302                                        ScrollPixelOffset::from(
 7303                                            line_layout.x_for_index(range.start.column() as usize)
 7304                                                + alignment_offset,
 7305                                        ) - layout.position_map.scroll_pixel_position.x,
 7306                                    )
 7307                            } else {
 7308                                layout.content_origin.x + alignment_offset
 7309                                    - Pixels::from(layout.position_map.scroll_pixel_position.x)
 7310                            },
 7311                            end_x: if row == range.end.row() {
 7312                                layout.content_origin.x
 7313                                    + Pixels::from(
 7314                                        ScrollPixelOffset::from(
 7315                                            line_layout.x_for_index(range.end.column() as usize)
 7316                                                + alignment_offset,
 7317                                        ) - layout.position_map.scroll_pixel_position.x,
 7318                                    )
 7319                            } else {
 7320                                Pixels::from(
 7321                                    ScrollPixelOffset::from(
 7322                                        layout.content_origin.x
 7323                                            + line_layout.width
 7324                                            + alignment_offset
 7325                                            + line_end_overshoot,
 7326                                    ) - layout.position_map.scroll_pixel_position.x,
 7327                                )
 7328                            },
 7329                        }
 7330                    })
 7331                    .collect(),
 7332            };
 7333
 7334            highlighted_range.paint(fill, layout.position_map.text_hitbox.bounds, window);
 7335        }
 7336    }
 7337
 7338    fn paint_inline_diagnostics(
 7339        &mut self,
 7340        layout: &mut EditorLayout,
 7341        window: &mut Window,
 7342        cx: &mut App,
 7343    ) {
 7344        for mut inline_diagnostic in layout.inline_diagnostics.drain() {
 7345            inline_diagnostic.1.paint(window, cx);
 7346        }
 7347    }
 7348
 7349    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 7350        if let Some(mut blame_layout) = layout.inline_blame_layout.take() {
 7351            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 7352                blame_layout.element.paint(window, cx);
 7353            })
 7354        }
 7355    }
 7356
 7357    fn paint_inline_code_actions(
 7358        &mut self,
 7359        layout: &mut EditorLayout,
 7360        window: &mut Window,
 7361        cx: &mut App,
 7362    ) {
 7363        if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
 7364            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 7365                inline_code_actions.paint(window, cx);
 7366            })
 7367        }
 7368    }
 7369
 7370    fn paint_diff_hunk_controls(
 7371        &mut self,
 7372        layout: &mut EditorLayout,
 7373        window: &mut Window,
 7374        cx: &mut App,
 7375    ) {
 7376        for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
 7377            diff_hunk_control.paint(window, cx);
 7378        }
 7379    }
 7380
 7381    fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 7382        if let Some(mut layout) = layout.minimap.take() {
 7383            let minimap_hitbox = layout.thumb_layout.hitbox.clone();
 7384            let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
 7385
 7386            window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
 7387                window.with_element_namespace("minimap", |window| {
 7388                    layout.minimap.paint(window, cx);
 7389                    if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
 7390                        let minimap_thumb_color = match layout.thumb_layout.thumb_state {
 7391                            ScrollbarThumbState::Idle => {
 7392                                cx.theme().colors().minimap_thumb_background
 7393                            }
 7394                            ScrollbarThumbState::Hovered => {
 7395                                cx.theme().colors().minimap_thumb_hover_background
 7396                            }
 7397                            ScrollbarThumbState::Dragging => {
 7398                                cx.theme().colors().minimap_thumb_active_background
 7399                            }
 7400                        };
 7401                        let minimap_thumb_border = match layout.thumb_border_style {
 7402                            MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
 7403                            MinimapThumbBorder::LeftOnly => Edges {
 7404                                left: ScrollbarLayout::BORDER_WIDTH,
 7405                                ..Default::default()
 7406                            },
 7407                            MinimapThumbBorder::LeftOpen => Edges {
 7408                                right: ScrollbarLayout::BORDER_WIDTH,
 7409                                top: ScrollbarLayout::BORDER_WIDTH,
 7410                                bottom: ScrollbarLayout::BORDER_WIDTH,
 7411                                ..Default::default()
 7412                            },
 7413                            MinimapThumbBorder::RightOpen => Edges {
 7414                                left: ScrollbarLayout::BORDER_WIDTH,
 7415                                top: ScrollbarLayout::BORDER_WIDTH,
 7416                                bottom: ScrollbarLayout::BORDER_WIDTH,
 7417                                ..Default::default()
 7418                            },
 7419                            MinimapThumbBorder::None => Default::default(),
 7420                        };
 7421
 7422                        window.paint_layer(minimap_hitbox.bounds, |window| {
 7423                            window.paint_quad(quad(
 7424                                thumb_bounds,
 7425                                Corners::default(),
 7426                                minimap_thumb_color,
 7427                                minimap_thumb_border,
 7428                                cx.theme().colors().minimap_thumb_border,
 7429                                BorderStyle::Solid,
 7430                            ));
 7431                        });
 7432                    }
 7433                });
 7434            });
 7435
 7436            if dragging_minimap {
 7437                window.set_window_cursor_style(CursorStyle::Arrow);
 7438            } else {
 7439                window.set_cursor_style(CursorStyle::Arrow, &minimap_hitbox);
 7440            }
 7441
 7442            let minimap_axis = ScrollbarAxis::Vertical;
 7443            let pixels_per_line = Pixels::from(
 7444                ScrollPixelOffset::from(minimap_hitbox.size.height) / layout.max_scroll_top,
 7445            )
 7446            .min(layout.minimap_line_height);
 7447
 7448            let mut mouse_position = window.mouse_position();
 7449
 7450            window.on_mouse_event({
 7451                let editor = self.editor.clone();
 7452
 7453                let minimap_hitbox = minimap_hitbox.clone();
 7454
 7455                move |event: &MouseMoveEvent, phase, window, cx| {
 7456                    if phase == DispatchPhase::Capture {
 7457                        return;
 7458                    }
 7459
 7460                    editor.update(cx, |editor, cx| {
 7461                        if event.pressed_button == Some(MouseButton::Left)
 7462                            && editor.scroll_manager.is_dragging_minimap()
 7463                        {
 7464                            let old_position = mouse_position.along(minimap_axis);
 7465                            let new_position = event.position.along(minimap_axis);
 7466                            if (minimap_hitbox.origin.along(minimap_axis)
 7467                                ..minimap_hitbox.bottom_right().along(minimap_axis))
 7468                                .contains(&old_position)
 7469                            {
 7470                                let position =
 7471                                    editor.scroll_position(cx).apply_along(minimap_axis, |p| {
 7472                                        (p + ScrollPixelOffset::from(
 7473                                            (new_position - old_position) / pixels_per_line,
 7474                                        ))
 7475                                        .max(0.)
 7476                                    });
 7477
 7478                                editor.set_scroll_position(position, window, cx);
 7479                            }
 7480                            cx.stop_propagation();
 7481                        } else if minimap_hitbox.is_hovered(window) {
 7482                            editor.scroll_manager.set_is_hovering_minimap_thumb(
 7483                                !event.dragging()
 7484                                    && layout
 7485                                        .thumb_layout
 7486                                        .thumb_bounds
 7487                                        .is_some_and(|bounds| bounds.contains(&event.position)),
 7488                                cx,
 7489                            );
 7490
 7491                            // Stop hover events from propagating to the
 7492                            // underlying editor if the minimap hitbox is hovered
 7493                            if !event.dragging() {
 7494                                cx.stop_propagation();
 7495                            }
 7496                        } else {
 7497                            editor.scroll_manager.hide_minimap_thumb(cx);
 7498                        }
 7499                        mouse_position = event.position;
 7500                    });
 7501                }
 7502            });
 7503
 7504            if dragging_minimap {
 7505                window.on_mouse_event({
 7506                    let editor = self.editor.clone();
 7507                    move |event: &MouseUpEvent, phase, window, cx| {
 7508                        if phase == DispatchPhase::Capture {
 7509                            return;
 7510                        }
 7511
 7512                        editor.update(cx, |editor, cx| {
 7513                            if minimap_hitbox.is_hovered(window) {
 7514                                editor.scroll_manager.set_is_hovering_minimap_thumb(
 7515                                    layout
 7516                                        .thumb_layout
 7517                                        .thumb_bounds
 7518                                        .is_some_and(|bounds| bounds.contains(&event.position)),
 7519                                    cx,
 7520                                );
 7521                            } else {
 7522                                editor.scroll_manager.hide_minimap_thumb(cx);
 7523                            }
 7524                            cx.stop_propagation();
 7525                        });
 7526                    }
 7527                });
 7528            } else {
 7529                window.on_mouse_event({
 7530                    let editor = self.editor.clone();
 7531
 7532                    move |event: &MouseDownEvent, phase, window, cx| {
 7533                        if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
 7534                            return;
 7535                        }
 7536
 7537                        let event_position = event.position;
 7538
 7539                        let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
 7540                            return;
 7541                        };
 7542
 7543                        editor.update(cx, |editor, cx| {
 7544                            if !thumb_bounds.contains(&event_position) {
 7545                                let click_position =
 7546                                    event_position.relative_to(&minimap_hitbox.origin).y;
 7547
 7548                                let top_position = (click_position
 7549                                    - thumb_bounds.size.along(minimap_axis) / 2.0)
 7550                                    .max(Pixels::ZERO);
 7551
 7552                                let scroll_offset = (layout.minimap_scroll_top
 7553                                    + ScrollPixelOffset::from(
 7554                                        top_position / layout.minimap_line_height,
 7555                                    ))
 7556                                .min(layout.max_scroll_top);
 7557
 7558                                let scroll_position = editor
 7559                                    .scroll_position(cx)
 7560                                    .apply_along(minimap_axis, |_| scroll_offset);
 7561                                editor.set_scroll_position(scroll_position, window, cx);
 7562                            }
 7563
 7564                            editor.scroll_manager.set_is_dragging_minimap(cx);
 7565                            cx.stop_propagation();
 7566                        });
 7567                    }
 7568                });
 7569            }
 7570        }
 7571    }
 7572
 7573    fn paint_spacer_blocks(
 7574        &mut self,
 7575        layout: &mut EditorLayout,
 7576        window: &mut Window,
 7577        cx: &mut App,
 7578    ) {
 7579        for mut block in layout.spacer_blocks.drain(..) {
 7580            let mut bounds = layout.hitbox.bounds;
 7581            bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
 7582            window.with_content_mask(Some(ContentMask { bounds }), |window| {
 7583                block.element.paint(window, cx);
 7584            })
 7585        }
 7586    }
 7587
 7588    fn paint_non_spacer_blocks(
 7589        &mut self,
 7590        layout: &mut EditorLayout,
 7591        window: &mut Window,
 7592        cx: &mut App,
 7593    ) {
 7594        for mut block in layout.blocks.drain(..) {
 7595            if block.overlaps_gutter {
 7596                block.element.paint(window, cx);
 7597            } else {
 7598                let mut bounds = layout.hitbox.bounds;
 7599                bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
 7600                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 7601                    block.element.paint(window, cx);
 7602                })
 7603            }
 7604        }
 7605    }
 7606
 7607    fn paint_edit_prediction_popover(
 7608        &mut self,
 7609        layout: &mut EditorLayout,
 7610        window: &mut Window,
 7611        cx: &mut App,
 7612    ) {
 7613        if let Some(edit_prediction_popover) = layout.edit_prediction_popover.as_mut() {
 7614            edit_prediction_popover.paint(window, cx);
 7615        }
 7616    }
 7617
 7618    fn paint_mouse_context_menu(
 7619        &mut self,
 7620        layout: &mut EditorLayout,
 7621        window: &mut Window,
 7622        cx: &mut App,
 7623    ) {
 7624        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
 7625            mouse_context_menu.paint(window, cx);
 7626        }
 7627    }
 7628
 7629    fn paint_scroll_wheel_listener(
 7630        &mut self,
 7631        layout: &EditorLayout,
 7632        window: &mut Window,
 7633        cx: &mut App,
 7634    ) {
 7635        window.on_mouse_event({
 7636            let position_map = layout.position_map.clone();
 7637            let editor = self.editor.clone();
 7638            let hitbox = layout.hitbox.clone();
 7639            let mut delta = ScrollDelta::default();
 7640
 7641            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
 7642            // accidentally turn off their scrolling.
 7643            let base_scroll_sensitivity =
 7644                EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
 7645
 7646            // Use a minimum fast_scroll_sensitivity for same reason above
 7647            let fast_scroll_sensitivity = EditorSettings::get_global(cx)
 7648                .fast_scroll_sensitivity
 7649                .max(0.01);
 7650
 7651            move |event: &ScrollWheelEvent, phase, window, cx| {
 7652                let scroll_sensitivity = {
 7653                    if event.modifiers.alt {
 7654                        fast_scroll_sensitivity
 7655                    } else {
 7656                        base_scroll_sensitivity
 7657                    }
 7658                };
 7659
 7660                if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
 7661                    delta = delta.coalesce(event.delta);
 7662                    editor.update(cx, |editor, cx| {
 7663                        let position_map: &PositionMap = &position_map;
 7664
 7665                        let line_height = position_map.line_height;
 7666                        let glyph_width = position_map.em_layout_width;
 7667                        let (delta, axis) = match delta {
 7668                            gpui::ScrollDelta::Pixels(mut pixels) => {
 7669                                //Trackpad
 7670                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
 7671                                (pixels, axis)
 7672                            }
 7673
 7674                            gpui::ScrollDelta::Lines(lines) => {
 7675                                //Not trackpad
 7676                                let pixels = point(lines.x * glyph_width, lines.y * line_height);
 7677                                (pixels, None)
 7678                            }
 7679                        };
 7680
 7681                        let current_scroll_position = position_map.snapshot.scroll_position();
 7682                        let x = (current_scroll_position.x * ScrollPixelOffset::from(glyph_width)
 7683                            - ScrollPixelOffset::from(delta.x * scroll_sensitivity))
 7684                            / ScrollPixelOffset::from(glyph_width);
 7685                        let y = (current_scroll_position.y * ScrollPixelOffset::from(line_height)
 7686                            - ScrollPixelOffset::from(delta.y * scroll_sensitivity))
 7687                            / ScrollPixelOffset::from(line_height);
 7688                        let mut scroll_position =
 7689                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
 7690                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
 7691                        if forbid_vertical_scroll {
 7692                            scroll_position.y = current_scroll_position.y;
 7693                        }
 7694
 7695                        if scroll_position != current_scroll_position {
 7696                            editor.scroll(scroll_position, axis, window, cx);
 7697                            cx.stop_propagation();
 7698                        } else if y < 0. {
 7699                            // Due to clamping, we may fail to detect cases of overscroll to the top;
 7700                            // We want the scroll manager to get an update in such cases and detect the change of direction
 7701                            // on the next frame.
 7702                            cx.notify();
 7703                        }
 7704                    });
 7705                }
 7706            }
 7707        });
 7708    }
 7709
 7710    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
 7711        if layout.mode.is_minimap() {
 7712            return;
 7713        }
 7714
 7715        self.paint_scroll_wheel_listener(layout, window, cx);
 7716
 7717        window.on_mouse_event({
 7718            let position_map = layout.position_map.clone();
 7719            let editor = self.editor.clone();
 7720            let line_numbers = layout.line_numbers.clone();
 7721
 7722            move |event: &MouseDownEvent, phase, window, cx| {
 7723                if phase == DispatchPhase::Bubble {
 7724                    match event.button {
 7725                        MouseButton::Left => editor.update(cx, |editor, cx| {
 7726                            let pending_mouse_down = editor
 7727                                .pending_mouse_down
 7728                                .get_or_insert_with(Default::default)
 7729                                .clone();
 7730
 7731                            *pending_mouse_down.borrow_mut() = Some(event.clone());
 7732
 7733                            Self::mouse_left_down(
 7734                                editor,
 7735                                event,
 7736                                &position_map,
 7737                                line_numbers.as_ref(),
 7738                                window,
 7739                                cx,
 7740                            );
 7741                        }),
 7742                        MouseButton::Right => editor.update(cx, |editor, cx| {
 7743                            Self::mouse_right_down(editor, event, &position_map, window, cx);
 7744                        }),
 7745                        MouseButton::Middle => editor.update(cx, |editor, cx| {
 7746                            Self::mouse_middle_down(editor, event, &position_map, window, cx);
 7747                        }),
 7748                        _ => {}
 7749                    };
 7750                }
 7751            }
 7752        });
 7753
 7754        window.on_mouse_event({
 7755            let editor = self.editor.clone();
 7756            let position_map = layout.position_map.clone();
 7757
 7758            move |event: &MouseUpEvent, phase, window, cx| {
 7759                if phase == DispatchPhase::Bubble {
 7760                    editor.update(cx, |editor, cx| {
 7761                        Self::mouse_up(editor, event, &position_map, window, cx)
 7762                    });
 7763                }
 7764            }
 7765        });
 7766
 7767        window.on_mouse_event({
 7768            let editor = self.editor.clone();
 7769            let position_map = layout.position_map.clone();
 7770            let mut captured_mouse_down = None;
 7771
 7772            move |event: &MouseUpEvent, phase, window, cx| match phase {
 7773                // Clear the pending mouse down during the capture phase,
 7774                // so that it happens even if another event handler stops
 7775                // propagation.
 7776                DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
 7777                    let pending_mouse_down = editor
 7778                        .pending_mouse_down
 7779                        .get_or_insert_with(Default::default)
 7780                        .clone();
 7781
 7782                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
 7783                    if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
 7784                        captured_mouse_down = pending_mouse_down.take();
 7785                        window.refresh();
 7786                    }
 7787                }),
 7788                // Fire click handlers during the bubble phase.
 7789                DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
 7790                    if let Some(mouse_down) = captured_mouse_down.take() {
 7791                        let event = ClickEvent::Mouse(MouseClickEvent {
 7792                            down: mouse_down,
 7793                            up: event.clone(),
 7794                        });
 7795                        Self::click(editor, &event, &position_map, window, cx);
 7796                    }
 7797                }),
 7798            }
 7799        });
 7800
 7801        window.on_mouse_event({
 7802            let position_map = layout.position_map.clone();
 7803            let editor = self.editor.clone();
 7804
 7805            move |event: &MousePressureEvent, phase, window, cx| {
 7806                if phase == DispatchPhase::Bubble {
 7807                    editor.update(cx, |editor, cx| {
 7808                        Self::pressure_click(editor, &event, &position_map, window, cx);
 7809                    })
 7810                }
 7811            }
 7812        });
 7813
 7814        window.on_mouse_event({
 7815            let position_map = layout.position_map.clone();
 7816            let editor = self.editor.clone();
 7817            let split_side = self.split_side;
 7818
 7819            move |event: &MouseMoveEvent, phase, window, cx| {
 7820                if phase == DispatchPhase::Bubble {
 7821                    editor.update(cx, |editor, cx| {
 7822                        if editor.hover_state.focused(window, cx) {
 7823                            return;
 7824                        }
 7825                        if event.pressed_button == Some(MouseButton::Left)
 7826                            || event.pressed_button == Some(MouseButton::Middle)
 7827                        {
 7828                            Self::mouse_dragged(editor, event, &position_map, window, cx)
 7829                        }
 7830
 7831                        Self::mouse_moved(editor, event, &position_map, split_side, window, cx)
 7832                    });
 7833                }
 7834            }
 7835        });
 7836    }
 7837
 7838    fn shape_line_number(
 7839        &self,
 7840        text: SharedString,
 7841        color: Hsla,
 7842        window: &mut Window,
 7843    ) -> ShapedLine {
 7844        let run = TextRun {
 7845            len: text.len(),
 7846            font: self.style.text.font(),
 7847            color,
 7848            ..Default::default()
 7849        };
 7850        window.text_system().shape_line(
 7851            text,
 7852            self.style.text.font_size.to_pixels(window.rem_size()),
 7853            &[run],
 7854            None,
 7855        )
 7856    }
 7857
 7858    fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
 7859        let unstaged = status.has_secondary_hunk();
 7860        let unstaged_hollow = matches!(
 7861            ProjectSettings::get_global(cx).git.hunk_style,
 7862            GitHunkStyleSetting::UnstagedHollow
 7863        );
 7864
 7865        unstaged == unstaged_hollow
 7866    }
 7867
 7868    #[cfg(debug_assertions)]
 7869    fn layout_debug_ranges(
 7870        selections: &mut Vec<(PlayerColor, Vec<SelectionLayout>)>,
 7871        anchor_range: Range<Anchor>,
 7872        display_snapshot: &DisplaySnapshot,
 7873        cx: &App,
 7874    ) {
 7875        let theme = cx.theme();
 7876        text::debug::GlobalDebugRanges::with_locked(|debug_ranges| {
 7877            if debug_ranges.ranges.is_empty() {
 7878                return;
 7879            }
 7880            let buffer_snapshot = &display_snapshot.buffer_snapshot();
 7881            for (buffer, buffer_range, excerpt_id) in
 7882                buffer_snapshot.range_to_buffer_ranges(anchor_range.start..=anchor_range.end)
 7883            {
 7884                let buffer_range =
 7885                    buffer.anchor_after(buffer_range.start)..buffer.anchor_before(buffer_range.end);
 7886                selections.extend(debug_ranges.ranges.iter().flat_map(|debug_range| {
 7887                    let player_color = theme
 7888                        .players()
 7889                        .color_for_participant(debug_range.occurrence_index as u32 + 1);
 7890                    debug_range.ranges.iter().filter_map(move |range| {
 7891                        if range.start.buffer_id != Some(buffer.remote_id()) {
 7892                            return None;
 7893                        }
 7894                        let clipped_start = range.start.max(&buffer_range.start, buffer);
 7895                        let clipped_end = range.end.min(&buffer_range.end, buffer);
 7896                        let range = buffer_snapshot
 7897                            .anchor_range_in_excerpt(excerpt_id, *clipped_start..*clipped_end)?;
 7898                        let start = range.start.to_display_point(display_snapshot);
 7899                        let end = range.end.to_display_point(display_snapshot);
 7900                        let selection_layout = SelectionLayout {
 7901                            head: start,
 7902                            range: start..end,
 7903                            cursor_shape: CursorShape::Bar,
 7904                            is_newest: false,
 7905                            is_local: false,
 7906                            active_rows: start.row()..end.row(),
 7907                            user_name: Some(SharedString::new(debug_range.value.clone())),
 7908                        };
 7909                        Some((player_color, vec![selection_layout]))
 7910                    })
 7911                }));
 7912            }
 7913        });
 7914    }
 7915}
 7916
 7917pub fn render_breadcrumb_text(
 7918    mut segments: Vec<HighlightedText>,
 7919    breadcrumb_font: Option<Font>,
 7920    prefix: Option<gpui::AnyElement>,
 7921    active_item: &dyn ItemHandle,
 7922    multibuffer_header: bool,
 7923    window: &mut Window,
 7924    cx: &App,
 7925) -> gpui::AnyElement {
 7926    const MAX_SEGMENTS: usize = 12;
 7927
 7928    let element = h_flex().flex_grow().text_ui(cx);
 7929
 7930    let prefix_end_ix = cmp::min(segments.len(), MAX_SEGMENTS / 2);
 7931    let suffix_start_ix = cmp::max(
 7932        prefix_end_ix,
 7933        segments.len().saturating_sub(MAX_SEGMENTS / 2),
 7934    );
 7935
 7936    if suffix_start_ix > prefix_end_ix {
 7937        segments.splice(
 7938            prefix_end_ix..suffix_start_ix,
 7939            Some(HighlightedText {
 7940                text: "β‹―".into(),
 7941                highlights: vec![],
 7942            }),
 7943        );
 7944    }
 7945
 7946    let highlighted_segments = segments.into_iter().enumerate().map(|(index, segment)| {
 7947        let mut text_style = window.text_style();
 7948        if let Some(font) = &breadcrumb_font {
 7949            text_style.font_family = font.family.clone();
 7950            text_style.font_features = font.features.clone();
 7951            text_style.font_style = font.style;
 7952            text_style.font_weight = font.weight;
 7953        }
 7954        text_style.color = Color::Muted.color(cx);
 7955
 7956        if index == 0
 7957            && !workspace::TabBarSettings::get_global(cx).show
 7958            && active_item.is_dirty(cx)
 7959            && let Some(styled_element) = apply_dirty_filename_style(&segment, &text_style, cx)
 7960        {
 7961            return styled_element;
 7962        }
 7963
 7964        StyledText::new(segment.text.replace('\n', " "))
 7965            .with_default_highlights(&text_style, segment.highlights)
 7966            .into_any()
 7967    });
 7968
 7969    let breadcrumbs = Itertools::intersperse_with(highlighted_segments, || {
 7970        Label::new("β€Ί").color(Color::Placeholder).into_any_element()
 7971    });
 7972
 7973    let breadcrumbs_stack = h_flex()
 7974        .gap_1()
 7975        .when(multibuffer_header, |this| {
 7976            this.pl_2()
 7977                .border_l_1()
 7978                .border_color(cx.theme().colors().border.opacity(0.6))
 7979        })
 7980        .children(breadcrumbs);
 7981
 7982    let breadcrumbs = if let Some(prefix) = prefix {
 7983        h_flex().gap_1p5().child(prefix).child(breadcrumbs_stack)
 7984    } else {
 7985        breadcrumbs_stack
 7986    };
 7987
 7988    let editor = active_item
 7989        .downcast::<Editor>()
 7990        .map(|editor| editor.downgrade());
 7991
 7992    let has_project_path = active_item.project_path(cx).is_some();
 7993
 7994    match editor {
 7995        Some(editor) => element
 7996            .id("breadcrumb_container")
 7997            .when(!multibuffer_header, |this| this.overflow_x_scroll())
 7998            .child(
 7999                ButtonLike::new("toggle outline view")
 8000                    .child(breadcrumbs)
 8001                    .when(multibuffer_header, |this| {
 8002                        this.style(ButtonStyle::Transparent)
 8003                    })
 8004                    .when(!multibuffer_header, |this| {
 8005                        let focus_handle = editor.upgrade().unwrap().focus_handle(&cx);
 8006
 8007                        this.tooltip(Tooltip::element(move |_window, cx| {
 8008                            v_flex()
 8009                                .gap_1()
 8010                                .child(
 8011                                    h_flex()
 8012                                        .gap_1()
 8013                                        .justify_between()
 8014                                        .child(Label::new("Show Symbol Outline"))
 8015                                        .child(ui::KeyBinding::for_action_in(
 8016                                            &zed_actions::outline::ToggleOutline,
 8017                                            &focus_handle,
 8018                                            cx,
 8019                                        )),
 8020                                )
 8021                                .when(has_project_path, |this| {
 8022                                    this.child(
 8023                                        h_flex()
 8024                                            .gap_1()
 8025                                            .justify_between()
 8026                                            .pt_1()
 8027                                            .border_t_1()
 8028                                            .border_color(cx.theme().colors().border_variant)
 8029                                            .child(Label::new("Right-Click to Copy Path")),
 8030                                    )
 8031                                })
 8032                                .into_any_element()
 8033                        }))
 8034                        .on_click({
 8035                            let editor = editor.clone();
 8036                            move |_, window, cx| {
 8037                                if let Some((editor, callback)) = editor
 8038                                    .upgrade()
 8039                                    .zip(zed_actions::outline::TOGGLE_OUTLINE.get())
 8040                                {
 8041                                    callback(editor.to_any_view(), window, cx);
 8042                                }
 8043                            }
 8044                        })
 8045                        .when(has_project_path, |this| {
 8046                            this.on_right_click({
 8047                                let editor = editor.clone();
 8048                                move |_, _, cx| {
 8049                                    if let Some(abs_path) = editor.upgrade().and_then(|editor| {
 8050                                        editor.update(cx, |editor, cx| {
 8051                                            editor.target_file_abs_path(cx)
 8052                                        })
 8053                                    }) {
 8054                                        if let Some(path_str) = abs_path.to_str() {
 8055                                            cx.write_to_clipboard(ClipboardItem::new_string(
 8056                                                path_str.to_string(),
 8057                                            ));
 8058                                        }
 8059                                    }
 8060                                }
 8061                            })
 8062                        })
 8063                    }),
 8064            )
 8065            .into_any_element(),
 8066        None => element
 8067            .h(rems_from_px(22.)) // Match the height and padding of the `ButtonLike` in the other arm.
 8068            .pl_1()
 8069            .child(breadcrumbs)
 8070            .into_any_element(),
 8071    }
 8072}
 8073
 8074fn apply_dirty_filename_style(
 8075    segment: &HighlightedText,
 8076    text_style: &gpui::TextStyle,
 8077    cx: &App,
 8078) -> Option<gpui::AnyElement> {
 8079    let text = segment.text.replace('\n', " ");
 8080
 8081    let filename_position = std::path::Path::new(segment.text.as_ref())
 8082        .file_name()
 8083        .and_then(|f| {
 8084            let filename_str = f.to_string_lossy();
 8085            segment.text.rfind(filename_str.as_ref())
 8086        })?;
 8087
 8088    let bold_weight = FontWeight::BOLD;
 8089    let default_color = Color::Default.color(cx);
 8090
 8091    if filename_position == 0 {
 8092        let mut filename_style = text_style.clone();
 8093        filename_style.font_weight = bold_weight;
 8094        filename_style.color = default_color;
 8095
 8096        return Some(
 8097            StyledText::new(text)
 8098                .with_default_highlights(&filename_style, [])
 8099                .into_any(),
 8100        );
 8101    }
 8102
 8103    let highlight_style = gpui::HighlightStyle {
 8104        font_weight: Some(bold_weight),
 8105        color: Some(default_color),
 8106        ..Default::default()
 8107    };
 8108
 8109    let highlight = vec![(filename_position..text.len(), highlight_style)];
 8110    Some(
 8111        StyledText::new(text)
 8112            .with_default_highlights(text_style, highlight)
 8113            .into_any(),
 8114    )
 8115}
 8116
 8117fn file_status_label_color(file_status: Option<FileStatus>) -> Color {
 8118    file_status.map_or(Color::Default, |status| {
 8119        if status.is_conflicted() {
 8120            Color::Conflict
 8121        } else if status.is_modified() {
 8122            Color::Modified
 8123        } else if status.is_deleted() {
 8124            Color::Disabled
 8125        } else if status.is_created() {
 8126            Color::Created
 8127        } else {
 8128            Color::Default
 8129        }
 8130    })
 8131}
 8132
 8133pub(crate) fn header_jump_data(
 8134    editor_snapshot: &EditorSnapshot,
 8135    block_row_start: DisplayRow,
 8136    height: u32,
 8137    first_excerpt: &ExcerptInfo,
 8138    latest_selection_anchors: &HashMap<BufferId, Anchor>,
 8139) -> JumpData {
 8140    let jump_target = if let Some(anchor) = latest_selection_anchors.get(&first_excerpt.buffer_id)
 8141        && let Some(range) = editor_snapshot.context_range_for_excerpt(anchor.excerpt_id)
 8142        && let Some(buffer) = editor_snapshot
 8143            .buffer_snapshot()
 8144            .buffer_for_excerpt(anchor.excerpt_id)
 8145    {
 8146        JumpTargetInExcerptInput {
 8147            id: anchor.excerpt_id,
 8148            buffer,
 8149            excerpt_start_anchor: range.start,
 8150            jump_anchor: anchor.text_anchor,
 8151        }
 8152    } else {
 8153        JumpTargetInExcerptInput {
 8154            id: first_excerpt.id,
 8155            buffer: &first_excerpt.buffer,
 8156            excerpt_start_anchor: first_excerpt.range.context.start,
 8157            jump_anchor: first_excerpt.range.primary.start,
 8158        }
 8159    };
 8160    header_jump_data_inner(editor_snapshot, block_row_start, height, &jump_target)
 8161}
 8162
 8163struct JumpTargetInExcerptInput<'a> {
 8164    id: ExcerptId,
 8165    buffer: &'a language::BufferSnapshot,
 8166    excerpt_start_anchor: text::Anchor,
 8167    jump_anchor: text::Anchor,
 8168}
 8169
 8170fn header_jump_data_inner(
 8171    snapshot: &EditorSnapshot,
 8172    block_row_start: DisplayRow,
 8173    height: u32,
 8174    for_excerpt: &JumpTargetInExcerptInput,
 8175) -> JumpData {
 8176    let buffer = &for_excerpt.buffer;
 8177    let jump_position = language::ToPoint::to_point(&for_excerpt.jump_anchor, buffer);
 8178    let excerpt_start = for_excerpt.excerpt_start_anchor;
 8179    let rows_from_excerpt_start = if for_excerpt.jump_anchor == excerpt_start {
 8180        0
 8181    } else {
 8182        let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
 8183        jump_position.row.saturating_sub(excerpt_start_point.row)
 8184    };
 8185
 8186    let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
 8187        .saturating_sub(
 8188            snapshot
 8189                .scroll_anchor
 8190                .scroll_position(&snapshot.display_snapshot)
 8191                .y as u32,
 8192        );
 8193
 8194    JumpData::MultiBufferPoint {
 8195        excerpt_id: for_excerpt.id,
 8196        anchor: for_excerpt.jump_anchor,
 8197        position: jump_position,
 8198        line_offset_from_top,
 8199    }
 8200}
 8201
 8202pub(crate) fn render_buffer_header(
 8203    editor: &Entity<Editor>,
 8204    for_excerpt: &ExcerptInfo,
 8205    is_folded: bool,
 8206    is_selected: bool,
 8207    is_sticky: bool,
 8208    jump_data: JumpData,
 8209    window: &mut Window,
 8210    cx: &mut App,
 8211) -> impl IntoElement {
 8212    let editor_read = editor.read(cx);
 8213    let multi_buffer = editor_read.buffer.read(cx);
 8214    let is_read_only = editor_read.read_only(cx);
 8215    let editor_handle: &dyn ItemHandle = editor;
 8216
 8217    let breadcrumbs = if is_selected {
 8218        editor_read.breadcrumbs_inner(cx)
 8219    } else {
 8220        None
 8221    };
 8222
 8223    let file_status = multi_buffer
 8224        .all_diff_hunks_expanded()
 8225        .then(|| editor_read.status_for_buffer_id(for_excerpt.buffer_id, cx))
 8226        .flatten();
 8227    let indicator = multi_buffer
 8228        .buffer(for_excerpt.buffer_id)
 8229        .and_then(|buffer| {
 8230            let buffer = buffer.read(cx);
 8231            let indicator_color = match (buffer.has_conflict(), buffer.is_dirty()) {
 8232                (true, _) => Some(Color::Warning),
 8233                (_, true) => Some(Color::Accent),
 8234                (false, false) => None,
 8235            };
 8236            indicator_color.map(|indicator_color| Indicator::dot().color(indicator_color))
 8237        });
 8238
 8239    let include_root = editor_read
 8240        .project
 8241        .as_ref()
 8242        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 8243        .unwrap_or_default();
 8244    let file = for_excerpt.buffer.file();
 8245    let can_open_excerpts = file.is_none_or(|file| file.can_open());
 8246    let path_style = file.map(|file| file.path_style(cx));
 8247    let relative_path = for_excerpt.buffer.resolve_file_path(include_root, cx);
 8248    let (parent_path, filename) = if let Some(path) = &relative_path {
 8249        if let Some(path_style) = path_style {
 8250            let (dir, file_name) = path_style.split(path);
 8251            (dir.map(|dir| dir.to_owned()), Some(file_name.to_owned()))
 8252        } else {
 8253            (None, Some(path.clone()))
 8254        }
 8255    } else {
 8256        (None, None)
 8257    };
 8258    let focus_handle = editor_read.focus_handle(cx);
 8259    let colors = cx.theme().colors();
 8260
 8261    let header = div()
 8262        .id(("buffer-header", for_excerpt.buffer_id.to_proto()))
 8263        .p(BUFFER_HEADER_PADDING)
 8264        .w_full()
 8265        .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
 8266        .child(
 8267            h_flex()
 8268                .group("buffer-header-group")
 8269                .size_full()
 8270                .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
 8271                .pl_1()
 8272                .pr_2()
 8273                .rounded_sm()
 8274                .gap_1p5()
 8275                .when(is_sticky, |el| el.shadow_md())
 8276                .border_1()
 8277                .map(|border| {
 8278                    let border_color =
 8279                        if is_selected && is_folded && focus_handle.contains_focused(window, cx) {
 8280                            colors.border_focused
 8281                        } else {
 8282                            colors.border
 8283                        };
 8284                    border.border_color(border_color)
 8285                })
 8286                .bg(colors.editor_subheader_background)
 8287                .hover(|style| style.bg(colors.element_hover))
 8288                .map(|header| {
 8289                    let editor = editor.clone();
 8290                    let buffer_id = for_excerpt.buffer_id;
 8291                    let toggle_chevron_icon =
 8292                        FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
 8293                    let button_size = rems_from_px(28.);
 8294
 8295                    header.child(
 8296                        div()
 8297                            .hover(|style| style.bg(colors.element_selected))
 8298                            .rounded_xs()
 8299                            .child(
 8300                                ButtonLike::new("toggle-buffer-fold")
 8301                                    .style(ButtonStyle::Transparent)
 8302                                    .height(button_size.into())
 8303                                    .width(button_size)
 8304                                    .children(toggle_chevron_icon)
 8305                                    .tooltip({
 8306                                        let focus_handle = focus_handle.clone();
 8307                                        let is_folded_for_tooltip = is_folded;
 8308                                        move |_window, cx| {
 8309                                            Tooltip::with_meta_in(
 8310                                                if is_folded_for_tooltip {
 8311                                                    "Unfold Excerpt"
 8312                                                } else {
 8313                                                    "Fold Excerpt"
 8314                                                },
 8315                                                Some(&ToggleFold),
 8316                                                format!(
 8317                                                    "{} to toggle all",
 8318                                                    text_for_keystroke(
 8319                                                        &Modifiers::alt(),
 8320                                                        "click",
 8321                                                        cx
 8322                                                    )
 8323                                                ),
 8324                                                &focus_handle,
 8325                                                cx,
 8326                                            )
 8327                                        }
 8328                                    })
 8329                                    .on_click(move |event, window, cx| {
 8330                                        if event.modifiers().alt {
 8331                                            editor.update(cx, |editor, cx| {
 8332                                                editor.toggle_fold_all(&ToggleFoldAll, window, cx);
 8333                                            });
 8334                                        } else {
 8335                                            if is_folded {
 8336                                                editor.update(cx, |editor, cx| {
 8337                                                    editor.unfold_buffer(buffer_id, cx);
 8338                                                });
 8339                                            } else {
 8340                                                editor.update(cx, |editor, cx| {
 8341                                                    editor.fold_buffer(buffer_id, cx);
 8342                                                });
 8343                                            }
 8344                                        }
 8345                                    }),
 8346                            ),
 8347                    )
 8348                })
 8349                .children(
 8350                    editor_read
 8351                        .addons
 8352                        .values()
 8353                        .filter_map(|addon| {
 8354                            addon.render_buffer_header_controls(for_excerpt, window, cx)
 8355                        })
 8356                        .take(1),
 8357                )
 8358                .when(!is_read_only, |this| {
 8359                    this.child(
 8360                        h_flex()
 8361                            .size_3()
 8362                            .justify_center()
 8363                            .flex_shrink_0()
 8364                            .children(indicator),
 8365                    )
 8366                })
 8367                .child(
 8368                    h_flex()
 8369                        .cursor_pointer()
 8370                        .id("path_header_block")
 8371                        .min_w_0()
 8372                        .size_full()
 8373                        .gap_1()
 8374                        .justify_between()
 8375                        .overflow_hidden()
 8376                        .child(h_flex().min_w_0().flex_1().gap_0p5().overflow_hidden().map(
 8377                            |path_header| {
 8378                                let filename = filename
 8379                                    .map(SharedString::from)
 8380                                    .unwrap_or_else(|| "untitled".into());
 8381
 8382                                let full_path = match parent_path.as_deref() {
 8383                                    Some(parent) if !parent.is_empty() => {
 8384                                        format!("{}{}", parent, filename.as_str())
 8385                                    }
 8386                                    _ => filename.as_str().to_string(),
 8387                                };
 8388
 8389                                path_header
 8390                                    .child(
 8391                                        ButtonLike::new("filename-button")
 8392                                            .when(ItemSettings::get_global(cx).file_icons, |this| {
 8393                                                let path = path::Path::new(filename.as_str());
 8394                                                let icon = FileIcons::get_icon(path, cx)
 8395                                                    .unwrap_or_default();
 8396
 8397                                                this.child(
 8398                                                    Icon::from_path(icon).color(Color::Muted),
 8399                                                )
 8400                                            })
 8401                                            .child(
 8402                                                Label::new(filename)
 8403                                                    .single_line()
 8404                                                    .color(file_status_label_color(file_status))
 8405                                                    .buffer_font(cx)
 8406                                                    .when(
 8407                                                        file_status.is_some_and(|s| s.is_deleted()),
 8408                                                        |label| label.strikethrough(),
 8409                                                    ),
 8410                                            )
 8411                                            .tooltip(move |_, cx| {
 8412                                                Tooltip::with_meta(
 8413                                                    "Open File",
 8414                                                    None,
 8415                                                    full_path.clone(),
 8416                                                    cx,
 8417                                                )
 8418                                            })
 8419                                            .on_click(window.listener_for(editor, {
 8420                                                let jump_data = jump_data.clone();
 8421                                                move |editor, e: &ClickEvent, window, cx| {
 8422                                                    editor.open_excerpts_common(
 8423                                                        Some(jump_data.clone()),
 8424                                                        e.modifiers().secondary(),
 8425                                                        window,
 8426                                                        cx,
 8427                                                    );
 8428                                                }
 8429                                            })),
 8430                                    )
 8431                                    .when_some(parent_path, |then, path| {
 8432                                        then.child(
 8433                                            Label::new(path)
 8434                                                .buffer_font(cx)
 8435                                                .truncate_start()
 8436                                                .color(
 8437                                                    if file_status
 8438                                                        .is_some_and(FileStatus::is_deleted)
 8439                                                    {
 8440                                                        Color::Custom(colors.text_disabled)
 8441                                                    } else {
 8442                                                        Color::Custom(colors.text_muted)
 8443                                                    },
 8444                                                ),
 8445                                        )
 8446                                    })
 8447                                    .when(!for_excerpt.buffer.capability.editable(), |el| {
 8448                                        el.child(Icon::new(IconName::FileLock).color(Color::Muted))
 8449                                    })
 8450                                    .when_some(breadcrumbs, |then, breadcrumbs| {
 8451                                        let font = theme::ThemeSettings::get_global(cx)
 8452                                            .buffer_font
 8453                                            .clone();
 8454                                        then.child(render_breadcrumb_text(
 8455                                            breadcrumbs,
 8456                                            Some(font),
 8457                                            None,
 8458                                            editor_handle,
 8459                                            true,
 8460                                            window,
 8461                                            cx,
 8462                                        ))
 8463                                    })
 8464                            },
 8465                        ))
 8466                        .when(can_open_excerpts && relative_path.is_some(), |this| {
 8467                            this.child(
 8468                                div()
 8469                                    .when(!is_selected, |this| {
 8470                                        this.visible_on_hover("buffer-header-group")
 8471                                    })
 8472                                    .child(
 8473                                        Button::new("open-file-button", "Open File")
 8474                                            .style(ButtonStyle::OutlinedGhost)
 8475                                            .when(is_selected, |this| {
 8476                                                this.key_binding(KeyBinding::for_action_in(
 8477                                                    &OpenExcerpts,
 8478                                                    &focus_handle,
 8479                                                    cx,
 8480                                                ))
 8481                                            })
 8482                                            .on_click(window.listener_for(editor, {
 8483                                                let jump_data = jump_data.clone();
 8484                                                move |editor, e: &ClickEvent, window, cx| {
 8485                                                    editor.open_excerpts_common(
 8486                                                        Some(jump_data.clone()),
 8487                                                        e.modifiers().secondary(),
 8488                                                        window,
 8489                                                        cx,
 8490                                                    );
 8491                                                }
 8492                                            })),
 8493                                    ),
 8494                            )
 8495                        })
 8496                        .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 8497                        .on_click(window.listener_for(editor, {
 8498                            let buffer_id = for_excerpt.buffer_id;
 8499                            move |editor, e: &ClickEvent, window, cx| {
 8500                                if e.modifiers().alt {
 8501                                    editor.open_excerpts_common(
 8502                                        Some(jump_data.clone()),
 8503                                        e.modifiers().secondary(),
 8504                                        window,
 8505                                        cx,
 8506                                    );
 8507                                    return;
 8508                                }
 8509
 8510                                if is_folded {
 8511                                    editor.unfold_buffer(buffer_id, cx);
 8512                                } else {
 8513                                    editor.fold_buffer(buffer_id, cx);
 8514                                }
 8515                            }
 8516                        })),
 8517                ),
 8518        );
 8519
 8520    let file = for_excerpt.buffer.file().cloned();
 8521    let editor = editor.clone();
 8522
 8523    right_click_menu("buffer-header-context-menu")
 8524        .trigger(move |_, _, _| header)
 8525        .menu(move |window, cx| {
 8526            let menu_context = focus_handle.clone();
 8527            let editor = editor.clone();
 8528            let file = file.clone();
 8529            ContextMenu::build(window, cx, move |mut menu, window, cx| {
 8530                if let Some(file) = file
 8531                    && let Some(project) = editor.read(cx).project()
 8532                    && let Some(worktree) =
 8533                        project.read(cx).worktree_for_id(file.worktree_id(cx), cx)
 8534                {
 8535                    let path_style = file.path_style(cx);
 8536                    let worktree = worktree.read(cx);
 8537                    let relative_path = file.path();
 8538                    let entry_for_path = worktree.entry_for_path(relative_path);
 8539                    let abs_path = entry_for_path.map(|e| {
 8540                        e.canonical_path
 8541                            .as_deref()
 8542                            .map_or_else(|| worktree.absolutize(relative_path), Path::to_path_buf)
 8543                    });
 8544                    let has_relative_path = worktree.root_entry().is_some_and(Entry::is_dir);
 8545
 8546                    let parent_abs_path = abs_path
 8547                        .as_ref()
 8548                        .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
 8549                    let relative_path = has_relative_path
 8550                        .then_some(relative_path)
 8551                        .map(ToOwned::to_owned);
 8552
 8553                    let visible_in_project_panel = relative_path.is_some() && worktree.is_visible();
 8554                    let reveal_in_project_panel = entry_for_path
 8555                        .filter(|_| visible_in_project_panel)
 8556                        .map(|entry| entry.id);
 8557                    menu = menu
 8558                        .when_some(abs_path, |menu, abs_path| {
 8559                            menu.entry(
 8560                                "Copy Path",
 8561                                Some(Box::new(zed_actions::workspace::CopyPath)),
 8562                                window.handler_for(&editor, move |_, _, cx| {
 8563                                    cx.write_to_clipboard(ClipboardItem::new_string(
 8564                                        abs_path.to_string_lossy().into_owned(),
 8565                                    ));
 8566                                }),
 8567                            )
 8568                        })
 8569                        .when_some(relative_path, |menu, relative_path| {
 8570                            menu.entry(
 8571                                "Copy Relative Path",
 8572                                Some(Box::new(zed_actions::workspace::CopyRelativePath)),
 8573                                window.handler_for(&editor, move |_, _, cx| {
 8574                                    cx.write_to_clipboard(ClipboardItem::new_string(
 8575                                        relative_path.display(path_style).to_string(),
 8576                                    ));
 8577                                }),
 8578                            )
 8579                        })
 8580                        .when(
 8581                            reveal_in_project_panel.is_some() || parent_abs_path.is_some(),
 8582                            |menu| menu.separator(),
 8583                        )
 8584                        .when_some(reveal_in_project_panel, |menu, entry_id| {
 8585                            menu.entry(
 8586                                "Reveal In Project Panel",
 8587                                Some(Box::new(RevealInProjectPanel::default())),
 8588                                window.handler_for(&editor, move |editor, _, cx| {
 8589                                    if let Some(project) = &mut editor.project {
 8590                                        project.update(cx, |_, cx| {
 8591                                            cx.emit(project::Event::RevealInProjectPanel(entry_id))
 8592                                        });
 8593                                    }
 8594                                }),
 8595                            )
 8596                        })
 8597                        .when_some(parent_abs_path, |menu, parent_abs_path| {
 8598                            menu.entry(
 8599                                "Open in Terminal",
 8600                                Some(Box::new(OpenInTerminal)),
 8601                                window.handler_for(&editor, move |_, window, cx| {
 8602                                    window.dispatch_action(
 8603                                        OpenTerminal {
 8604                                            working_directory: parent_abs_path.clone(),
 8605                                            local: false,
 8606                                        }
 8607                                        .boxed_clone(),
 8608                                        cx,
 8609                                    );
 8610                                }),
 8611                            )
 8612                        });
 8613                }
 8614
 8615                menu.context(menu_context)
 8616            })
 8617        })
 8618}
 8619
 8620fn prepaint_gutter_button(
 8621    mut button: AnyElement,
 8622    row: DisplayRow,
 8623    line_height: Pixels,
 8624    gutter_dimensions: &GutterDimensions,
 8625    scroll_position: gpui::Point<ScrollOffset>,
 8626    gutter_hitbox: &Hitbox,
 8627    window: &mut Window,
 8628    cx: &mut App,
 8629) -> AnyElement {
 8630    let available_space = size(
 8631        AvailableSpace::MinContent,
 8632        AvailableSpace::Definite(line_height),
 8633    );
 8634    let indicator_size = button.layout_as_root(available_space, window, cx);
 8635    let git_gutter_width = EditorElement::gutter_strip_width(line_height)
 8636        + gutter_dimensions
 8637            .git_blame_entries_width
 8638            .unwrap_or_default();
 8639
 8640    let x = git_gutter_width + px(2.);
 8641
 8642    let mut y =
 8643        Pixels::from((row.as_f64() - scroll_position.y) * ScrollPixelOffset::from(line_height));
 8644    y += (line_height - indicator_size.height) / 2.;
 8645
 8646    button.prepaint_as_root(
 8647        gutter_hitbox.origin + point(x, y),
 8648        available_space,
 8649        window,
 8650        cx,
 8651    );
 8652    button
 8653}
 8654
 8655fn render_inline_blame_entry(
 8656    blame_entry: BlameEntry,
 8657    style: &EditorStyle,
 8658    cx: &mut App,
 8659) -> Option<AnyElement> {
 8660    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 8661    renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
 8662}
 8663
 8664fn render_blame_entry_popover(
 8665    blame_entry: BlameEntry,
 8666    scroll_handle: ScrollHandle,
 8667    commit_message: Option<ParsedCommitMessage>,
 8668    markdown: Entity<Markdown>,
 8669    workspace: WeakEntity<Workspace>,
 8670    blame: &Entity<GitBlame>,
 8671    buffer: BufferId,
 8672    window: &mut Window,
 8673    cx: &mut App,
 8674) -> Option<AnyElement> {
 8675    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 8676    let blame = blame.read(cx);
 8677    let repository = blame.repository(cx, buffer)?;
 8678    renderer.render_blame_entry_popover(
 8679        blame_entry,
 8680        scroll_handle,
 8681        commit_message,
 8682        markdown,
 8683        repository,
 8684        workspace,
 8685        window,
 8686        cx,
 8687    )
 8688}
 8689
 8690fn render_blame_entry(
 8691    ix: usize,
 8692    blame: &Entity<GitBlame>,
 8693    blame_entry: BlameEntry,
 8694    style: &EditorStyle,
 8695    last_used_color: &mut Option<(Hsla, Oid)>,
 8696    editor: Entity<Editor>,
 8697    workspace: Entity<Workspace>,
 8698    buffer: BufferId,
 8699    renderer: &dyn BlameRenderer,
 8700    window: &mut Window,
 8701    cx: &mut App,
 8702) -> Option<AnyElement> {
 8703    let index: u32 = blame_entry.sha.into();
 8704    let mut sha_color = cx.theme().players().color_for_participant(index).cursor;
 8705
 8706    // If the last color we used is the same as the one we get for this line, but
 8707    // the commit SHAs are different, then we try again to get a different color.
 8708    if let Some((color, sha)) = *last_used_color
 8709        && sha != blame_entry.sha
 8710        && color == sha_color
 8711    {
 8712        sha_color = cx.theme().players().color_for_participant(index + 1).cursor;
 8713    }
 8714    last_used_color.replace((sha_color, blame_entry.sha));
 8715
 8716    let blame = blame.read(cx);
 8717    let details = blame.details_for_entry(buffer, &blame_entry);
 8718    let repository = blame.repository(cx, buffer)?;
 8719    renderer.render_blame_entry(
 8720        &style.text,
 8721        blame_entry,
 8722        details,
 8723        repository,
 8724        workspace.downgrade(),
 8725        editor,
 8726        ix,
 8727        sha_color,
 8728        window,
 8729        cx,
 8730    )
 8731}
 8732
 8733#[derive(Debug)]
 8734pub(crate) struct LineWithInvisibles {
 8735    fragments: SmallVec<[LineFragment; 1]>,
 8736    invisibles: Vec<Invisible>,
 8737    len: usize,
 8738    pub(crate) width: Pixels,
 8739    font_size: Pixels,
 8740}
 8741
 8742enum LineFragment {
 8743    Text(ShapedLine),
 8744    Element {
 8745        id: ChunkRendererId,
 8746        element: Option<AnyElement>,
 8747        size: Size<Pixels>,
 8748        len: usize,
 8749    },
 8750}
 8751
 8752impl fmt::Debug for LineFragment {
 8753    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 8754        match self {
 8755            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
 8756            LineFragment::Element { size, len, .. } => f
 8757                .debug_struct("Element")
 8758                .field("size", size)
 8759                .field("len", len)
 8760                .finish(),
 8761        }
 8762    }
 8763}
 8764
 8765impl LineWithInvisibles {
 8766    fn from_chunks<'a>(
 8767        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
 8768        editor_style: &EditorStyle,
 8769        max_line_len: usize,
 8770        max_line_count: usize,
 8771        editor_mode: &EditorMode,
 8772        text_width: Pixels,
 8773        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 8774        bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
 8775        window: &mut Window,
 8776        cx: &mut App,
 8777    ) -> Vec<Self> {
 8778        let text_style = &editor_style.text;
 8779        let mut layouts = Vec::with_capacity(max_line_count);
 8780        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
 8781        let mut line = String::new();
 8782        let mut invisibles = Vec::new();
 8783        let mut width = Pixels::ZERO;
 8784        let mut len = 0;
 8785        let mut styles = Vec::new();
 8786        let mut non_whitespace_added = false;
 8787        let mut row = 0;
 8788        let mut line_exceeded_max_len = false;
 8789        let font_size = text_style.font_size.to_pixels(window.rem_size());
 8790        let min_contrast = EditorSettings::get_global(cx).minimum_contrast_for_highlights;
 8791
 8792        let ellipsis = SharedString::from("β‹―");
 8793
 8794        for highlighted_chunk in chunks.chain([HighlightedChunk {
 8795            text: "\n",
 8796            style: None,
 8797            is_tab: false,
 8798            is_inlay: false,
 8799            replacement: None,
 8800        }]) {
 8801            if let Some(replacement) = highlighted_chunk.replacement {
 8802                if !line.is_empty() {
 8803                    let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
 8804                    let text_runs: &[TextRun] = if segments.is_empty() {
 8805                        &styles
 8806                    } else {
 8807                        &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
 8808                    };
 8809                    let shaped_line = window.text_system().shape_line(
 8810                        line.clone().into(),
 8811                        font_size,
 8812                        text_runs,
 8813                        None,
 8814                    );
 8815                    width += shaped_line.width;
 8816                    len += shaped_line.len;
 8817                    fragments.push(LineFragment::Text(shaped_line));
 8818                    line.clear();
 8819                    styles.clear();
 8820                }
 8821
 8822                match replacement {
 8823                    ChunkReplacement::Renderer(renderer) => {
 8824                        let available_width = if renderer.constrain_width {
 8825                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
 8826                                ellipsis.clone()
 8827                            } else {
 8828                                SharedString::from(Arc::from(highlighted_chunk.text))
 8829                            };
 8830                            let shaped_line = window.text_system().shape_line(
 8831                                chunk,
 8832                                font_size,
 8833                                &[text_style.to_run(highlighted_chunk.text.len())],
 8834                                None,
 8835                            );
 8836                            AvailableSpace::Definite(shaped_line.width)
 8837                        } else {
 8838                            AvailableSpace::MinContent
 8839                        };
 8840
 8841                        let mut element = (renderer.render)(&mut ChunkRendererContext {
 8842                            context: cx,
 8843                            window,
 8844                            max_width: text_width,
 8845                        });
 8846                        let line_height = text_style.line_height_in_pixels(window.rem_size());
 8847                        let size = element.layout_as_root(
 8848                            size(available_width, AvailableSpace::Definite(line_height)),
 8849                            window,
 8850                            cx,
 8851                        );
 8852
 8853                        width += size.width;
 8854                        len += highlighted_chunk.text.len();
 8855                        fragments.push(LineFragment::Element {
 8856                            id: renderer.id,
 8857                            element: Some(element),
 8858                            size,
 8859                            len: highlighted_chunk.text.len(),
 8860                        });
 8861                    }
 8862                    ChunkReplacement::Str(x) => {
 8863                        let text_style = if let Some(style) = highlighted_chunk.style {
 8864                            Cow::Owned(text_style.clone().highlight(style))
 8865                        } else {
 8866                            Cow::Borrowed(text_style)
 8867                        };
 8868
 8869                        let run = TextRun {
 8870                            len: x.len(),
 8871                            font: text_style.font(),
 8872                            color: text_style.color,
 8873                            background_color: text_style.background_color,
 8874                            underline: text_style.underline,
 8875                            strikethrough: text_style.strikethrough,
 8876                        };
 8877                        let line_layout = window
 8878                            .text_system()
 8879                            .shape_line(x, font_size, &[run], None)
 8880                            .with_len(highlighted_chunk.text.len());
 8881
 8882                        width += line_layout.width;
 8883                        len += highlighted_chunk.text.len();
 8884                        fragments.push(LineFragment::Text(line_layout))
 8885                    }
 8886                }
 8887            } else {
 8888                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
 8889                    if ix > 0 {
 8890                        let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
 8891                        let text_runs = if segments.is_empty() {
 8892                            &styles
 8893                        } else {
 8894                            &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
 8895                        };
 8896                        let shaped_line = window.text_system().shape_line(
 8897                            line.clone().into(),
 8898                            font_size,
 8899                            text_runs,
 8900                            None,
 8901                        );
 8902                        width += shaped_line.width;
 8903                        len += shaped_line.len;
 8904                        fragments.push(LineFragment::Text(shaped_line));
 8905                        layouts.push(Self {
 8906                            width: mem::take(&mut width),
 8907                            len: mem::take(&mut len),
 8908                            fragments: mem::take(&mut fragments),
 8909                            invisibles: std::mem::take(&mut invisibles),
 8910                            font_size,
 8911                        });
 8912
 8913                        line.clear();
 8914                        styles.clear();
 8915                        row += 1;
 8916                        line_exceeded_max_len = false;
 8917                        non_whitespace_added = false;
 8918                        if row == max_line_count {
 8919                            return layouts;
 8920                        }
 8921                    }
 8922
 8923                    if !line_chunk.is_empty() && !line_exceeded_max_len {
 8924                        let text_style = if let Some(style) = highlighted_chunk.style {
 8925                            Cow::Owned(text_style.clone().highlight(style))
 8926                        } else {
 8927                            Cow::Borrowed(text_style)
 8928                        };
 8929
 8930                        if line.len() + line_chunk.len() > max_line_len {
 8931                            let mut chunk_len = max_line_len - line.len();
 8932                            while !line_chunk.is_char_boundary(chunk_len) {
 8933                                chunk_len -= 1;
 8934                            }
 8935                            line_chunk = &line_chunk[..chunk_len];
 8936                            line_exceeded_max_len = true;
 8937                        }
 8938
 8939                        styles.push(TextRun {
 8940                            len: line_chunk.len(),
 8941                            font: text_style.font(),
 8942                            color: text_style.color,
 8943                            background_color: text_style.background_color,
 8944                            underline: text_style.underline,
 8945                            strikethrough: text_style.strikethrough,
 8946                        });
 8947
 8948                        if editor_mode.is_full() && !highlighted_chunk.is_inlay {
 8949                            // Line wrap pads its contents with fake whitespaces,
 8950                            // avoid printing them
 8951                            let is_soft_wrapped = is_row_soft_wrapped(row);
 8952                            if highlighted_chunk.is_tab {
 8953                                if non_whitespace_added || !is_soft_wrapped {
 8954                                    invisibles.push(Invisible::Tab {
 8955                                        line_start_offset: line.len(),
 8956                                        line_end_offset: line.len() + line_chunk.len(),
 8957                                    });
 8958                                }
 8959                            } else {
 8960                                invisibles.extend(line_chunk.char_indices().filter_map(
 8961                                    |(index, c)| {
 8962                                        let is_whitespace = c.is_whitespace();
 8963                                        non_whitespace_added |= !is_whitespace;
 8964                                        if is_whitespace
 8965                                            && (non_whitespace_added || !is_soft_wrapped)
 8966                                        {
 8967                                            Some(Invisible::Whitespace {
 8968                                                line_offset: line.len() + index,
 8969                                            })
 8970                                        } else {
 8971                                            None
 8972                                        }
 8973                                    },
 8974                                ))
 8975                            }
 8976                        }
 8977
 8978                        line.push_str(line_chunk);
 8979                    }
 8980                }
 8981            }
 8982        }
 8983
 8984        layouts
 8985    }
 8986
 8987    /// Takes text runs and non-overlapping left-to-right background ranges with color.
 8988    /// Returns new text runs with adjusted contrast as per background ranges.
 8989    fn split_runs_by_bg_segments(
 8990        text_runs: &[TextRun],
 8991        bg_segments: &[(Range<DisplayPoint>, Hsla)],
 8992        min_contrast: f32,
 8993        start_col_offset: usize,
 8994    ) -> Vec<TextRun> {
 8995        let mut output_runs: Vec<TextRun> = Vec::with_capacity(text_runs.len());
 8996        let mut line_col = start_col_offset;
 8997        let mut segment_ix = 0usize;
 8998
 8999        for text_run in text_runs.iter() {
 9000            let run_start_col = line_col;
 9001            let run_end_col = run_start_col + text_run.len;
 9002            while segment_ix < bg_segments.len()
 9003                && (bg_segments[segment_ix].0.end.column() as usize) <= run_start_col
 9004            {
 9005                segment_ix += 1;
 9006            }
 9007            let mut cursor_col = run_start_col;
 9008            let mut local_segment_ix = segment_ix;
 9009            while local_segment_ix < bg_segments.len() {
 9010                let (range, segment_color) = &bg_segments[local_segment_ix];
 9011                let segment_start_col = range.start.column() as usize;
 9012                let segment_end_col = range.end.column() as usize;
 9013                if segment_start_col >= run_end_col {
 9014                    break;
 9015                }
 9016                if segment_start_col > cursor_col {
 9017                    let span_len = segment_start_col - cursor_col;
 9018                    output_runs.push(TextRun {
 9019                        len: span_len,
 9020                        font: text_run.font.clone(),
 9021                        color: text_run.color,
 9022                        background_color: text_run.background_color,
 9023                        underline: text_run.underline,
 9024                        strikethrough: text_run.strikethrough,
 9025                    });
 9026                    cursor_col = segment_start_col;
 9027                }
 9028                let segment_slice_end_col = segment_end_col.min(run_end_col);
 9029                if segment_slice_end_col > cursor_col {
 9030                    let new_text_color =
 9031                        ensure_minimum_contrast(text_run.color, *segment_color, min_contrast);
 9032                    output_runs.push(TextRun {
 9033                        len: segment_slice_end_col - cursor_col,
 9034                        font: text_run.font.clone(),
 9035                        color: new_text_color,
 9036                        background_color: text_run.background_color,
 9037                        underline: text_run.underline,
 9038                        strikethrough: text_run.strikethrough,
 9039                    });
 9040                    cursor_col = segment_slice_end_col;
 9041                }
 9042                if segment_end_col >= run_end_col {
 9043                    break;
 9044                }
 9045                local_segment_ix += 1;
 9046            }
 9047            if cursor_col < run_end_col {
 9048                output_runs.push(TextRun {
 9049                    len: run_end_col - cursor_col,
 9050                    font: text_run.font.clone(),
 9051                    color: text_run.color,
 9052                    background_color: text_run.background_color,
 9053                    underline: text_run.underline,
 9054                    strikethrough: text_run.strikethrough,
 9055                });
 9056            }
 9057            line_col = run_end_col;
 9058            segment_ix = local_segment_ix;
 9059        }
 9060        output_runs
 9061    }
 9062
 9063    fn prepaint(
 9064        &mut self,
 9065        line_height: Pixels,
 9066        scroll_position: gpui::Point<ScrollOffset>,
 9067        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 9068        row: DisplayRow,
 9069        content_origin: gpui::Point<Pixels>,
 9070        line_elements: &mut SmallVec<[AnyElement; 1]>,
 9071        window: &mut Window,
 9072        cx: &mut App,
 9073    ) {
 9074        let line_y = f32::from(line_height) * Pixels::from(row.as_f64() - scroll_position.y);
 9075        self.prepaint_with_custom_offset(
 9076            line_height,
 9077            scroll_pixel_position,
 9078            content_origin,
 9079            line_y,
 9080            line_elements,
 9081            window,
 9082            cx,
 9083        );
 9084    }
 9085
 9086    fn prepaint_with_custom_offset(
 9087        &mut self,
 9088        line_height: Pixels,
 9089        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 9090        content_origin: gpui::Point<Pixels>,
 9091        line_y: Pixels,
 9092        line_elements: &mut SmallVec<[AnyElement; 1]>,
 9093        window: &mut Window,
 9094        cx: &mut App,
 9095    ) {
 9096        let mut fragment_origin =
 9097            content_origin + gpui::point(Pixels::from(-scroll_pixel_position.x), line_y);
 9098        for fragment in &mut self.fragments {
 9099            match fragment {
 9100                LineFragment::Text(line) => {
 9101                    fragment_origin.x += line.width;
 9102                }
 9103                LineFragment::Element { element, size, .. } => {
 9104                    let mut element = element
 9105                        .take()
 9106                        .expect("you can't prepaint LineWithInvisibles twice");
 9107
 9108                    // Center the element vertically within the line.
 9109                    let mut element_origin = fragment_origin;
 9110                    element_origin.y += (line_height - size.height) / 2.;
 9111                    element.prepaint_at(element_origin, window, cx);
 9112                    line_elements.push(element);
 9113
 9114                    fragment_origin.x += size.width;
 9115                }
 9116            }
 9117        }
 9118    }
 9119
 9120    fn draw(
 9121        &self,
 9122        layout: &EditorLayout,
 9123        row: DisplayRow,
 9124        content_origin: gpui::Point<Pixels>,
 9125        whitespace_setting: ShowWhitespaceSetting,
 9126        selection_ranges: &[Range<DisplayPoint>],
 9127        window: &mut Window,
 9128        cx: &mut App,
 9129    ) {
 9130        self.draw_with_custom_offset(
 9131            layout,
 9132            row,
 9133            content_origin,
 9134            layout.position_map.line_height
 9135                * (row.as_f64() - layout.position_map.scroll_position.y) as f32,
 9136            whitespace_setting,
 9137            selection_ranges,
 9138            window,
 9139            cx,
 9140        );
 9141    }
 9142
 9143    fn draw_with_custom_offset(
 9144        &self,
 9145        layout: &EditorLayout,
 9146        row: DisplayRow,
 9147        content_origin: gpui::Point<Pixels>,
 9148        line_y: Pixels,
 9149        whitespace_setting: ShowWhitespaceSetting,
 9150        selection_ranges: &[Range<DisplayPoint>],
 9151        window: &mut Window,
 9152        cx: &mut App,
 9153    ) {
 9154        let line_height = layout.position_map.line_height;
 9155        let mut fragment_origin = content_origin
 9156            + gpui::point(
 9157                Pixels::from(-layout.position_map.scroll_pixel_position.x),
 9158                line_y,
 9159            );
 9160
 9161        for fragment in &self.fragments {
 9162            match fragment {
 9163                LineFragment::Text(line) => {
 9164                    line.paint(
 9165                        fragment_origin,
 9166                        line_height,
 9167                        layout.text_align,
 9168                        Some(layout.content_width),
 9169                        window,
 9170                        cx,
 9171                    )
 9172                    .log_err();
 9173                    fragment_origin.x += line.width;
 9174                }
 9175                LineFragment::Element { size, .. } => {
 9176                    fragment_origin.x += size.width;
 9177                }
 9178            }
 9179        }
 9180
 9181        self.draw_invisibles(
 9182            selection_ranges,
 9183            layout,
 9184            content_origin,
 9185            line_y,
 9186            row,
 9187            line_height,
 9188            whitespace_setting,
 9189            window,
 9190            cx,
 9191        );
 9192    }
 9193
 9194    fn draw_background(
 9195        &self,
 9196        layout: &EditorLayout,
 9197        row: DisplayRow,
 9198        content_origin: gpui::Point<Pixels>,
 9199        window: &mut Window,
 9200        cx: &mut App,
 9201    ) {
 9202        let line_height = layout.position_map.line_height;
 9203        let line_y = line_height * (row.as_f64() - layout.position_map.scroll_position.y) as f32;
 9204
 9205        let mut fragment_origin = content_origin
 9206            + gpui::point(
 9207                Pixels::from(-layout.position_map.scroll_pixel_position.x),
 9208                line_y,
 9209            );
 9210
 9211        for fragment in &self.fragments {
 9212            match fragment {
 9213                LineFragment::Text(line) => {
 9214                    line.paint_background(
 9215                        fragment_origin,
 9216                        line_height,
 9217                        layout.text_align,
 9218                        Some(layout.content_width),
 9219                        window,
 9220                        cx,
 9221                    )
 9222                    .log_err();
 9223                    fragment_origin.x += line.width;
 9224                }
 9225                LineFragment::Element { size, .. } => {
 9226                    fragment_origin.x += size.width;
 9227                }
 9228            }
 9229        }
 9230    }
 9231
 9232    fn draw_invisibles(
 9233        &self,
 9234        selection_ranges: &[Range<DisplayPoint>],
 9235        layout: &EditorLayout,
 9236        content_origin: gpui::Point<Pixels>,
 9237        line_y: Pixels,
 9238        row: DisplayRow,
 9239        line_height: Pixels,
 9240        whitespace_setting: ShowWhitespaceSetting,
 9241        window: &mut Window,
 9242        cx: &mut App,
 9243    ) {
 9244        let extract_whitespace_info = |invisible: &Invisible| {
 9245            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
 9246                Invisible::Tab {
 9247                    line_start_offset,
 9248                    line_end_offset,
 9249                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
 9250                Invisible::Whitespace { line_offset } => {
 9251                    (*line_offset, line_offset + 1, &layout.space_invisible)
 9252                }
 9253            };
 9254
 9255            let x_offset: ScrollPixelOffset = self.x_for_index(token_offset).into();
 9256            let invisible_offset: ScrollPixelOffset =
 9257                ((layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0)
 9258                    .into();
 9259            let origin = content_origin
 9260                + gpui::point(
 9261                    Pixels::from(
 9262                        x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
 9263                    ),
 9264                    line_y,
 9265                );
 9266
 9267            (
 9268                [token_offset, token_end_offset],
 9269                Box::new(move |window: &mut Window, cx: &mut App| {
 9270                    invisible_symbol
 9271                        .paint(origin, line_height, TextAlign::Left, None, window, cx)
 9272                        .log_err();
 9273                }),
 9274            )
 9275        };
 9276
 9277        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
 9278        match whitespace_setting {
 9279            ShowWhitespaceSetting::None => (),
 9280            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
 9281            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
 9282                let invisible_point = DisplayPoint::new(row, start as u32);
 9283                if !selection_ranges
 9284                    .iter()
 9285                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
 9286                {
 9287                    return;
 9288                }
 9289
 9290                paint(window, cx);
 9291            }),
 9292
 9293            ShowWhitespaceSetting::Trailing => {
 9294                let mut previous_start = self.len;
 9295                for ([start, end], paint) in invisible_iter.rev() {
 9296                    if previous_start != end {
 9297                        break;
 9298                    }
 9299                    previous_start = start;
 9300                    paint(window, cx);
 9301                }
 9302            }
 9303
 9304            // For a whitespace to be on a boundary, any of the following conditions need to be met:
 9305            // - It is a tab
 9306            // - It is adjacent to an edge (start or end)
 9307            // - It is adjacent to a whitespace (left or right)
 9308            ShowWhitespaceSetting::Boundary => {
 9309                // We'll need to keep track of the last invisible we've seen and then check if we are adjacent to it for some of
 9310                // the above cases.
 9311                // Note: We zip in the original `invisibles` to check for tab equality
 9312                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
 9313                for (([start, end], paint), invisible) in
 9314                    invisible_iter.zip_eq(self.invisibles.iter())
 9315                {
 9316                    let should_render = match (&last_seen, invisible) {
 9317                        (_, Invisible::Tab { .. }) => true,
 9318                        (Some((_, last_end, _)), _) => *last_end == start,
 9319                        _ => false,
 9320                    };
 9321
 9322                    if should_render || start == 0 || end == self.len {
 9323                        paint(window, cx);
 9324
 9325                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
 9326                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
 9327                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
 9328                            // Note that we need to make sure that the last one is actually adjacent
 9329                            if !should_render_last && last_end == start {
 9330                                paint_last(window, cx);
 9331                            }
 9332                        }
 9333                    }
 9334
 9335                    // Manually render anything within a selection
 9336                    let invisible_point = DisplayPoint::new(row, start as u32);
 9337                    if selection_ranges.iter().any(|region| {
 9338                        region.start <= invisible_point && invisible_point < region.end
 9339                    }) {
 9340                        paint(window, cx);
 9341                    }
 9342
 9343                    last_seen = Some((should_render, end, paint));
 9344                }
 9345            }
 9346        }
 9347    }
 9348
 9349    pub fn x_for_index(&self, index: usize) -> Pixels {
 9350        let mut fragment_start_x = Pixels::ZERO;
 9351        let mut fragment_start_index = 0;
 9352
 9353        for fragment in &self.fragments {
 9354            match fragment {
 9355                LineFragment::Text(shaped_line) => {
 9356                    let fragment_end_index = fragment_start_index + shaped_line.len;
 9357                    if index < fragment_end_index {
 9358                        return fragment_start_x
 9359                            + shaped_line.x_for_index(index - fragment_start_index);
 9360                    }
 9361                    fragment_start_x += shaped_line.width;
 9362                    fragment_start_index = fragment_end_index;
 9363                }
 9364                LineFragment::Element { len, size, .. } => {
 9365                    let fragment_end_index = fragment_start_index + len;
 9366                    if index < fragment_end_index {
 9367                        return fragment_start_x;
 9368                    }
 9369                    fragment_start_x += size.width;
 9370                    fragment_start_index = fragment_end_index;
 9371                }
 9372            }
 9373        }
 9374
 9375        fragment_start_x
 9376    }
 9377
 9378    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
 9379        let mut fragment_start_x = Pixels::ZERO;
 9380        let mut fragment_start_index = 0;
 9381
 9382        for fragment in &self.fragments {
 9383            match fragment {
 9384                LineFragment::Text(shaped_line) => {
 9385                    let fragment_end_x = fragment_start_x + shaped_line.width;
 9386                    if x < fragment_end_x {
 9387                        return Some(
 9388                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
 9389                        );
 9390                    }
 9391                    fragment_start_x = fragment_end_x;
 9392                    fragment_start_index += shaped_line.len;
 9393                }
 9394                LineFragment::Element { len, size, .. } => {
 9395                    let fragment_end_x = fragment_start_x + size.width;
 9396                    if x < fragment_end_x {
 9397                        return Some(fragment_start_index);
 9398                    }
 9399                    fragment_start_index += len;
 9400                    fragment_start_x = fragment_end_x;
 9401                }
 9402            }
 9403        }
 9404
 9405        None
 9406    }
 9407
 9408    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
 9409        let mut fragment_start_index = 0;
 9410
 9411        for fragment in &self.fragments {
 9412            match fragment {
 9413                LineFragment::Text(shaped_line) => {
 9414                    let fragment_end_index = fragment_start_index + shaped_line.len;
 9415                    if index < fragment_end_index {
 9416                        return shaped_line.font_id_for_index(index - fragment_start_index);
 9417                    }
 9418                    fragment_start_index = fragment_end_index;
 9419                }
 9420                LineFragment::Element { len, .. } => {
 9421                    let fragment_end_index = fragment_start_index + len;
 9422                    if index < fragment_end_index {
 9423                        return None;
 9424                    }
 9425                    fragment_start_index = fragment_end_index;
 9426                }
 9427            }
 9428        }
 9429
 9430        None
 9431    }
 9432
 9433    pub fn alignment_offset(&self, text_align: TextAlign, content_width: Pixels) -> Pixels {
 9434        let line_width = self.width;
 9435        match text_align {
 9436            TextAlign::Left => px(0.0),
 9437            TextAlign::Center => (content_width - line_width) / 2.0,
 9438            TextAlign::Right => content_width - line_width,
 9439        }
 9440    }
 9441}
 9442
 9443#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 9444enum Invisible {
 9445    /// A tab character
 9446    ///
 9447    /// A tab character is internally represented by spaces (configured by the user's tab width)
 9448    /// aligned to the nearest column, so it's necessary to store the start and end offset for
 9449    /// adjacency checks.
 9450    Tab {
 9451        line_start_offset: usize,
 9452        line_end_offset: usize,
 9453    },
 9454    Whitespace {
 9455        line_offset: usize,
 9456    },
 9457}
 9458
 9459impl EditorElement {
 9460    /// Returns the rem size to use when rendering the [`EditorElement`].
 9461    ///
 9462    /// This allows UI elements to scale based on the `buffer_font_size`.
 9463    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
 9464        match self.editor.read(cx).mode {
 9465            EditorMode::Full {
 9466                scale_ui_elements_with_buffer_font_size: true,
 9467                ..
 9468            }
 9469            | EditorMode::Minimap { .. } => {
 9470                let buffer_font_size = self.style.text.font_size;
 9471                match buffer_font_size {
 9472                    AbsoluteLength::Pixels(pixels) => {
 9473                        let rem_size_scale = {
 9474                            // Our default UI font size is 14px on a 16px base scale.
 9475                            // This means the default UI font size is 0.875rems.
 9476                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
 9477
 9478                            // We then determine the delta between a single rem and the default font
 9479                            // size scale.
 9480                            let default_font_size_delta = 1. - default_font_size_scale;
 9481
 9482                            // Finally, we add this delta to 1rem to get the scale factor that
 9483                            // should be used to scale up the UI.
 9484                            1. + default_font_size_delta
 9485                        };
 9486
 9487                        Some(pixels * rem_size_scale)
 9488                    }
 9489                    AbsoluteLength::Rems(rems) => {
 9490                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
 9491                    }
 9492                }
 9493            }
 9494            // We currently use single-line and auto-height editors in UI contexts,
 9495            // so we don't want to scale everything with the buffer font size, as it
 9496            // ends up looking off.
 9497            _ => None,
 9498        }
 9499    }
 9500
 9501    fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
 9502        if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
 9503            parent.upgrade()
 9504        } else {
 9505            Some(self.editor.clone())
 9506        }
 9507    }
 9508}
 9509
 9510#[derive(Default)]
 9511pub struct EditorRequestLayoutState {
 9512    // We use prepaint depth to limit the number of times prepaint is
 9513    // called recursively. We need this so that we can update stale
 9514    // data for e.g. block heights in block map.
 9515    prepaint_depth: Rc<Cell<usize>>,
 9516}
 9517
 9518impl EditorRequestLayoutState {
 9519    // In ideal conditions we only need one more subsequent prepaint call for resize to take effect.
 9520    // i.e. MAX_PREPAINT_DEPTH = 2, but since moving blocks inline (place_near), more lines from
 9521    // below get exposed, and we end up querying blocks for those lines too in subsequent renders.
 9522    // Setting MAX_PREPAINT_DEPTH = 3, passes all tests. Just to be on the safe side we set it to 5, so
 9523    // that subsequent shrinking does not lead to incorrect block placing.
 9524    const MAX_PREPAINT_DEPTH: usize = 5;
 9525
 9526    fn increment_prepaint_depth(&self) -> EditorPrepaintGuard {
 9527        let depth = self.prepaint_depth.get();
 9528        self.prepaint_depth.set(depth + 1);
 9529        EditorPrepaintGuard {
 9530            prepaint_depth: self.prepaint_depth.clone(),
 9531        }
 9532    }
 9533
 9534    fn has_remaining_prepaint_depth(&self) -> bool {
 9535        self.prepaint_depth.get() < Self::MAX_PREPAINT_DEPTH
 9536    }
 9537}
 9538
 9539struct EditorPrepaintGuard {
 9540    prepaint_depth: Rc<Cell<usize>>,
 9541}
 9542
 9543impl Drop for EditorPrepaintGuard {
 9544    fn drop(&mut self) {
 9545        let depth = self.prepaint_depth.get();
 9546        self.prepaint_depth.set(depth.saturating_sub(1));
 9547    }
 9548}
 9549
 9550impl Element for EditorElement {
 9551    type RequestLayoutState = EditorRequestLayoutState;
 9552    type PrepaintState = EditorLayout;
 9553
 9554    fn id(&self) -> Option<ElementId> {
 9555        None
 9556    }
 9557
 9558    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
 9559        None
 9560    }
 9561
 9562    fn request_layout(
 9563        &mut self,
 9564        _: Option<&GlobalElementId>,
 9565        _inspector_id: Option<&gpui::InspectorElementId>,
 9566        window: &mut Window,
 9567        cx: &mut App,
 9568    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
 9569        let rem_size = self.rem_size(cx);
 9570        window.with_rem_size(rem_size, |window| {
 9571            self.editor.update(cx, |editor, cx| {
 9572                editor.set_style(self.style.clone(), window, cx);
 9573
 9574                let layout_id = match editor.mode {
 9575                    EditorMode::SingleLine => {
 9576                        let rem_size = window.rem_size();
 9577                        let height = self.style.text.line_height_in_pixels(rem_size);
 9578                        let mut style = Style::default();
 9579                        style.size.height = height.into();
 9580                        style.size.width = relative(1.).into();
 9581                        window.request_layout(style, None, cx)
 9582                    }
 9583                    EditorMode::AutoHeight {
 9584                        min_lines,
 9585                        max_lines,
 9586                    } => {
 9587                        let editor_handle = cx.entity();
 9588                        window.request_measured_layout(
 9589                            Style::default(),
 9590                            move |known_dimensions, available_space, window, cx| {
 9591                                editor_handle
 9592                                    .update(cx, |editor, cx| {
 9593                                        compute_auto_height_layout(
 9594                                            editor,
 9595                                            min_lines,
 9596                                            max_lines,
 9597                                            known_dimensions,
 9598                                            available_space.width,
 9599                                            window,
 9600                                            cx,
 9601                                        )
 9602                                    })
 9603                                    .unwrap_or_default()
 9604                            },
 9605                        )
 9606                    }
 9607                    EditorMode::Minimap { .. } => {
 9608                        let mut style = Style::default();
 9609                        style.size.width = relative(1.).into();
 9610                        style.size.height = relative(1.).into();
 9611                        window.request_layout(style, None, cx)
 9612                    }
 9613                    EditorMode::Full {
 9614                        sizing_behavior, ..
 9615                    } => {
 9616                        let mut style = Style::default();
 9617                        style.size.width = relative(1.).into();
 9618                        if sizing_behavior == SizingBehavior::SizeByContent {
 9619                            let snapshot = editor.snapshot(window, cx);
 9620                            let line_height =
 9621                                self.style.text.line_height_in_pixels(window.rem_size());
 9622                            let scroll_height =
 9623                                (snapshot.max_point().row().next_row().0 as f32) * line_height;
 9624                            style.size.height = scroll_height.into();
 9625                        } else {
 9626                            style.size.height = relative(1.).into();
 9627                        }
 9628                        window.request_layout(style, None, cx)
 9629                    }
 9630                };
 9631
 9632                (layout_id, EditorRequestLayoutState::default())
 9633            })
 9634        })
 9635    }
 9636
 9637    fn prepaint(
 9638        &mut self,
 9639        _: Option<&GlobalElementId>,
 9640        _inspector_id: Option<&gpui::InspectorElementId>,
 9641        bounds: Bounds<Pixels>,
 9642        request_layout: &mut Self::RequestLayoutState,
 9643        window: &mut Window,
 9644        cx: &mut App,
 9645    ) -> Self::PrepaintState {
 9646        let _prepaint_depth_guard = request_layout.increment_prepaint_depth();
 9647        let text_style = TextStyleRefinement {
 9648            font_size: Some(self.style.text.font_size),
 9649            line_height: Some(self.style.text.line_height),
 9650            ..Default::default()
 9651        };
 9652
 9653        let is_minimap = self.editor.read(cx).mode.is_minimap();
 9654        let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
 9655
 9656        if !is_minimap {
 9657            let focus_handle = self.editor.focus_handle(cx);
 9658            window.set_view_id(self.editor.entity_id());
 9659            window.set_focus_handle(&focus_handle, cx);
 9660        }
 9661
 9662        let rem_size = self.rem_size(cx);
 9663        window.with_rem_size(rem_size, |window| {
 9664            window.with_text_style(Some(text_style), |window| {
 9665                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 9666                    let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
 9667                        (editor.snapshot(window, cx), editor.read_only(cx))
 9668                    });
 9669                    let style = &self.style;
 9670
 9671                    let rem_size = window.rem_size();
 9672                    let font_id = window.text_system().resolve_font(&style.text.font());
 9673                    let font_size = style.text.font_size.to_pixels(rem_size);
 9674                    let line_height = style.text.line_height_in_pixels(rem_size);
 9675                    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
 9676                    let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
 9677                    let em_layout_width = window.text_system().em_layout_width(font_id, font_size);
 9678                    let glyph_grid_cell = size(em_advance, line_height);
 9679
 9680                    let gutter_dimensions =
 9681                        snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
 9682                    let text_width = bounds.size.width - gutter_dimensions.width;
 9683
 9684                    let settings = EditorSettings::get_global(cx);
 9685                    let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
 9686                    let vertical_scrollbar_width = (scrollbars_shown
 9687                        && settings.scrollbar.axes.vertical
 9688                        && self.editor.read(cx).show_scrollbars.vertical)
 9689                        .then_some(style.scrollbar_width)
 9690                        .unwrap_or_default();
 9691                    let minimap_width = self
 9692                        .get_minimap_width(
 9693                            &settings.minimap,
 9694                            scrollbars_shown,
 9695                            text_width,
 9696                            em_width,
 9697                            font_size,
 9698                            rem_size,
 9699                            cx,
 9700                        )
 9701                        .unwrap_or_default();
 9702
 9703                    let right_margin = minimap_width + vertical_scrollbar_width;
 9704
 9705                    let extended_right = 2 * em_width + right_margin;
 9706                    let editor_width = text_width - gutter_dimensions.margin - extended_right;
 9707                    let editor_margins = EditorMargins {
 9708                        gutter: gutter_dimensions,
 9709                        right: right_margin,
 9710                        extended_right,
 9711                    };
 9712
 9713                    snapshot = self.editor.update(cx, |editor, cx| {
 9714                        editor.last_bounds = Some(bounds);
 9715                        editor.gutter_dimensions = gutter_dimensions;
 9716                        editor.set_visible_line_count(
 9717                            (bounds.size.height / line_height) as f64,
 9718                            window,
 9719                            cx,
 9720                        );
 9721                        editor.set_visible_column_count(f64::from(editor_width / em_advance));
 9722
 9723                        if matches!(
 9724                            editor.mode,
 9725                            EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
 9726                        ) {
 9727                            snapshot
 9728                        } else {
 9729                            let wrap_width = calculate_wrap_width(
 9730                                editor.soft_wrap_mode(cx),
 9731                                editor_width,
 9732                                em_layout_width,
 9733                            );
 9734
 9735                            if editor.set_wrap_width(wrap_width, cx) {
 9736                                editor.snapshot(window, cx)
 9737                            } else {
 9738                                snapshot
 9739                            }
 9740                        }
 9741                    });
 9742
 9743                    let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
 9744                    let gutter_hitbox = window.insert_hitbox(
 9745                        gutter_bounds(bounds, gutter_dimensions),
 9746                        HitboxBehavior::Normal,
 9747                    );
 9748                    let text_hitbox = window.insert_hitbox(
 9749                        Bounds {
 9750                            origin: gutter_hitbox.top_right(),
 9751                            size: size(text_width, bounds.size.height),
 9752                        },
 9753                        HitboxBehavior::Normal,
 9754                    );
 9755
 9756                    // Offset the content_bounds from the text_bounds by the gutter margin (which
 9757                    // is roughly half a character wide) to make hit testing work more like how we want.
 9758                    let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
 9759                    let content_origin = text_hitbox.origin + content_offset;
 9760
 9761                    let height_in_lines = f64::from(bounds.size.height / line_height);
 9762                    let max_row = snapshot.max_point().row().as_f64();
 9763
 9764                    // Calculate how much of the editor is clipped by parent containers (e.g., List).
 9765                    // This allows us to only render lines that are actually visible, which is
 9766                    // critical for performance when large AutoHeight editors are inside Lists.
 9767                    let visible_bounds = window.content_mask().bounds;
 9768                    let clipped_top = (visible_bounds.origin.y - bounds.origin.y).max(px(0.));
 9769                    let clipped_top_in_lines = f64::from(clipped_top / line_height);
 9770                    let visible_height_in_lines =
 9771                        f64::from(visible_bounds.size.height / line_height);
 9772
 9773                    // The max scroll position for the top of the window
 9774                    let max_scroll_top = if matches!(
 9775                        snapshot.mode,
 9776                        EditorMode::SingleLine
 9777                            | EditorMode::AutoHeight { .. }
 9778                            | EditorMode::Full {
 9779                                sizing_behavior: SizingBehavior::ExcludeOverscrollMargin
 9780                                    | SizingBehavior::SizeByContent,
 9781                                ..
 9782                            }
 9783                    ) {
 9784                        (max_row - height_in_lines + 1.).max(0.)
 9785                    } else {
 9786                        let settings = EditorSettings::get_global(cx);
 9787                        match settings.scroll_beyond_last_line {
 9788                            ScrollBeyondLastLine::OnePage => max_row,
 9789                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
 9790                            ScrollBeyondLastLine::VerticalScrollMargin => {
 9791                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
 9792                                    .max(0.)
 9793                            }
 9794                        }
 9795                    };
 9796
 9797                    let (
 9798                        autoscroll_request,
 9799                        autoscroll_containing_element,
 9800                        needs_horizontal_autoscroll,
 9801                    ) = self.editor.update(cx, |editor, cx| {
 9802                        let autoscroll_request = editor.scroll_manager.take_autoscroll_request();
 9803
 9804                        let autoscroll_containing_element =
 9805                            autoscroll_request.is_some() || editor.has_pending_selection();
 9806
 9807                        let (needs_horizontal_autoscroll, was_scrolled) = editor
 9808                            .autoscroll_vertically(
 9809                                bounds,
 9810                                line_height,
 9811                                max_scroll_top,
 9812                                autoscroll_request,
 9813                                window,
 9814                                cx,
 9815                            );
 9816                        if was_scrolled.0 {
 9817                            snapshot = editor.snapshot(window, cx);
 9818                        }
 9819                        (
 9820                            autoscroll_request,
 9821                            autoscroll_containing_element,
 9822                            needs_horizontal_autoscroll,
 9823                        )
 9824                    });
 9825
 9826                    let mut scroll_position = snapshot.scroll_position();
 9827                    // The scroll position is a fractional point, the whole number of which represents
 9828                    // the top of the window in terms of display rows.
 9829                    // We add clipped_top_in_lines to skip rows that are clipped by parent containers,
 9830                    // but we don't modify scroll_position itself since the parent handles positioning.
 9831                    let max_row = snapshot.max_point().row();
 9832                    let start_row = cmp::min(
 9833                        DisplayRow((scroll_position.y + clipped_top_in_lines).floor() as u32),
 9834                        max_row,
 9835                    );
 9836                    let end_row = cmp::min(
 9837                        (scroll_position.y + clipped_top_in_lines + visible_height_in_lines).ceil()
 9838                            as u32,
 9839                        max_row.next_row().0,
 9840                    );
 9841                    let end_row = DisplayRow(end_row);
 9842
 9843                    let row_infos = snapshot // note we only get the visual range
 9844                        .row_infos(start_row)
 9845                        .take((start_row..end_row).len())
 9846                        .collect::<Vec<RowInfo>>();
 9847                    let is_row_soft_wrapped = |row: usize| {
 9848                        row_infos
 9849                            .get(row)
 9850                            .is_none_or(|info| info.buffer_row.is_none())
 9851                    };
 9852
 9853                    let start_anchor = if start_row == Default::default() {
 9854                        Anchor::min()
 9855                    } else {
 9856                        snapshot.buffer_snapshot().anchor_before(
 9857                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
 9858                        )
 9859                    };
 9860                    let end_anchor = if end_row > max_row {
 9861                        Anchor::max()
 9862                    } else {
 9863                        snapshot.buffer_snapshot().anchor_before(
 9864                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
 9865                        )
 9866                    };
 9867
 9868                    let mut highlighted_rows = self
 9869                        .editor
 9870                        .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
 9871
 9872                    let is_light = cx.theme().appearance().is_light();
 9873
 9874                    let mut highlighted_ranges = self
 9875                        .editor_with_selections(cx)
 9876                        .map(|editor| {
 9877                            if editor == self.editor {
 9878                                editor.read(cx).background_highlights_in_range(
 9879                                    start_anchor..end_anchor,
 9880                                    &snapshot.display_snapshot,
 9881                                    cx.theme(),
 9882                                )
 9883                            } else {
 9884                                editor.update(cx, |editor, cx| {
 9885                                    let snapshot = editor.snapshot(window, cx);
 9886                                    let start_anchor = if start_row == Default::default() {
 9887                                        Anchor::min()
 9888                                    } else {
 9889                                        snapshot.buffer_snapshot().anchor_before(
 9890                                            DisplayPoint::new(start_row, 0)
 9891                                                .to_offset(&snapshot, Bias::Left),
 9892                                        )
 9893                                    };
 9894                                    let end_anchor = if end_row > max_row {
 9895                                        Anchor::max()
 9896                                    } else {
 9897                                        snapshot.buffer_snapshot().anchor_before(
 9898                                            DisplayPoint::new(end_row, 0)
 9899                                                .to_offset(&snapshot, Bias::Right),
 9900                                        )
 9901                                    };
 9902
 9903                                    editor.background_highlights_in_range(
 9904                                        start_anchor..end_anchor,
 9905                                        &snapshot.display_snapshot,
 9906                                        cx.theme(),
 9907                                    )
 9908                                })
 9909                            }
 9910                        })
 9911                        .unwrap_or_default();
 9912
 9913                    for (ix, row_info) in row_infos.iter().enumerate() {
 9914                        let Some(diff_status) = row_info.diff_status else {
 9915                            continue;
 9916                        };
 9917
 9918                        let background_color = match diff_status.kind {
 9919                            DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
 9920                            DiffHunkStatusKind::Deleted => {
 9921                                cx.theme().colors().version_control_deleted
 9922                            }
 9923                            DiffHunkStatusKind::Modified => {
 9924                                debug_panic!("modified diff status for row info");
 9925                                continue;
 9926                            }
 9927                        };
 9928
 9929                        let hunk_opacity = if is_light { 0.16 } else { 0.12 };
 9930
 9931                        let hollow_highlight = LineHighlight {
 9932                            background: (background_color.opacity(if is_light {
 9933                                0.08
 9934                            } else {
 9935                                0.06
 9936                            }))
 9937                            .into(),
 9938                            border: Some(if is_light {
 9939                                background_color.opacity(0.48)
 9940                            } else {
 9941                                background_color.opacity(0.36)
 9942                            }),
 9943                            include_gutter: true,
 9944                            type_id: None,
 9945                        };
 9946
 9947                        let filled_highlight = LineHighlight {
 9948                            background: solid_background(background_color.opacity(hunk_opacity)),
 9949                            border: None,
 9950                            include_gutter: true,
 9951                            type_id: None,
 9952                        };
 9953
 9954                        let background = if Self::diff_hunk_hollow(diff_status, cx) {
 9955                            hollow_highlight
 9956                        } else {
 9957                            filled_highlight
 9958                        };
 9959
 9960                        let base_display_point =
 9961                            DisplayPoint::new(start_row + DisplayRow(ix as u32), 0);
 9962
 9963                        highlighted_rows
 9964                            .entry(base_display_point.row())
 9965                            .or_insert(background);
 9966                    }
 9967
 9968                    // Add diff review drag selection highlight to text area
 9969                    if let Some(drag_state) = &self.editor.read(cx).diff_review_drag_state {
 9970                        let range = drag_state.row_range(&snapshot.display_snapshot);
 9971                        let start_row = range.start().0;
 9972                        let end_row = range.end().0;
 9973                        let drag_highlight_color =
 9974                            cx.theme().colors().editor_active_line_background;
 9975                        let drag_highlight = LineHighlight {
 9976                            background: solid_background(drag_highlight_color),
 9977                            border: Some(cx.theme().colors().border_focused),
 9978                            include_gutter: true,
 9979                            type_id: None,
 9980                        };
 9981                        for row_num in start_row..=end_row {
 9982                            highlighted_rows
 9983                                .entry(DisplayRow(row_num))
 9984                                .or_insert(drag_highlight);
 9985                        }
 9986                    }
 9987
 9988                    let highlighted_gutter_ranges =
 9989                        self.editor.read(cx).gutter_highlights_in_range(
 9990                            start_anchor..end_anchor,
 9991                            &snapshot.display_snapshot,
 9992                            cx,
 9993                        );
 9994
 9995                    let document_colors = self
 9996                        .editor
 9997                        .read(cx)
 9998                        .colors
 9999                        .as_ref()
10000                        .map(|colors| colors.editor_display_highlights(&snapshot));
10001                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
10002                        start_anchor..end_anchor,
10003                        &snapshot.display_snapshot,
10004                        cx,
10005                    );
10006
10007                    let (local_selections, selected_buffer_ids, latest_selection_anchors): (
10008                        Vec<Selection<Point>>,
10009                        Vec<BufferId>,
10010                        HashMap<BufferId, Anchor>,
10011                    ) = self
10012                        .editor_with_selections(cx)
10013                        .map(|editor| {
10014                            editor.update(cx, |editor, cx| {
10015                                let all_selections =
10016                                    editor.selections.all::<Point>(&snapshot.display_snapshot);
10017                                let all_anchor_selections =
10018                                    editor.selections.all_anchors(&snapshot.display_snapshot);
10019                                let selected_buffer_ids =
10020                                    if editor.buffer_kind(cx) == ItemBufferKind::Singleton {
10021                                        Vec::new()
10022                                    } else {
10023                                        let mut selected_buffer_ids =
10024                                            Vec::with_capacity(all_selections.len());
10025
10026                                        for selection in all_selections {
10027                                            for buffer_id in snapshot
10028                                                .buffer_snapshot()
10029                                                .buffer_ids_for_range(selection.range())
10030                                            {
10031                                                if selected_buffer_ids.last() != Some(&buffer_id) {
10032                                                    selected_buffer_ids.push(buffer_id);
10033                                                }
10034                                            }
10035                                        }
10036
10037                                        selected_buffer_ids
10038                                    };
10039
10040                                let mut selections = editor.selections.disjoint_in_range(
10041                                    start_anchor..end_anchor,
10042                                    &snapshot.display_snapshot,
10043                                );
10044                                selections
10045                                    .extend(editor.selections.pending(&snapshot.display_snapshot));
10046
10047                                let mut anchors_by_buffer: HashMap<BufferId, (usize, Anchor)> =
10048                                    HashMap::default();
10049                                for selection in all_anchor_selections.iter() {
10050                                    let head = selection.head();
10051                                    if let Some(buffer_id) = head.text_anchor.buffer_id {
10052                                        anchors_by_buffer
10053                                            .entry(buffer_id)
10054                                            .and_modify(|(latest_id, latest_anchor)| {
10055                                                if selection.id > *latest_id {
10056                                                    *latest_id = selection.id;
10057                                                    *latest_anchor = head;
10058                                                }
10059                                            })
10060                                            .or_insert((selection.id, head));
10061                                    }
10062                                }
10063                                let latest_selection_anchors = anchors_by_buffer
10064                                    .into_iter()
10065                                    .map(|(buffer_id, (_, anchor))| (buffer_id, anchor))
10066                                    .collect();
10067
10068                                (selections, selected_buffer_ids, latest_selection_anchors)
10069                            })
10070                        })
10071                        .unwrap_or_else(|| (Vec::new(), Vec::new(), HashMap::default()));
10072
10073                    let (selections, mut active_rows, newest_selection_head) = self
10074                        .layout_selections(
10075                            start_anchor,
10076                            end_anchor,
10077                            &local_selections,
10078                            &snapshot,
10079                            start_row,
10080                            end_row,
10081                            window,
10082                            cx,
10083                        );
10084
10085                    // relative rows are based on newest selection, even outside the visible area
10086                    let current_selection_head = self.editor.update(cx, |editor, cx| {
10087                        (editor.selections.count() != 0).then(|| {
10088                            let newest = editor
10089                                .selections
10090                                .newest::<Point>(&editor.display_snapshot(cx));
10091
10092                            SelectionLayout::new(
10093                                newest,
10094                                editor.selections.line_mode(),
10095                                editor.cursor_offset_on_selection,
10096                                editor.cursor_shape,
10097                                &snapshot,
10098                                true,
10099                                true,
10100                                None,
10101                            )
10102                            .head
10103                            .row()
10104                        })
10105                    });
10106
10107                    let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
10108                        editor.active_breakpoints(start_row..end_row, window, cx)
10109                    });
10110                    for (display_row, (_, bp, state)) in &breakpoint_rows {
10111                        if bp.is_enabled() && state.is_none_or(|s| s.verified) {
10112                            active_rows.entry(*display_row).or_default().breakpoint = true;
10113                        }
10114                    }
10115
10116                    let line_numbers = self.layout_line_numbers(
10117                        Some(&gutter_hitbox),
10118                        gutter_dimensions,
10119                        line_height,
10120                        scroll_position,
10121                        start_row..end_row,
10122                        &row_infos,
10123                        &active_rows,
10124                        current_selection_head,
10125                        &snapshot,
10126                        window,
10127                        cx,
10128                    );
10129
10130                    // We add the gutter breakpoint indicator to breakpoint_rows after painting
10131                    // line numbers so we don't paint a line number debug accent color if a user
10132                    // has their mouse over that line when a breakpoint isn't there
10133                    self.editor.update(cx, |editor, _| {
10134                        if let Some(phantom_breakpoint) = &mut editor
10135                            .gutter_breakpoint_indicator
10136                            .0
10137                            .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
10138                        {
10139                            // Is there a non-phantom breakpoint on this line?
10140                            phantom_breakpoint.collides_with_existing_breakpoint = true;
10141                            breakpoint_rows
10142                                .entry(phantom_breakpoint.display_row)
10143                                .or_insert_with(|| {
10144                                    let position = snapshot.display_point_to_anchor(
10145                                        DisplayPoint::new(phantom_breakpoint.display_row, 0),
10146                                        Bias::Right,
10147                                    );
10148                                    let breakpoint = Breakpoint::new_standard();
10149                                    phantom_breakpoint.collides_with_existing_breakpoint = false;
10150                                    (position, breakpoint, None)
10151                                });
10152                        }
10153                    });
10154
10155                    let mut expand_toggles =
10156                        window.with_element_namespace("expand_toggles", |window| {
10157                            self.layout_expand_toggles(
10158                                &gutter_hitbox,
10159                                gutter_dimensions,
10160                                em_width,
10161                                line_height,
10162                                scroll_position,
10163                                &row_infos,
10164                                window,
10165                                cx,
10166                            )
10167                        });
10168
10169                    let mut crease_toggles =
10170                        window.with_element_namespace("crease_toggles", |window| {
10171                            self.layout_crease_toggles(
10172                                start_row..end_row,
10173                                &row_infos,
10174                                &active_rows,
10175                                &snapshot,
10176                                window,
10177                                cx,
10178                            )
10179                        });
10180                    let crease_trailers =
10181                        window.with_element_namespace("crease_trailers", |window| {
10182                            self.layout_crease_trailers(
10183                                row_infos.iter().cloned(),
10184                                &snapshot,
10185                                window,
10186                                cx,
10187                            )
10188                        });
10189
10190                    let display_hunks = self.layout_gutter_diff_hunks(
10191                        line_height,
10192                        &gutter_hitbox,
10193                        start_row..end_row,
10194                        &snapshot,
10195                        window,
10196                        cx,
10197                    );
10198
10199                    Self::layout_word_diff_highlights(
10200                        &display_hunks,
10201                        &row_infos,
10202                        start_row,
10203                        &snapshot,
10204                        &mut highlighted_ranges,
10205                        cx,
10206                    );
10207
10208                    let merged_highlighted_ranges =
10209                        if let Some((_, colors)) = document_colors.as_ref() {
10210                            &highlighted_ranges
10211                                .clone()
10212                                .into_iter()
10213                                .chain(colors.clone())
10214                                .collect()
10215                        } else {
10216                            &highlighted_ranges
10217                        };
10218                    let bg_segments_per_row = Self::bg_segments_per_row(
10219                        start_row..end_row,
10220                        &selections,
10221                        &merged_highlighted_ranges,
10222                        self.style.background,
10223                    );
10224
10225                    let mut line_layouts = Self::layout_lines(
10226                        start_row..end_row,
10227                        &snapshot,
10228                        &self.style,
10229                        editor_width,
10230                        is_row_soft_wrapped,
10231                        &bg_segments_per_row,
10232                        window,
10233                        cx,
10234                    );
10235                    let new_renderer_widths = (!is_minimap).then(|| {
10236                        line_layouts
10237                            .iter()
10238                            .flat_map(|layout| &layout.fragments)
10239                            .filter_map(|fragment| {
10240                                if let LineFragment::Element { id, size, .. } = fragment {
10241                                    Some((*id, size.width))
10242                                } else {
10243                                    None
10244                                }
10245                            })
10246                    });
10247                    let renderer_widths_changed = request_layout.has_remaining_prepaint_depth()
10248                        && new_renderer_widths.is_some_and(|new_renderer_widths| {
10249                            self.editor.update(cx, |editor, cx| {
10250                                editor.update_renderer_widths(new_renderer_widths, cx)
10251                            })
10252                        });
10253                    if renderer_widths_changed {
10254                        return self.prepaint(
10255                            None,
10256                            _inspector_id,
10257                            bounds,
10258                            request_layout,
10259                            window,
10260                            cx,
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                        if request_layout.has_remaining_prepaint_depth() {
10378                            self.editor.update(cx, |editor, cx| {
10379                                editor.resize_blocks(
10380                                    resized_blocks,
10381                                    autoscroll_request.map(|(autoscroll, _)| autoscroll),
10382                                    cx,
10383                                )
10384                            });
10385                            return self.prepaint(
10386                                None,
10387                                _inspector_id,
10388                                bounds,
10389                                request_layout,
10390                                window,
10391                                cx,
10392                            );
10393                        } else {
10394                            debug_panic!(
10395                                "dropping block resize because prepaint depth \
10396                                 limit was reached"
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: Rc<LineWithInvisibles>,
11273    line_number: Option<ShapedLine>,
11274    elements: SmallVec<[AnyElement; 1]>,
11275    available_text_width: Pixels,
11276    hitbox: Hitbox,
11277}
11278
11279impl EditorLayout {
11280    fn line_end_overshoot(&self) -> Pixels {
11281        0.15 * self.position_map.line_height
11282    }
11283}
11284
11285impl StickyHeaders {
11286    fn paint(
11287        &mut self,
11288        layout: &mut EditorLayout,
11289        whitespace_setting: ShowWhitespaceSetting,
11290        window: &mut Window,
11291        cx: &mut App,
11292    ) {
11293        let line_height = layout.position_map.line_height;
11294
11295        for line in self.lines.iter_mut().rev() {
11296            window.paint_layer(
11297                Bounds::new(
11298                    layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
11299                    size(line.hitbox.size.width, line_height),
11300                ),
11301                |window| {
11302                    let gutter_bounds = Bounds::new(
11303                        layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
11304                        size(layout.gutter_hitbox.size.width, line_height),
11305                    );
11306                    window.paint_quad(fill(gutter_bounds, self.gutter_background));
11307
11308                    let text_bounds = Bounds::new(
11309                        layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset),
11310                        size(line.available_text_width, line_height),
11311                    );
11312                    window.paint_quad(fill(text_bounds, self.content_background));
11313
11314                    if line.hitbox.is_hovered(window) {
11315                        let hover_overlay = cx.theme().colors().panel_overlay_hover;
11316                        window.paint_quad(fill(gutter_bounds, hover_overlay));
11317                        window.paint_quad(fill(text_bounds, hover_overlay));
11318                    }
11319
11320                    line.paint(
11321                        layout,
11322                        self.gutter_right_padding,
11323                        line.available_text_width,
11324                        layout.content_origin,
11325                        line_height,
11326                        whitespace_setting,
11327                        window,
11328                        cx,
11329                    );
11330                },
11331            );
11332
11333            window.set_cursor_style(CursorStyle::IBeam, &line.hitbox);
11334        }
11335    }
11336}
11337
11338impl StickyHeaderLine {
11339    fn new(
11340        row: DisplayRow,
11341        offset: Pixels,
11342        mut line: LineWithInvisibles,
11343        line_number: Option<ShapedLine>,
11344        line_height: Pixels,
11345        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11346        content_origin: gpui::Point<Pixels>,
11347        gutter_hitbox: &Hitbox,
11348        text_hitbox: &Hitbox,
11349        window: &mut Window,
11350        cx: &mut App,
11351    ) -> Self {
11352        let mut elements = SmallVec::<[AnyElement; 1]>::new();
11353        line.prepaint_with_custom_offset(
11354            line_height,
11355            scroll_pixel_position,
11356            content_origin,
11357            offset,
11358            &mut elements,
11359            window,
11360            cx,
11361        );
11362
11363        let hitbox_bounds = Bounds::new(
11364            gutter_hitbox.origin + point(Pixels::ZERO, offset),
11365            size(text_hitbox.right() - gutter_hitbox.left(), line_height),
11366        );
11367        let available_text_width =
11368            (hitbox_bounds.size.width - gutter_hitbox.size.width).max(Pixels::ZERO);
11369
11370        Self {
11371            row,
11372            offset,
11373            line: Rc::new(line),
11374            line_number,
11375            elements,
11376            available_text_width,
11377            hitbox: window.insert_hitbox(hitbox_bounds, HitboxBehavior::BlockMouseExceptScroll),
11378        }
11379    }
11380
11381    fn paint(
11382        &mut self,
11383        layout: &EditorLayout,
11384        gutter_right_padding: Pixels,
11385        available_text_width: Pixels,
11386        content_origin: gpui::Point<Pixels>,
11387        line_height: Pixels,
11388        whitespace_setting: ShowWhitespaceSetting,
11389        window: &mut Window,
11390        cx: &mut App,
11391    ) {
11392        window.with_content_mask(
11393            Some(ContentMask {
11394                bounds: Bounds::new(
11395                    layout.position_map.text_hitbox.bounds.origin
11396                        + point(Pixels::ZERO, self.offset),
11397                    size(available_text_width, line_height),
11398                ),
11399            }),
11400            |window| {
11401                self.line.draw_with_custom_offset(
11402                    layout,
11403                    self.row,
11404                    content_origin,
11405                    self.offset,
11406                    whitespace_setting,
11407                    &[],
11408                    window,
11409                    cx,
11410                );
11411                for element in &mut self.elements {
11412                    element.paint(window, cx);
11413                }
11414            },
11415        );
11416
11417        if let Some(line_number) = &self.line_number {
11418            let gutter_origin = layout.gutter_hitbox.origin + point(Pixels::ZERO, self.offset);
11419            let gutter_width = layout.gutter_hitbox.size.width;
11420            let origin = point(
11421                gutter_origin.x + gutter_width - gutter_right_padding - line_number.width,
11422                gutter_origin.y,
11423            );
11424            line_number
11425                .paint(origin, line_height, TextAlign::Left, None, window, cx)
11426                .log_err();
11427        }
11428    }
11429}
11430
11431#[derive(Debug)]
11432struct LineNumberSegment {
11433    shaped_line: ShapedLine,
11434    hitbox: Option<Hitbox>,
11435}
11436
11437#[derive(Debug)]
11438struct LineNumberLayout {
11439    segments: SmallVec<[LineNumberSegment; 1]>,
11440}
11441
11442struct ColoredRange<T> {
11443    start: T,
11444    end: T,
11445    color: Hsla,
11446}
11447
11448impl Along for ScrollbarAxes {
11449    type Unit = bool;
11450
11451    fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
11452        match axis {
11453            ScrollbarAxis::Horizontal => self.horizontal,
11454            ScrollbarAxis::Vertical => self.vertical,
11455        }
11456    }
11457
11458    fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
11459        match axis {
11460            ScrollbarAxis::Horizontal => ScrollbarAxes {
11461                horizontal: f(self.horizontal),
11462                vertical: self.vertical,
11463            },
11464            ScrollbarAxis::Vertical => ScrollbarAxes {
11465                horizontal: self.horizontal,
11466                vertical: f(self.vertical),
11467            },
11468        }
11469    }
11470}
11471
11472#[derive(Clone)]
11473struct EditorScrollbars {
11474    pub vertical: Option<ScrollbarLayout>,
11475    pub horizontal: Option<ScrollbarLayout>,
11476    pub visible: bool,
11477}
11478
11479impl EditorScrollbars {
11480    pub fn from_scrollbar_axes(
11481        show_scrollbar: ScrollbarAxes,
11482        layout_information: &ScrollbarLayoutInformation,
11483        content_offset: gpui::Point<Pixels>,
11484        scroll_position: gpui::Point<f64>,
11485        scrollbar_width: Pixels,
11486        right_margin: Pixels,
11487        editor_width: Pixels,
11488        show_scrollbars: bool,
11489        scrollbar_state: Option<&ActiveScrollbarState>,
11490        window: &mut Window,
11491    ) -> Self {
11492        let ScrollbarLayoutInformation {
11493            editor_bounds,
11494            scroll_range,
11495            glyph_grid_cell,
11496        } = layout_information;
11497
11498        let viewport_size = size(editor_width, editor_bounds.size.height);
11499
11500        let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
11501            ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
11502                Corner::BottomLeft,
11503                editor_bounds.bottom_left(),
11504                size(
11505                    // The horizontal viewport size differs from the space available for the
11506                    // horizontal scrollbar, so we have to manually stitch it together here.
11507                    editor_bounds.size.width - right_margin,
11508                    scrollbar_width,
11509                ),
11510            ),
11511            ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
11512                Corner::TopRight,
11513                editor_bounds.top_right(),
11514                size(scrollbar_width, viewport_size.height),
11515            ),
11516        };
11517
11518        let mut create_scrollbar_layout = |axis| {
11519            let viewport_size = viewport_size.along(axis);
11520            let scroll_range = scroll_range.along(axis);
11521
11522            // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
11523            (show_scrollbar.along(axis)
11524                && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
11525                .then(|| {
11526                    ScrollbarLayout::new(
11527                        window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
11528                        viewport_size,
11529                        scroll_range,
11530                        glyph_grid_cell.along(axis),
11531                        content_offset.along(axis),
11532                        scroll_position.along(axis),
11533                        show_scrollbars,
11534                        axis,
11535                    )
11536                    .with_thumb_state(
11537                        scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
11538                    )
11539                })
11540        };
11541
11542        Self {
11543            vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
11544            horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
11545            visible: show_scrollbars,
11546        }
11547    }
11548
11549    pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
11550        [
11551            (&self.vertical, ScrollbarAxis::Vertical),
11552            (&self.horizontal, ScrollbarAxis::Horizontal),
11553        ]
11554        .into_iter()
11555        .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
11556    }
11557
11558    /// Returns the currently hovered scrollbar axis, if any.
11559    pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
11560        self.iter_scrollbars()
11561            .find(|s| s.0.hitbox.is_hovered(window))
11562    }
11563}
11564
11565#[derive(Clone)]
11566struct ScrollbarLayout {
11567    hitbox: Hitbox,
11568    visible_range: Range<ScrollOffset>,
11569    text_unit_size: Pixels,
11570    thumb_bounds: Option<Bounds<Pixels>>,
11571    thumb_state: ScrollbarThumbState,
11572}
11573
11574impl ScrollbarLayout {
11575    const BORDER_WIDTH: Pixels = px(1.0);
11576    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
11577    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
11578    const MIN_THUMB_SIZE: Pixels = px(25.0);
11579
11580    fn new(
11581        scrollbar_track_hitbox: Hitbox,
11582        viewport_size: Pixels,
11583        scroll_range: Pixels,
11584        glyph_space: Pixels,
11585        content_offset: Pixels,
11586        scroll_position: ScrollOffset,
11587        show_thumb: bool,
11588        axis: ScrollbarAxis,
11589    ) -> Self {
11590        let track_bounds = scrollbar_track_hitbox.bounds;
11591        // The length of the track available to the scrollbar thumb. We deliberately
11592        // exclude the content size here so that the thumb aligns with the content.
11593        let track_length = track_bounds.size.along(axis) - content_offset;
11594
11595        Self::new_with_hitbox_and_track_length(
11596            scrollbar_track_hitbox,
11597            track_length,
11598            viewport_size,
11599            scroll_range.into(),
11600            glyph_space,
11601            content_offset.into(),
11602            scroll_position,
11603            show_thumb,
11604            axis,
11605        )
11606    }
11607
11608    fn for_minimap(
11609        minimap_track_hitbox: Hitbox,
11610        visible_lines: f64,
11611        total_editor_lines: f64,
11612        minimap_line_height: Pixels,
11613        scroll_position: ScrollOffset,
11614        minimap_scroll_top: ScrollOffset,
11615        show_thumb: bool,
11616    ) -> Self {
11617        // The scrollbar thumb size is calculated as
11618        // (visible_content/total_content) Γ— scrollbar_track_length.
11619        //
11620        // For the minimap's thumb layout, we leverage this by setting the
11621        // scrollbar track length to the entire document size (using minimap line
11622        // height). This creates a thumb that exactly represents the editor
11623        // viewport scaled to minimap proportions.
11624        //
11625        // We adjust the thumb position relative to `minimap_scroll_top` to
11626        // accommodate for the deliberately oversized track.
11627        //
11628        // This approach ensures that the minimap thumb accurately reflects the
11629        // editor's current scroll position whilst nicely synchronizing the minimap
11630        // thumb and scrollbar thumb.
11631        let scroll_range = total_editor_lines * f64::from(minimap_line_height);
11632        let viewport_size = visible_lines * f64::from(minimap_line_height);
11633
11634        let track_top_offset = -minimap_scroll_top * f64::from(minimap_line_height);
11635
11636        Self::new_with_hitbox_and_track_length(
11637            minimap_track_hitbox,
11638            Pixels::from(scroll_range),
11639            Pixels::from(viewport_size),
11640            scroll_range,
11641            minimap_line_height,
11642            track_top_offset,
11643            scroll_position,
11644            show_thumb,
11645            ScrollbarAxis::Vertical,
11646        )
11647    }
11648
11649    fn new_with_hitbox_and_track_length(
11650        scrollbar_track_hitbox: Hitbox,
11651        track_length: Pixels,
11652        viewport_size: Pixels,
11653        scroll_range: f64,
11654        glyph_space: Pixels,
11655        content_offset: ScrollOffset,
11656        scroll_position: ScrollOffset,
11657        show_thumb: bool,
11658        axis: ScrollbarAxis,
11659    ) -> Self {
11660        let text_units_per_page = viewport_size.to_f64() / glyph_space.to_f64();
11661        let visible_range = scroll_position..scroll_position + text_units_per_page;
11662        let total_text_units = scroll_range / glyph_space.to_f64();
11663
11664        let thumb_percentage = text_units_per_page / total_text_units;
11665        let thumb_size = Pixels::from(ScrollOffset::from(track_length) * thumb_percentage)
11666            .max(ScrollbarLayout::MIN_THUMB_SIZE)
11667            .min(track_length);
11668
11669        let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
11670
11671        let content_larger_than_viewport = text_unit_divisor > 0.;
11672
11673        let text_unit_size = if content_larger_than_viewport {
11674            Pixels::from(ScrollOffset::from(track_length - thumb_size) / text_unit_divisor)
11675        } else {
11676            glyph_space
11677        };
11678
11679        let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
11680            Self::thumb_bounds(
11681                &scrollbar_track_hitbox,
11682                content_offset,
11683                visible_range.start,
11684                text_unit_size,
11685                thumb_size,
11686                axis,
11687            )
11688        });
11689
11690        ScrollbarLayout {
11691            hitbox: scrollbar_track_hitbox,
11692            visible_range,
11693            text_unit_size,
11694            thumb_bounds,
11695            thumb_state: Default::default(),
11696        }
11697    }
11698
11699    fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
11700        if let Some(thumb_state) = thumb_state {
11701            Self {
11702                thumb_state,
11703                ..self
11704            }
11705        } else {
11706            self
11707        }
11708    }
11709
11710    fn thumb_bounds(
11711        scrollbar_track: &Hitbox,
11712        content_offset: f64,
11713        visible_range_start: f64,
11714        text_unit_size: Pixels,
11715        thumb_size: Pixels,
11716        axis: ScrollbarAxis,
11717    ) -> Bounds<Pixels> {
11718        let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
11719            origin
11720                + Pixels::from(
11721                    content_offset + visible_range_start * ScrollOffset::from(text_unit_size),
11722                )
11723        });
11724        Bounds::new(
11725            thumb_origin,
11726            scrollbar_track.size.apply_along(axis, |_| thumb_size),
11727        )
11728    }
11729
11730    fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
11731        self.thumb_bounds
11732            .is_some_and(|bounds| bounds.contains(position))
11733    }
11734
11735    fn marker_quads_for_ranges(
11736        &self,
11737        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
11738        column: Option<usize>,
11739    ) -> Vec<PaintQuad> {
11740        struct MinMax {
11741            min: Pixels,
11742            max: Pixels,
11743        }
11744        let (x_range, height_limit) = if let Some(column) = column {
11745            let column_width = ((self.hitbox.size.width - Self::BORDER_WIDTH) / 3.0).floor();
11746            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
11747            let end = start + column_width;
11748            (
11749                Range { start, end },
11750                MinMax {
11751                    min: Self::MIN_MARKER_HEIGHT,
11752                    max: px(f32::MAX),
11753                },
11754            )
11755        } else {
11756            (
11757                Range {
11758                    start: Self::BORDER_WIDTH,
11759                    end: self.hitbox.size.width,
11760                },
11761                MinMax {
11762                    min: Self::LINE_MARKER_HEIGHT,
11763                    max: Self::LINE_MARKER_HEIGHT,
11764                },
11765            )
11766        };
11767
11768        let row_to_y = |row: DisplayRow| row.as_f64() as f32 * self.text_unit_size;
11769        let mut pixel_ranges = row_ranges
11770            .into_iter()
11771            .map(|range| {
11772                let start_y = row_to_y(range.start);
11773                let end_y = row_to_y(range.end)
11774                    + self
11775                        .text_unit_size
11776                        .max(height_limit.min)
11777                        .min(height_limit.max);
11778                ColoredRange {
11779                    start: start_y,
11780                    end: end_y,
11781                    color: range.color,
11782                }
11783            })
11784            .peekable();
11785
11786        let mut quads = Vec::new();
11787        while let Some(mut pixel_range) = pixel_ranges.next() {
11788            while let Some(next_pixel_range) = pixel_ranges.peek() {
11789                if pixel_range.end >= next_pixel_range.start - px(1.0)
11790                    && pixel_range.color == next_pixel_range.color
11791                {
11792                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
11793                    pixel_ranges.next();
11794                } else {
11795                    break;
11796                }
11797            }
11798
11799            let bounds = Bounds::from_corners(
11800                point(x_range.start, pixel_range.start),
11801                point(x_range.end, pixel_range.end),
11802            );
11803            quads.push(quad(
11804                bounds,
11805                Corners::default(),
11806                pixel_range.color,
11807                Edges::default(),
11808                Hsla::transparent_black(),
11809                BorderStyle::default(),
11810            ));
11811        }
11812
11813        quads
11814    }
11815}
11816
11817struct MinimapLayout {
11818    pub minimap: AnyElement,
11819    pub thumb_layout: ScrollbarLayout,
11820    pub minimap_scroll_top: ScrollOffset,
11821    pub minimap_line_height: Pixels,
11822    pub thumb_border_style: MinimapThumbBorder,
11823    pub max_scroll_top: ScrollOffset,
11824}
11825
11826impl MinimapLayout {
11827    /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
11828    const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
11829    /// The minimap width as a percentage of the editor width.
11830    const MINIMAP_WIDTH_PCT: f32 = 0.15;
11831    /// Calculates the scroll top offset the minimap editor has to have based on the
11832    /// current scroll progress.
11833    fn calculate_minimap_top_offset(
11834        document_lines: f64,
11835        visible_editor_lines: f64,
11836        visible_minimap_lines: f64,
11837        scroll_position: f64,
11838    ) -> ScrollOffset {
11839        let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
11840        if non_visible_document_lines == 0. {
11841            0.
11842        } else {
11843            let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
11844            scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
11845        }
11846    }
11847}
11848
11849struct CreaseTrailerLayout {
11850    element: AnyElement,
11851    bounds: Bounds<Pixels>,
11852}
11853
11854pub(crate) struct PositionMap {
11855    pub size: Size<Pixels>,
11856    pub line_height: Pixels,
11857    pub scroll_position: gpui::Point<ScrollOffset>,
11858    pub scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11859    pub scroll_max: gpui::Point<ScrollOffset>,
11860    pub em_width: Pixels,
11861    pub em_advance: Pixels,
11862    pub em_layout_width: Pixels,
11863    pub visible_row_range: Range<DisplayRow>,
11864    pub line_layouts: Vec<LineWithInvisibles>,
11865    pub snapshot: EditorSnapshot,
11866    pub text_align: TextAlign,
11867    pub content_width: Pixels,
11868    pub text_hitbox: Hitbox,
11869    pub gutter_hitbox: Hitbox,
11870    pub inline_blame_bounds: Option<(Bounds<Pixels>, BufferId, BlameEntry)>,
11871    pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
11872    pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
11873}
11874
11875#[derive(Debug, Copy, Clone)]
11876pub struct PointForPosition {
11877    pub previous_valid: DisplayPoint,
11878    pub next_valid: DisplayPoint,
11879    pub exact_unclipped: DisplayPoint,
11880    pub column_overshoot_after_line_end: u32,
11881}
11882
11883impl PointForPosition {
11884    pub fn as_valid(&self) -> Option<DisplayPoint> {
11885        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
11886            Some(self.previous_valid)
11887        } else {
11888            None
11889        }
11890    }
11891
11892    pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
11893        let Some(valid_point) = self.as_valid() else {
11894            return false;
11895        };
11896        let range = selection.range();
11897
11898        let candidate_row = valid_point.row();
11899        let candidate_col = valid_point.column();
11900
11901        let start_row = range.start.row();
11902        let start_col = range.start.column();
11903        let end_row = range.end.row();
11904        let end_col = range.end.column();
11905
11906        if candidate_row < start_row || candidate_row > end_row {
11907            false
11908        } else if start_row == end_row {
11909            candidate_col >= start_col && candidate_col < end_col
11910        } else if candidate_row == start_row {
11911            candidate_col >= start_col
11912        } else if candidate_row == end_row {
11913            candidate_col < end_col
11914        } else {
11915            true
11916        }
11917    }
11918}
11919
11920impl PositionMap {
11921    pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
11922        let text_bounds = self.text_hitbox.bounds;
11923        let scroll_position = self.snapshot.scroll_position();
11924        let position = position - text_bounds.origin;
11925        let y = position.y.max(px(0.)).min(self.size.height);
11926        let x = position.x + (scroll_position.x as f32 * self.em_layout_width);
11927        let row = ((y / self.line_height) as f64 + scroll_position.y) as u32;
11928
11929        let (column, x_overshoot_after_line_end) = if let Some(line) = self
11930            .line_layouts
11931            .get(row as usize - scroll_position.y as usize)
11932        {
11933            let alignment_offset = line.alignment_offset(self.text_align, self.content_width);
11934            let x_relative_to_text = x - alignment_offset;
11935            if let Some(ix) = line.index_for_x(x_relative_to_text) {
11936                (ix as u32, px(0.))
11937            } else {
11938                (line.len as u32, px(0.).max(x_relative_to_text - line.width))
11939            }
11940        } else {
11941            (0, x)
11942        };
11943
11944        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
11945        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
11946        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
11947
11948        let column_overshoot_after_line_end =
11949            (x_overshoot_after_line_end / self.em_layout_width) as u32;
11950        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
11951        PointForPosition {
11952            previous_valid,
11953            next_valid,
11954            exact_unclipped,
11955            column_overshoot_after_line_end,
11956        }
11957    }
11958
11959    fn point_for_position_on_line(
11960        &self,
11961        position: gpui::Point<Pixels>,
11962        row: DisplayRow,
11963        line: &LineWithInvisibles,
11964    ) -> PointForPosition {
11965        let text_bounds = self.text_hitbox.bounds;
11966        let scroll_position = self.snapshot.scroll_position();
11967        let position = position - text_bounds.origin;
11968        let x = position.x + (scroll_position.x as f32 * self.em_layout_width);
11969
11970        let alignment_offset = line.alignment_offset(self.text_align, self.content_width);
11971        let x_relative_to_text = x - alignment_offset;
11972        let (column, x_overshoot_after_line_end) =
11973            if let Some(ix) = line.index_for_x(x_relative_to_text) {
11974                (ix as u32, px(0.))
11975            } else {
11976                (line.len as u32, px(0.).max(x_relative_to_text - line.width))
11977            };
11978
11979        let mut exact_unclipped = DisplayPoint::new(row, column);
11980        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
11981        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
11982
11983        let column_overshoot_after_line_end =
11984            (x_overshoot_after_line_end / self.em_layout_width) as u32;
11985        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
11986        PointForPosition {
11987            previous_valid,
11988            next_valid,
11989            exact_unclipped,
11990            column_overshoot_after_line_end,
11991        }
11992    }
11993}
11994
11995pub(crate) struct BlockLayout {
11996    pub(crate) id: BlockId,
11997    pub(crate) x_offset: Pixels,
11998    pub(crate) row: Option<DisplayRow>,
11999    pub(crate) element: AnyElement,
12000    pub(crate) available_space: Size<AvailableSpace>,
12001    pub(crate) style: BlockStyle,
12002    pub(crate) overlaps_gutter: bool,
12003    pub(crate) is_buffer_header: bool,
12004}
12005
12006pub fn layout_line(
12007    row: DisplayRow,
12008    snapshot: &EditorSnapshot,
12009    style: &EditorStyle,
12010    text_width: Pixels,
12011    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
12012    window: &mut Window,
12013    cx: &mut App,
12014) -> LineWithInvisibles {
12015    let use_tree_sitter =
12016        !snapshot.semantic_tokens_enabled || snapshot.use_tree_sitter_for_syntax(row, cx);
12017    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), use_tree_sitter, style);
12018    LineWithInvisibles::from_chunks(
12019        chunks,
12020        style,
12021        MAX_LINE_LEN,
12022        1,
12023        &snapshot.mode,
12024        text_width,
12025        is_row_soft_wrapped,
12026        &[],
12027        window,
12028        cx,
12029    )
12030    .pop()
12031    .unwrap()
12032}
12033
12034#[derive(Debug, Clone)]
12035pub struct IndentGuideLayout {
12036    origin: gpui::Point<Pixels>,
12037    length: Pixels,
12038    single_indent_width: Pixels,
12039    display_row_range: Range<DisplayRow>,
12040    depth: u32,
12041    active: bool,
12042    settings: IndentGuideSettings,
12043}
12044
12045pub struct CursorLayout {
12046    origin: gpui::Point<Pixels>,
12047    block_width: Pixels,
12048    line_height: Pixels,
12049    color: Hsla,
12050    shape: CursorShape,
12051    block_text: Option<ShapedLine>,
12052    cursor_name: Option<AnyElement>,
12053}
12054
12055#[derive(Debug)]
12056pub struct CursorName {
12057    string: SharedString,
12058    color: Hsla,
12059    is_top_row: bool,
12060}
12061
12062impl CursorLayout {
12063    pub fn new(
12064        origin: gpui::Point<Pixels>,
12065        block_width: Pixels,
12066        line_height: Pixels,
12067        color: Hsla,
12068        shape: CursorShape,
12069        block_text: Option<ShapedLine>,
12070    ) -> CursorLayout {
12071        CursorLayout {
12072            origin,
12073            block_width,
12074            line_height,
12075            color,
12076            shape,
12077            block_text,
12078            cursor_name: None,
12079        }
12080    }
12081
12082    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
12083        Bounds {
12084            origin: self.origin + origin,
12085            size: size(self.block_width, self.line_height),
12086        }
12087    }
12088
12089    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
12090        match self.shape {
12091            CursorShape::Bar => Bounds {
12092                origin: self.origin + origin,
12093                size: size(px(2.0), self.line_height),
12094            },
12095            CursorShape::Block | CursorShape::Hollow => Bounds {
12096                origin: self.origin + origin,
12097                size: size(self.block_width, self.line_height),
12098            },
12099            CursorShape::Underline => Bounds {
12100                origin: self.origin
12101                    + origin
12102                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
12103                size: size(self.block_width, px(2.0)),
12104            },
12105        }
12106    }
12107
12108    pub fn layout(
12109        &mut self,
12110        origin: gpui::Point<Pixels>,
12111        cursor_name: Option<CursorName>,
12112        window: &mut Window,
12113        cx: &mut App,
12114    ) {
12115        if let Some(cursor_name) = cursor_name {
12116            let bounds = self.bounds(origin);
12117            let text_size = self.line_height / 1.5;
12118
12119            let name_origin = if cursor_name.is_top_row {
12120                point(bounds.right() - px(1.), bounds.top())
12121            } else {
12122                match self.shape {
12123                    CursorShape::Bar => point(
12124                        bounds.right() - px(2.),
12125                        bounds.top() - text_size / 2. - px(1.),
12126                    ),
12127                    _ => point(
12128                        bounds.right() - px(1.),
12129                        bounds.top() - text_size / 2. - px(1.),
12130                    ),
12131                }
12132            };
12133            let mut name_element = div()
12134                .bg(self.color)
12135                .text_size(text_size)
12136                .px_0p5()
12137                .line_height(text_size + px(2.))
12138                .text_color(cursor_name.color)
12139                .child(cursor_name.string)
12140                .into_any_element();
12141
12142            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
12143
12144            self.cursor_name = Some(name_element);
12145        }
12146    }
12147
12148    pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
12149        let bounds = self.bounds(origin);
12150
12151        //Draw background or border quad
12152        let cursor = if matches!(self.shape, CursorShape::Hollow) {
12153            outline(bounds, self.color, BorderStyle::Solid)
12154        } else {
12155            fill(bounds, self.color)
12156        };
12157
12158        if let Some(name) = &mut self.cursor_name {
12159            name.paint(window, cx);
12160        }
12161
12162        window.paint_quad(cursor);
12163
12164        if let Some(block_text) = &self.block_text {
12165            block_text
12166                .paint(
12167                    self.origin + origin,
12168                    self.line_height,
12169                    TextAlign::Left,
12170                    None,
12171                    window,
12172                    cx,
12173                )
12174                .log_err();
12175        }
12176    }
12177
12178    pub fn shape(&self) -> CursorShape {
12179        self.shape
12180    }
12181}
12182
12183#[derive(Debug)]
12184pub struct HighlightedRange {
12185    pub start_y: Pixels,
12186    pub line_height: Pixels,
12187    pub lines: Vec<HighlightedRangeLine>,
12188    pub color: Hsla,
12189    pub corner_radius: Pixels,
12190}
12191
12192#[derive(Debug)]
12193pub struct HighlightedRangeLine {
12194    pub start_x: Pixels,
12195    pub end_x: Pixels,
12196}
12197
12198impl HighlightedRange {
12199    pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
12200        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
12201            self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
12202            self.paint_lines(
12203                self.start_y + self.line_height,
12204                &self.lines[1..],
12205                fill,
12206                bounds,
12207                window,
12208            );
12209        } else {
12210            self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
12211        }
12212    }
12213
12214    fn paint_lines(
12215        &self,
12216        start_y: Pixels,
12217        lines: &[HighlightedRangeLine],
12218        fill: bool,
12219        _bounds: Bounds<Pixels>,
12220        window: &mut Window,
12221    ) {
12222        if lines.is_empty() {
12223            return;
12224        }
12225
12226        let first_line = lines.first().unwrap();
12227        let last_line = lines.last().unwrap();
12228
12229        let first_top_left = point(first_line.start_x, start_y);
12230        let first_top_right = point(first_line.end_x, start_y);
12231
12232        let curve_height = point(Pixels::ZERO, self.corner_radius);
12233        let curve_width = |start_x: Pixels, end_x: Pixels| {
12234            let max = (end_x - start_x) / 2.;
12235            let width = if max < self.corner_radius {
12236                max
12237            } else {
12238                self.corner_radius
12239            };
12240
12241            point(width, Pixels::ZERO)
12242        };
12243
12244        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
12245        let mut builder = if fill {
12246            gpui::PathBuilder::fill()
12247        } else {
12248            gpui::PathBuilder::stroke(px(1.))
12249        };
12250        builder.move_to(first_top_right - top_curve_width);
12251        builder.curve_to(first_top_right + curve_height, first_top_right);
12252
12253        let mut iter = lines.iter().enumerate().peekable();
12254        while let Some((ix, line)) = iter.next() {
12255            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
12256
12257            if let Some((_, next_line)) = iter.peek() {
12258                let next_top_right = point(next_line.end_x, bottom_right.y);
12259
12260                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
12261                    Ordering::Equal => {
12262                        builder.line_to(bottom_right);
12263                    }
12264                    Ordering::Less => {
12265                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
12266                        builder.line_to(bottom_right - curve_height);
12267                        if self.corner_radius > Pixels::ZERO {
12268                            builder.curve_to(bottom_right - curve_width, bottom_right);
12269                        }
12270                        builder.line_to(next_top_right + curve_width);
12271                        if self.corner_radius > Pixels::ZERO {
12272                            builder.curve_to(next_top_right + curve_height, next_top_right);
12273                        }
12274                    }
12275                    Ordering::Greater => {
12276                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
12277                        builder.line_to(bottom_right - curve_height);
12278                        if self.corner_radius > Pixels::ZERO {
12279                            builder.curve_to(bottom_right + curve_width, bottom_right);
12280                        }
12281                        builder.line_to(next_top_right - curve_width);
12282                        if self.corner_radius > Pixels::ZERO {
12283                            builder.curve_to(next_top_right + curve_height, next_top_right);
12284                        }
12285                    }
12286                }
12287            } else {
12288                let curve_width = curve_width(line.start_x, line.end_x);
12289                builder.line_to(bottom_right - curve_height);
12290                if self.corner_radius > Pixels::ZERO {
12291                    builder.curve_to(bottom_right - curve_width, bottom_right);
12292                }
12293
12294                let bottom_left = point(line.start_x, bottom_right.y);
12295                builder.line_to(bottom_left + curve_width);
12296                if self.corner_radius > Pixels::ZERO {
12297                    builder.curve_to(bottom_left - curve_height, bottom_left);
12298                }
12299            }
12300        }
12301
12302        if first_line.start_x > last_line.start_x {
12303            let curve_width = curve_width(last_line.start_x, first_line.start_x);
12304            let second_top_left = point(last_line.start_x, start_y + self.line_height);
12305            builder.line_to(second_top_left + curve_height);
12306            if self.corner_radius > Pixels::ZERO {
12307                builder.curve_to(second_top_left + curve_width, second_top_left);
12308            }
12309            let first_bottom_left = point(first_line.start_x, second_top_left.y);
12310            builder.line_to(first_bottom_left - curve_width);
12311            if self.corner_radius > Pixels::ZERO {
12312                builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
12313            }
12314        }
12315
12316        builder.line_to(first_top_left + curve_height);
12317        if self.corner_radius > Pixels::ZERO {
12318            builder.curve_to(first_top_left + top_curve_width, first_top_left);
12319        }
12320        builder.line_to(first_top_right - top_curve_width);
12321
12322        if let Ok(path) = builder.build() {
12323            window.paint_path(path, self.color);
12324        }
12325    }
12326}
12327
12328pub(crate) struct StickyHeader {
12329    pub sticky_row: DisplayRow,
12330    pub start_point: Point,
12331    pub offset: ScrollOffset,
12332}
12333
12334enum CursorPopoverType {
12335    CodeContextMenu,
12336    EditPrediction,
12337}
12338
12339pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12340    (delta.pow(1.2) / 100.0).min(px(3.0)).into()
12341}
12342
12343fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12344    (delta.pow(1.2) / 300.0).into()
12345}
12346
12347pub fn register_action<T: Action>(
12348    editor: &Entity<Editor>,
12349    window: &mut Window,
12350    listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
12351) {
12352    let editor = editor.clone();
12353    window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
12354        let action = action.downcast_ref().unwrap();
12355        if phase == DispatchPhase::Bubble {
12356            editor.update(cx, |editor, cx| {
12357                listener(editor, action, window, cx);
12358            })
12359        }
12360    })
12361}
12362
12363/// Shared between `prepaint` and `compute_auto_height_layout` to ensure
12364/// both full and auto-height editors compute wrap widths consistently.
12365fn calculate_wrap_width(
12366    soft_wrap: SoftWrap,
12367    editor_width: Pixels,
12368    em_width: Pixels,
12369) -> Option<Pixels> {
12370    let wrap_width_for = |column: u32| (column as f32 * em_width).ceil();
12371
12372    match soft_wrap {
12373        SoftWrap::GitDiff => None,
12374        SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
12375        SoftWrap::EditorWidth => Some(editor_width),
12376        SoftWrap::Column(column) => Some(wrap_width_for(column)),
12377        SoftWrap::Bounded(column) => Some(editor_width.min(wrap_width_for(column))),
12378    }
12379}
12380
12381fn compute_auto_height_layout(
12382    editor: &mut Editor,
12383    min_lines: usize,
12384    max_lines: Option<usize>,
12385    known_dimensions: Size<Option<Pixels>>,
12386    available_width: AvailableSpace,
12387    window: &mut Window,
12388    cx: &mut Context<Editor>,
12389) -> Option<Size<Pixels>> {
12390    let width = known_dimensions.width.or({
12391        if let AvailableSpace::Definite(available_width) = available_width {
12392            Some(available_width)
12393        } else {
12394            None
12395        }
12396    })?;
12397    if let Some(height) = known_dimensions.height {
12398        return Some(size(width, height));
12399    }
12400
12401    let style = editor.style.as_ref().unwrap();
12402    let font_id = window.text_system().resolve_font(&style.text.font());
12403    let font_size = style.text.font_size.to_pixels(window.rem_size());
12404    let line_height = style.text.line_height_in_pixels(window.rem_size());
12405    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
12406
12407    let mut snapshot = editor.snapshot(window, cx);
12408    let gutter_dimensions = snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
12409
12410    editor.gutter_dimensions = gutter_dimensions;
12411    let text_width = width - gutter_dimensions.width;
12412    let overscroll = size(em_width, px(0.));
12413
12414    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
12415    let wrap_width = calculate_wrap_width(editor.soft_wrap_mode(cx), editor_width, em_width);
12416    if wrap_width.is_some() && editor.set_wrap_width(wrap_width, cx) {
12417        snapshot = editor.snapshot(window, cx);
12418    }
12419
12420    let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
12421
12422    let min_height = line_height * min_lines as f32;
12423    let content_height = scroll_height.max(min_height);
12424
12425    let final_height = if let Some(max_lines) = max_lines {
12426        let max_height = line_height * max_lines as f32;
12427        content_height.min(max_height)
12428    } else {
12429        content_height
12430    };
12431
12432    Some(size(width, final_height))
12433}
12434
12435#[cfg(test)]
12436mod tests {
12437    use super::*;
12438    use crate::{
12439        Editor, MultiBuffer, SelectionEffects,
12440        display_map::{BlockPlacement, BlockProperties},
12441        editor_tests::{init_test, update_test_language_settings},
12442    };
12443    use gpui::{TestAppContext, VisualTestContext};
12444    use language::{Buffer, language_settings, tree_sitter_python};
12445    use log::info;
12446    use rand::{RngCore, rngs::StdRng};
12447    use std::num::NonZeroU32;
12448    use util::test::sample_text;
12449
12450    #[gpui::test]
12451    async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
12452        init_test(cx, |_| {});
12453        let window = cx.add_window(|window, cx| {
12454            let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12455            let mut editor = Editor::new(
12456                EditorMode::AutoHeight {
12457                    min_lines: 1,
12458                    max_lines: None,
12459                },
12460                buffer,
12461                None,
12462                window,
12463                cx,
12464            );
12465            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12466            editor
12467        });
12468        let cx = &mut VisualTestContext::from_window(*window, cx);
12469        let editor = window.root(cx).unwrap();
12470        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12471
12472        for x in 1..=100 {
12473            let (_, state) = cx.draw(
12474                Default::default(),
12475                size(px(200. + 0.13 * x as f32), px(500.)),
12476                |_, _| EditorElement::new(&editor, style.clone()),
12477            );
12478
12479            assert!(
12480                state.position_map.scroll_max.x == 0.,
12481                "Soft wrapped editor should have no horizontal scrolling!"
12482            );
12483        }
12484    }
12485
12486    #[gpui::test]
12487    async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
12488        init_test(cx, |_| {});
12489        let window = cx.add_window(|window, cx| {
12490            let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12491            let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
12492            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12493            editor
12494        });
12495        let cx = &mut VisualTestContext::from_window(*window, cx);
12496        let editor = window.root(cx).unwrap();
12497        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12498
12499        for x in 1..=100 {
12500            let (_, state) = cx.draw(
12501                Default::default(),
12502                size(px(200. + 0.13 * x as f32), px(500.)),
12503                |_, _| EditorElement::new(&editor, style.clone()),
12504            );
12505
12506            assert!(
12507                state.position_map.scroll_max.x == 0.,
12508                "Soft wrapped editor should have no horizontal scrolling!"
12509            );
12510        }
12511    }
12512
12513    #[gpui::test]
12514    fn test_layout_line_numbers(cx: &mut TestAppContext) {
12515        init_test(cx, |_| {});
12516        let window = cx.add_window(|window, cx| {
12517            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12518            Editor::new(EditorMode::full(), buffer, None, window, cx)
12519        });
12520
12521        let editor = window.root(cx).unwrap();
12522        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12523        let line_height = window
12524            .update(cx, |_, window, _| {
12525                style.text.line_height_in_pixels(window.rem_size())
12526            })
12527            .unwrap();
12528        let element = EditorElement::new(&editor, style);
12529        let snapshot = window
12530            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12531            .unwrap();
12532
12533        let layouts = cx
12534            .update_window(*window, |_, window, cx| {
12535                element.layout_line_numbers(
12536                    None,
12537                    GutterDimensions {
12538                        left_padding: Pixels::ZERO,
12539                        right_padding: Pixels::ZERO,
12540                        width: px(30.0),
12541                        margin: Pixels::ZERO,
12542                        git_blame_entries_width: None,
12543                    },
12544                    line_height,
12545                    gpui::Point::default(),
12546                    DisplayRow(0)..DisplayRow(6),
12547                    &(0..6)
12548                        .map(|row| RowInfo {
12549                            buffer_row: Some(row),
12550                            ..Default::default()
12551                        })
12552                        .collect::<Vec<_>>(),
12553                    &BTreeMap::default(),
12554                    Some(DisplayRow(0)),
12555                    &snapshot,
12556                    window,
12557                    cx,
12558                )
12559            })
12560            .unwrap();
12561        assert_eq!(layouts.len(), 6);
12562
12563        let relative_rows = window
12564            .update(cx, |editor, window, cx| {
12565                let snapshot = editor.snapshot(window, cx);
12566                snapshot.calculate_relative_line_numbers(
12567                    &(DisplayRow(0)..DisplayRow(6)),
12568                    DisplayRow(3),
12569                    false,
12570                )
12571            })
12572            .unwrap();
12573        assert_eq!(relative_rows[&DisplayRow(0)], 3);
12574        assert_eq!(relative_rows[&DisplayRow(1)], 2);
12575        assert_eq!(relative_rows[&DisplayRow(2)], 1);
12576        // current line has no relative number
12577        assert!(!relative_rows.contains_key(&DisplayRow(3)));
12578        assert_eq!(relative_rows[&DisplayRow(4)], 1);
12579        assert_eq!(relative_rows[&DisplayRow(5)], 2);
12580
12581        // works if cursor is before screen
12582        let relative_rows = window
12583            .update(cx, |editor, window, cx| {
12584                let snapshot = editor.snapshot(window, cx);
12585                snapshot.calculate_relative_line_numbers(
12586                    &(DisplayRow(3)..DisplayRow(6)),
12587                    DisplayRow(1),
12588                    false,
12589                )
12590            })
12591            .unwrap();
12592        assert_eq!(relative_rows.len(), 3);
12593        assert_eq!(relative_rows[&DisplayRow(3)], 2);
12594        assert_eq!(relative_rows[&DisplayRow(4)], 3);
12595        assert_eq!(relative_rows[&DisplayRow(5)], 4);
12596
12597        // works if cursor is after screen
12598        let relative_rows = window
12599            .update(cx, |editor, window, cx| {
12600                let snapshot = editor.snapshot(window, cx);
12601                snapshot.calculate_relative_line_numbers(
12602                    &(DisplayRow(0)..DisplayRow(3)),
12603                    DisplayRow(6),
12604                    false,
12605                )
12606            })
12607            .unwrap();
12608        assert_eq!(relative_rows.len(), 3);
12609        assert_eq!(relative_rows[&DisplayRow(0)], 5);
12610        assert_eq!(relative_rows[&DisplayRow(1)], 4);
12611        assert_eq!(relative_rows[&DisplayRow(2)], 3);
12612
12613        const DELETED_LINE: u32 = 3;
12614        let layouts = cx
12615            .update_window(*window, |_, window, cx| {
12616                element.layout_line_numbers(
12617                    None,
12618                    GutterDimensions {
12619                        left_padding: Pixels::ZERO,
12620                        right_padding: Pixels::ZERO,
12621                        width: px(30.0),
12622                        margin: Pixels::ZERO,
12623                        git_blame_entries_width: None,
12624                    },
12625                    line_height,
12626                    gpui::Point::default(),
12627                    DisplayRow(0)..DisplayRow(6),
12628                    &(0..6)
12629                        .map(|row| RowInfo {
12630                            buffer_row: Some(row),
12631                            diff_status: (row == DELETED_LINE).then(|| {
12632                                DiffHunkStatus::deleted(
12633                                    buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12634                                )
12635                            }),
12636                            ..Default::default()
12637                        })
12638                        .collect::<Vec<_>>(),
12639                    &BTreeMap::default(),
12640                    Some(DisplayRow(0)),
12641                    &snapshot,
12642                    window,
12643                    cx,
12644                )
12645            })
12646            .unwrap();
12647        assert_eq!(layouts.len(), 5,);
12648        assert!(
12649            layouts.get(&MultiBufferRow(DELETED_LINE)).is_none(),
12650            "Deleted line should not have a line number"
12651        );
12652    }
12653
12654    #[gpui::test]
12655    async fn test_layout_line_numbers_with_folded_lines(cx: &mut TestAppContext) {
12656        init_test(cx, |_| {});
12657
12658        let python_lang = languages::language("python", tree_sitter_python::LANGUAGE.into());
12659
12660        let window = cx.add_window(|window, cx| {
12661            let buffer = cx.new(|cx| {
12662                Buffer::local(
12663                    indoc::indoc! {"
12664                        fn test() -> int {
12665                            return 2;
12666                        }
12667
12668                        fn another_test() -> int {
12669                            # This is a very peculiar method that is hard to grasp.
12670                            return 4;
12671                        }
12672                    "},
12673                    cx,
12674                )
12675                .with_language(python_lang, cx)
12676            });
12677
12678            let buffer = MultiBuffer::build_from_buffer(buffer, cx);
12679            Editor::new(EditorMode::full(), buffer, None, window, cx)
12680        });
12681
12682        let editor = window.root(cx).unwrap();
12683        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12684        let line_height = window
12685            .update(cx, |_, window, _| {
12686                style.text.line_height_in_pixels(window.rem_size())
12687            })
12688            .unwrap();
12689        let element = EditorElement::new(&editor, style);
12690        let snapshot = window
12691            .update(cx, |editor, window, cx| {
12692                editor.fold_at(MultiBufferRow(0), window, cx);
12693                editor.snapshot(window, cx)
12694            })
12695            .unwrap();
12696
12697        let layouts = cx
12698            .update_window(*window, |_, window, cx| {
12699                element.layout_line_numbers(
12700                    None,
12701                    GutterDimensions {
12702                        left_padding: Pixels::ZERO,
12703                        right_padding: Pixels::ZERO,
12704                        width: px(30.0),
12705                        margin: Pixels::ZERO,
12706                        git_blame_entries_width: None,
12707                    },
12708                    line_height,
12709                    gpui::Point::default(),
12710                    DisplayRow(0)..DisplayRow(6),
12711                    &(0..6)
12712                        .map(|row| RowInfo {
12713                            buffer_row: Some(row),
12714                            ..Default::default()
12715                        })
12716                        .collect::<Vec<_>>(),
12717                    &BTreeMap::default(),
12718                    Some(DisplayRow(3)),
12719                    &snapshot,
12720                    window,
12721                    cx,
12722                )
12723            })
12724            .unwrap();
12725        assert_eq!(layouts.len(), 6);
12726
12727        let relative_rows = window
12728            .update(cx, |editor, window, cx| {
12729                let snapshot = editor.snapshot(window, cx);
12730                snapshot.calculate_relative_line_numbers(
12731                    &(DisplayRow(0)..DisplayRow(6)),
12732                    DisplayRow(3),
12733                    false,
12734                )
12735            })
12736            .unwrap();
12737        assert_eq!(relative_rows[&DisplayRow(0)], 3);
12738        assert_eq!(relative_rows[&DisplayRow(1)], 2);
12739        assert_eq!(relative_rows[&DisplayRow(2)], 1);
12740        // current line has no relative number
12741        assert!(!relative_rows.contains_key(&DisplayRow(3)));
12742        assert_eq!(relative_rows[&DisplayRow(4)], 1);
12743        assert_eq!(relative_rows[&DisplayRow(5)], 2);
12744    }
12745
12746    #[gpui::test]
12747    fn test_layout_line_numbers_wrapping(cx: &mut TestAppContext) {
12748        init_test(cx, |_| {});
12749        let window = cx.add_window(|window, cx| {
12750            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12751            Editor::new(EditorMode::full(), buffer, None, window, cx)
12752        });
12753
12754        update_test_language_settings(cx, &|s| {
12755            s.defaults.preferred_line_length = Some(5_u32);
12756            s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
12757        });
12758
12759        let editor = window.root(cx).unwrap();
12760        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12761        let line_height = window
12762            .update(cx, |_, window, _| {
12763                style.text.line_height_in_pixels(window.rem_size())
12764            })
12765            .unwrap();
12766        let element = EditorElement::new(&editor, style);
12767        let snapshot = window
12768            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12769            .unwrap();
12770
12771        let layouts = cx
12772            .update_window(*window, |_, window, cx| {
12773                element.layout_line_numbers(
12774                    None,
12775                    GutterDimensions {
12776                        left_padding: Pixels::ZERO,
12777                        right_padding: Pixels::ZERO,
12778                        width: px(30.0),
12779                        margin: Pixels::ZERO,
12780                        git_blame_entries_width: None,
12781                    },
12782                    line_height,
12783                    gpui::Point::default(),
12784                    DisplayRow(0)..DisplayRow(6),
12785                    &(0..6)
12786                        .map(|row| RowInfo {
12787                            buffer_row: Some(row),
12788                            ..Default::default()
12789                        })
12790                        .collect::<Vec<_>>(),
12791                    &BTreeMap::default(),
12792                    Some(DisplayRow(0)),
12793                    &snapshot,
12794                    window,
12795                    cx,
12796                )
12797            })
12798            .unwrap();
12799        assert_eq!(layouts.len(), 3);
12800
12801        let relative_rows = window
12802            .update(cx, |editor, window, cx| {
12803                let snapshot = editor.snapshot(window, cx);
12804                snapshot.calculate_relative_line_numbers(
12805                    &(DisplayRow(0)..DisplayRow(6)),
12806                    DisplayRow(3),
12807                    true,
12808                )
12809            })
12810            .unwrap();
12811
12812        assert_eq!(relative_rows[&DisplayRow(0)], 3);
12813        assert_eq!(relative_rows[&DisplayRow(1)], 2);
12814        assert_eq!(relative_rows[&DisplayRow(2)], 1);
12815        // current line has no relative number
12816        assert!(!relative_rows.contains_key(&DisplayRow(3)));
12817        assert_eq!(relative_rows[&DisplayRow(4)], 1);
12818        assert_eq!(relative_rows[&DisplayRow(5)], 2);
12819
12820        let layouts = cx
12821            .update_window(*window, |_, window, cx| {
12822                element.layout_line_numbers(
12823                    None,
12824                    GutterDimensions {
12825                        left_padding: Pixels::ZERO,
12826                        right_padding: Pixels::ZERO,
12827                        width: px(30.0),
12828                        margin: Pixels::ZERO,
12829                        git_blame_entries_width: None,
12830                    },
12831                    line_height,
12832                    gpui::Point::default(),
12833                    DisplayRow(0)..DisplayRow(6),
12834                    &(0..6)
12835                        .map(|row| RowInfo {
12836                            buffer_row: Some(row),
12837                            diff_status: Some(DiffHunkStatus::deleted(
12838                                buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12839                            )),
12840                            ..Default::default()
12841                        })
12842                        .collect::<Vec<_>>(),
12843                    &BTreeMap::from_iter([(DisplayRow(0), LineHighlightSpec::default())]),
12844                    Some(DisplayRow(0)),
12845                    &snapshot,
12846                    window,
12847                    cx,
12848                )
12849            })
12850            .unwrap();
12851        assert!(
12852            layouts.is_empty(),
12853            "Deleted lines should have no line number"
12854        );
12855
12856        let relative_rows = window
12857            .update(cx, |editor, window, cx| {
12858                let snapshot = editor.snapshot(window, cx);
12859                snapshot.calculate_relative_line_numbers(
12860                    &(DisplayRow(0)..DisplayRow(6)),
12861                    DisplayRow(3),
12862                    true,
12863                )
12864            })
12865            .unwrap();
12866
12867        // Deleted lines should still have relative numbers
12868        assert_eq!(relative_rows[&DisplayRow(0)], 3);
12869        assert_eq!(relative_rows[&DisplayRow(1)], 2);
12870        assert_eq!(relative_rows[&DisplayRow(2)], 1);
12871        // current line, even if deleted, has no relative number
12872        assert!(!relative_rows.contains_key(&DisplayRow(3)));
12873        assert_eq!(relative_rows[&DisplayRow(4)], 1);
12874        assert_eq!(relative_rows[&DisplayRow(5)], 2);
12875    }
12876
12877    #[gpui::test]
12878    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
12879        init_test(cx, |_| {});
12880
12881        let window = cx.add_window(|window, cx| {
12882            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
12883            Editor::new(EditorMode::full(), buffer, None, window, cx)
12884        });
12885        let cx = &mut VisualTestContext::from_window(*window, cx);
12886        let editor = window.root(cx).unwrap();
12887        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12888
12889        window
12890            .update(cx, |editor, window, cx| {
12891                editor.cursor_offset_on_selection = true;
12892                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
12893                    s.select_ranges([
12894                        Point::new(0, 0)..Point::new(1, 0),
12895                        Point::new(3, 2)..Point::new(3, 3),
12896                        Point::new(5, 6)..Point::new(6, 0),
12897                    ]);
12898                });
12899            })
12900            .unwrap();
12901
12902        let (_, state) = cx.draw(
12903            point(px(500.), px(500.)),
12904            size(px(500.), px(500.)),
12905            |_, _| EditorElement::new(&editor, style),
12906        );
12907
12908        assert_eq!(state.selections.len(), 1);
12909        let local_selections = &state.selections[0].1;
12910        assert_eq!(local_selections.len(), 3);
12911        // moves cursor back one line
12912        assert_eq!(
12913            local_selections[0].head,
12914            DisplayPoint::new(DisplayRow(0), 6)
12915        );
12916        assert_eq!(
12917            local_selections[0].range,
12918            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
12919        );
12920
12921        // moves cursor back one column
12922        assert_eq!(
12923            local_selections[1].range,
12924            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
12925        );
12926        assert_eq!(
12927            local_selections[1].head,
12928            DisplayPoint::new(DisplayRow(3), 2)
12929        );
12930
12931        // leaves cursor on the max point
12932        assert_eq!(
12933            local_selections[2].range,
12934            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
12935        );
12936        assert_eq!(
12937            local_selections[2].head,
12938            DisplayPoint::new(DisplayRow(6), 0)
12939        );
12940
12941        // active lines does not include 1 (even though the range of the selection does)
12942        assert_eq!(
12943            state.active_rows.keys().cloned().collect::<Vec<_>>(),
12944            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
12945        );
12946    }
12947
12948    #[gpui::test]
12949    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
12950        init_test(cx, |_| {});
12951
12952        let window = cx.add_window(|window, cx| {
12953            let buffer = MultiBuffer::build_simple("", cx);
12954            Editor::new(EditorMode::full(), buffer, None, window, cx)
12955        });
12956        let cx = &mut VisualTestContext::from_window(*window, cx);
12957        let editor = window.root(cx).unwrap();
12958        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12959        window
12960            .update(cx, |editor, window, cx| {
12961                editor.set_placeholder_text("hello", window, cx);
12962                editor.insert_blocks(
12963                    [BlockProperties {
12964                        style: BlockStyle::Fixed,
12965                        placement: BlockPlacement::Above(Anchor::min()),
12966                        height: Some(3),
12967                        render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
12968                        priority: 0,
12969                    }],
12970                    None,
12971                    cx,
12972                );
12973
12974                // Blur the editor so that it displays placeholder text.
12975                window.blur();
12976            })
12977            .unwrap();
12978
12979        let (_, state) = cx.draw(
12980            point(px(500.), px(500.)),
12981            size(px(500.), px(500.)),
12982            |_, _| EditorElement::new(&editor, style),
12983        );
12984        assert_eq!(state.position_map.line_layouts.len(), 4);
12985        assert_eq!(state.line_numbers.len(), 1);
12986        assert_eq!(
12987            state
12988                .line_numbers
12989                .get(&MultiBufferRow(0))
12990                .map(|line_number| line_number
12991                    .segments
12992                    .first()
12993                    .unwrap()
12994                    .shaped_line
12995                    .text
12996                    .as_ref()),
12997            Some("1")
12998        );
12999    }
13000
13001    #[gpui::test]
13002    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
13003        const TAB_SIZE: u32 = 4;
13004
13005        let input_text = "\t \t|\t| a b";
13006        let expected_invisibles = vec![
13007            Invisible::Tab {
13008                line_start_offset: 0,
13009                line_end_offset: TAB_SIZE as usize,
13010            },
13011            Invisible::Whitespace {
13012                line_offset: TAB_SIZE as usize,
13013            },
13014            Invisible::Tab {
13015                line_start_offset: TAB_SIZE as usize + 1,
13016                line_end_offset: TAB_SIZE as usize * 2,
13017            },
13018            Invisible::Tab {
13019                line_start_offset: TAB_SIZE as usize * 2 + 1,
13020                line_end_offset: TAB_SIZE as usize * 3,
13021            },
13022            Invisible::Whitespace {
13023                line_offset: TAB_SIZE as usize * 3 + 1,
13024            },
13025            Invisible::Whitespace {
13026                line_offset: TAB_SIZE as usize * 3 + 3,
13027            },
13028        ];
13029        assert_eq!(
13030            expected_invisibles.len(),
13031            input_text
13032                .chars()
13033                .filter(|initial_char| initial_char.is_whitespace())
13034                .count(),
13035            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
13036        );
13037
13038        for show_line_numbers in [true, false] {
13039            init_test(cx, |s| {
13040                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
13041                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
13042            });
13043
13044            let actual_invisibles = collect_invisibles_from_new_editor(
13045                cx,
13046                EditorMode::full(),
13047                input_text,
13048                px(500.0),
13049                show_line_numbers,
13050            );
13051
13052            assert_eq!(expected_invisibles, actual_invisibles);
13053        }
13054    }
13055
13056    #[gpui::test]
13057    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
13058        init_test(cx, |s| {
13059            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
13060            s.defaults.tab_size = NonZeroU32::new(4);
13061        });
13062
13063        for editor_mode_without_invisibles in [
13064            EditorMode::SingleLine,
13065            EditorMode::AutoHeight {
13066                min_lines: 1,
13067                max_lines: Some(100),
13068            },
13069        ] {
13070            for show_line_numbers in [true, false] {
13071                let invisibles = collect_invisibles_from_new_editor(
13072                    cx,
13073                    editor_mode_without_invisibles.clone(),
13074                    "\t\t\t| | a b",
13075                    px(500.0),
13076                    show_line_numbers,
13077                );
13078                assert!(
13079                    invisibles.is_empty(),
13080                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
13081                );
13082            }
13083        }
13084    }
13085
13086    #[gpui::test]
13087    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
13088        let tab_size = 4;
13089        let input_text = "a\tbcd     ".repeat(9);
13090        let repeated_invisibles = [
13091            Invisible::Tab {
13092                line_start_offset: 1,
13093                line_end_offset: tab_size as usize,
13094            },
13095            Invisible::Whitespace {
13096                line_offset: tab_size as usize + 3,
13097            },
13098            Invisible::Whitespace {
13099                line_offset: tab_size as usize + 4,
13100            },
13101            Invisible::Whitespace {
13102                line_offset: tab_size as usize + 5,
13103            },
13104            Invisible::Whitespace {
13105                line_offset: tab_size as usize + 6,
13106            },
13107            Invisible::Whitespace {
13108                line_offset: tab_size as usize + 7,
13109            },
13110        ];
13111        let expected_invisibles = std::iter::once(repeated_invisibles)
13112            .cycle()
13113            .take(9)
13114            .flatten()
13115            .collect::<Vec<_>>();
13116        assert_eq!(
13117            expected_invisibles.len(),
13118            input_text
13119                .chars()
13120                .filter(|initial_char| initial_char.is_whitespace())
13121                .count(),
13122            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
13123        );
13124        info!("Expected invisibles: {expected_invisibles:?}");
13125
13126        init_test(cx, |_| {});
13127
13128        // Put the same string with repeating whitespace pattern into editors of various size,
13129        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
13130        let resize_step = 10.0;
13131        let mut editor_width = 200.0;
13132        while editor_width <= 1000.0 {
13133            for show_line_numbers in [true, false] {
13134                update_test_language_settings(cx, &|s| {
13135                    s.defaults.tab_size = NonZeroU32::new(tab_size);
13136                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
13137                    s.defaults.preferred_line_length = Some(editor_width as u32);
13138                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
13139                });
13140
13141                let actual_invisibles = collect_invisibles_from_new_editor(
13142                    cx,
13143                    EditorMode::full(),
13144                    &input_text,
13145                    px(editor_width),
13146                    show_line_numbers,
13147                );
13148
13149                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
13150                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
13151                let mut i = 0;
13152                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
13153                    i = actual_index;
13154                    match expected_invisibles.get(i) {
13155                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
13156                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
13157                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
13158                            _ => {
13159                                panic!(
13160                                    "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
13161                                )
13162                            }
13163                        },
13164                        None => {
13165                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
13166                        }
13167                    }
13168                }
13169                let missing_expected_invisibles = &expected_invisibles[i + 1..];
13170                assert!(
13171                    missing_expected_invisibles.is_empty(),
13172                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
13173                );
13174
13175                editor_width += resize_step;
13176            }
13177        }
13178    }
13179
13180    fn collect_invisibles_from_new_editor(
13181        cx: &mut TestAppContext,
13182        editor_mode: EditorMode,
13183        input_text: &str,
13184        editor_width: Pixels,
13185        show_line_numbers: bool,
13186    ) -> Vec<Invisible> {
13187        info!(
13188            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
13189            f32::from(editor_width)
13190        );
13191        let window = cx.add_window(|window, cx| {
13192            let buffer = MultiBuffer::build_simple(input_text, cx);
13193            Editor::new(editor_mode, buffer, None, window, cx)
13194        });
13195        let cx = &mut VisualTestContext::from_window(*window, cx);
13196        let editor = window.root(cx).unwrap();
13197
13198        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
13199        window
13200            .update(cx, |editor, _, cx| {
13201                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
13202                editor.set_wrap_width(Some(editor_width), cx);
13203                editor.set_show_line_numbers(show_line_numbers, cx);
13204            })
13205            .unwrap();
13206        let (_, state) = cx.draw(
13207            point(px(500.), px(500.)),
13208            size(px(500.), px(500.)),
13209            |_, _| EditorElement::new(&editor, style),
13210        );
13211        state
13212            .position_map
13213            .line_layouts
13214            .iter()
13215            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
13216            .cloned()
13217            .collect()
13218    }
13219
13220    #[gpui::test]
13221    fn test_merge_overlapping_ranges() {
13222        let base_bg = Hsla::white();
13223        let color1 = Hsla {
13224            h: 0.0,
13225            s: 0.5,
13226            l: 0.5,
13227            a: 0.5,
13228        };
13229        let color2 = Hsla {
13230            h: 120.0,
13231            s: 0.5,
13232            l: 0.5,
13233            a: 0.5,
13234        };
13235
13236        let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
13237        let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
13238            v.iter()
13239                .map(|(r, _)| (r.start.column(), r.end.column()))
13240                .collect()
13241        };
13242
13243        // Test overlapping ranges blend colors
13244        let overlapping = vec![
13245            (display_point(5)..display_point(15), color1),
13246            (display_point(10)..display_point(20), color2),
13247        ];
13248        let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
13249        assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
13250
13251        // Test middle segment should have blended color
13252        let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
13253        assert_eq!(result[1].1, blended);
13254
13255        // Test adjacent same-color ranges merge
13256        let adjacent_same = vec![
13257            (display_point(5)..display_point(10), color1),
13258            (display_point(10)..display_point(15), color1),
13259        ];
13260        let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
13261        assert_eq!(cols(&result), vec![(5, 15)]);
13262
13263        // Test contained range splits
13264        let contained = vec![
13265            (display_point(5)..display_point(20), color1),
13266            (display_point(10)..display_point(15), color2),
13267        ];
13268        let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
13269        assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
13270
13271        // Test multiple overlaps split at every boundary
13272        let color3 = Hsla {
13273            h: 240.0,
13274            s: 0.5,
13275            l: 0.5,
13276            a: 0.5,
13277        };
13278        let complex = vec![
13279            (display_point(5)..display_point(12), color1),
13280            (display_point(8)..display_point(16), color2),
13281            (display_point(10)..display_point(14), color3),
13282        ];
13283        let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
13284        assert_eq!(
13285            cols(&result),
13286            vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
13287        );
13288    }
13289
13290    #[gpui::test]
13291    fn test_bg_segments_per_row() {
13292        let base_bg = Hsla::white();
13293
13294        // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
13295        {
13296            let selection_color = Hsla {
13297                h: 200.0,
13298                s: 0.5,
13299                l: 0.5,
13300                a: 0.5,
13301            };
13302            let player_color = PlayerColor {
13303                cursor: selection_color,
13304                background: selection_color,
13305                selection: selection_color,
13306            };
13307
13308            let spanning_selection = SelectionLayout {
13309                head: DisplayPoint::new(DisplayRow(3), 7),
13310                cursor_shape: CursorShape::Bar,
13311                is_newest: true,
13312                is_local: true,
13313                range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
13314                active_rows: DisplayRow(1)..DisplayRow(4),
13315                user_name: None,
13316            };
13317
13318            let selections = vec![(player_color, vec![spanning_selection])];
13319            let result = EditorElement::bg_segments_per_row(
13320                DisplayRow(0)..DisplayRow(5),
13321                &selections,
13322                &[],
13323                base_bg,
13324            );
13325
13326            assert_eq!(result.len(), 5);
13327            assert!(result[0].is_empty());
13328            assert_eq!(result[1].len(), 1);
13329            assert_eq!(result[2].len(), 1);
13330            assert_eq!(result[3].len(), 1);
13331            assert!(result[4].is_empty());
13332
13333            assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13334            assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13335            assert_eq!(result[1][0].0.end.column(), u32::MAX);
13336            assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13337            assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13338            assert_eq!(result[2][0].0.end.column(), u32::MAX);
13339            assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
13340            assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
13341        }
13342
13343        // Case B: selection ends exactly at the start of row 3, excluding row 3
13344        {
13345            let selection_color = Hsla {
13346                h: 120.0,
13347                s: 0.5,
13348                l: 0.5,
13349                a: 0.5,
13350            };
13351            let player_color = PlayerColor {
13352                cursor: selection_color,
13353                background: selection_color,
13354                selection: selection_color,
13355            };
13356
13357            let selection = SelectionLayout {
13358                head: DisplayPoint::new(DisplayRow(2), 0),
13359                cursor_shape: CursorShape::Bar,
13360                is_newest: true,
13361                is_local: true,
13362                range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
13363                active_rows: DisplayRow(1)..DisplayRow(3),
13364                user_name: None,
13365            };
13366
13367            let selections = vec![(player_color, vec![selection])];
13368            let result = EditorElement::bg_segments_per_row(
13369                DisplayRow(0)..DisplayRow(4),
13370                &selections,
13371                &[],
13372                base_bg,
13373            );
13374
13375            assert_eq!(result.len(), 4);
13376            assert!(result[0].is_empty());
13377            assert_eq!(result[1].len(), 1);
13378            assert_eq!(result[2].len(), 1);
13379            assert!(result[3].is_empty());
13380
13381            assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13382            assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13383            assert_eq!(result[1][0].0.end.column(), u32::MAX);
13384            assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13385            assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13386            assert_eq!(result[2][0].0.end.column(), u32::MAX);
13387        }
13388    }
13389
13390    #[cfg(test)]
13391    fn generate_test_run(len: usize, color: Hsla) -> TextRun {
13392        TextRun {
13393            len,
13394            color,
13395            ..Default::default()
13396        }
13397    }
13398
13399    #[gpui::test]
13400    fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
13401        init_test(cx, |_| {});
13402
13403        let dx = |start: u32, end: u32| {
13404            DisplayPoint::new(DisplayRow(0), start)..DisplayPoint::new(DisplayRow(0), end)
13405        };
13406
13407        let text_color = Hsla {
13408            h: 210.0,
13409            s: 0.1,
13410            l: 0.4,
13411            a: 1.0,
13412        };
13413        let bg_1 = Hsla {
13414            h: 30.0,
13415            s: 0.6,
13416            l: 0.8,
13417            a: 1.0,
13418        };
13419        let bg_2 = Hsla {
13420            h: 200.0,
13421            s: 0.6,
13422            l: 0.2,
13423            a: 1.0,
13424        };
13425        let min_contrast = 45.0;
13426        let adjusted_bg1 = ensure_minimum_contrast(text_color, bg_1, min_contrast);
13427        let adjusted_bg2 = ensure_minimum_contrast(text_color, bg_2, min_contrast);
13428
13429        // Case A: single run; disjoint segments inside the run
13430        {
13431            let runs = vec![generate_test_run(20, text_color)];
13432            let segs = vec![(dx(5, 10), bg_1), (dx(12, 16), bg_2)];
13433            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13434            // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
13435            assert_eq!(
13436                out.iter().map(|r| r.len).collect::<Vec<_>>(),
13437                vec![5, 5, 2, 4, 4]
13438            );
13439            assert_eq!(out[0].color, text_color);
13440            assert_eq!(out[1].color, adjusted_bg1);
13441            assert_eq!(out[2].color, text_color);
13442            assert_eq!(out[3].color, adjusted_bg2);
13443            assert_eq!(out[4].color, text_color);
13444        }
13445
13446        // Case B: multiple runs; segment extends to end of line (u32::MAX)
13447        {
13448            let runs = vec![
13449                generate_test_run(8, text_color),
13450                generate_test_run(7, text_color),
13451            ];
13452            let segs = vec![(dx(6, u32::MAX), bg_1)];
13453            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13454            // Expected slices across runs: [0,6) [6,8) | [0,7)
13455            assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
13456            assert_eq!(out[0].color, text_color);
13457            assert_eq!(out[1].color, adjusted_bg1);
13458            assert_eq!(out[2].color, adjusted_bg1);
13459        }
13460
13461        // Case C: multi-byte characters
13462        {
13463            // for text: "Hello 🌍 δΈ–η•Œ!"
13464            let runs = vec![
13465                generate_test_run(5, text_color), // "Hello"
13466                generate_test_run(6, text_color), // " 🌍 "
13467                generate_test_run(6, text_color), // "δΈ–η•Œ"
13468                generate_test_run(1, text_color), // "!"
13469            ];
13470            // selecting "🌍 δΈ–"
13471            let segs = vec![(dx(6, 14), bg_1)];
13472            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13473            // "Hello" | " " | "🌍 " | "δΈ–" | "η•Œ" | "!"
13474            assert_eq!(
13475                out.iter().map(|r| r.len).collect::<Vec<_>>(),
13476                vec![5, 1, 5, 3, 3, 1]
13477            );
13478            assert_eq!(out[0].color, text_color); // "Hello"
13479            assert_eq!(out[2].color, adjusted_bg1); // "🌍 "
13480            assert_eq!(out[3].color, adjusted_bg1); // "δΈ–"
13481            assert_eq!(out[4].color, text_color); // "η•Œ"
13482            assert_eq!(out[5].color, text_color); // "!"
13483        }
13484
13485        // Case D: split multiple consecutive text runs with segments
13486        {
13487            let segs = vec![
13488                (dx(2, 4), bg_1),   // selecting "cd"
13489                (dx(4, 8), bg_2),   // selecting "efgh"
13490                (dx(9, 11), bg_1),  // selecting "jk"
13491                (dx(12, 16), bg_2), // selecting "mnop"
13492                (dx(18, 19), bg_1), // selecting "s"
13493            ];
13494
13495            // for text: "abcdef"
13496            let runs = vec![
13497                generate_test_run(2, text_color), // ab
13498                generate_test_run(4, text_color), // cdef
13499            ];
13500            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13501            // new splits "ab", "cd", "ef"
13502            assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![2, 2, 2]);
13503            assert_eq!(out[0].color, text_color);
13504            assert_eq!(out[1].color, adjusted_bg1);
13505            assert_eq!(out[2].color, adjusted_bg2);
13506
13507            // for text: "ghijklmn"
13508            let runs = vec![
13509                generate_test_run(3, text_color), // ghi
13510                generate_test_run(2, text_color), // jk
13511                generate_test_run(3, text_color), // lmn
13512            ];
13513            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 6); // 2 + 4 from first run
13514            // new splits "gh", "i", "jk", "l", "mn"
13515            assert_eq!(
13516                out.iter().map(|r| r.len).collect::<Vec<_>>(),
13517                vec![2, 1, 2, 1, 2]
13518            );
13519            assert_eq!(out[0].color, adjusted_bg2);
13520            assert_eq!(out[1].color, text_color);
13521            assert_eq!(out[2].color, adjusted_bg1);
13522            assert_eq!(out[3].color, text_color);
13523            assert_eq!(out[4].color, adjusted_bg2);
13524
13525            // for text: "opqrs"
13526            let runs = vec![
13527                generate_test_run(1, text_color), // o
13528                generate_test_run(4, text_color), // pqrs
13529            ];
13530            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 14); // 6 + 3 + 2 + 3 from first two runs
13531            // new splits "o", "p", "qr", "s"
13532            assert_eq!(
13533                out.iter().map(|r| r.len).collect::<Vec<_>>(),
13534                vec![1, 1, 2, 1]
13535            );
13536            assert_eq!(out[0].color, adjusted_bg2);
13537            assert_eq!(out[1].color, adjusted_bg2);
13538            assert_eq!(out[2].color, text_color);
13539            assert_eq!(out[3].color, adjusted_bg1);
13540        }
13541    }
13542
13543    #[test]
13544    fn test_spacer_pattern_period() {
13545        // line height is smaller than target height, so we just return half the line height
13546        assert_eq!(EditorElement::spacer_pattern_period(10.0, 20.0), 5.0);
13547
13548        // line height is exactly half the target height, perfect match
13549        assert_eq!(EditorElement::spacer_pattern_period(20.0, 10.0), 10.0);
13550
13551        // line height is close to half the target height
13552        assert_eq!(EditorElement::spacer_pattern_period(20.0, 9.0), 10.0);
13553
13554        // line height is close to 1/4 the target height
13555        assert_eq!(EditorElement::spacer_pattern_period(20.0, 4.8), 5.0);
13556    }
13557
13558    #[gpui::test(iterations = 100)]
13559    fn test_random_spacer_pattern_period(mut rng: StdRng) {
13560        let line_height = rng.next_u32() as f32;
13561        let target_height = rng.next_u32() as f32;
13562
13563        let result = EditorElement::spacer_pattern_period(line_height, target_height);
13564
13565        let k = line_height / result;
13566        assert!(k - k.round() < 0.0000001); // approximately integer
13567        assert!((k.round() as u32).is_multiple_of(2));
13568    }
13569
13570    #[test]
13571    fn test_calculate_wrap_width() {
13572        let editor_width = px(800.0);
13573        let em_width = px(8.0);
13574
13575        assert_eq!(
13576            calculate_wrap_width(SoftWrap::GitDiff, editor_width, em_width),
13577            None,
13578        );
13579
13580        assert_eq!(
13581            calculate_wrap_width(SoftWrap::None, editor_width, em_width),
13582            Some(px((MAX_LINE_LEN as f32 / 2.0 * 8.0).ceil())),
13583        );
13584
13585        assert_eq!(
13586            calculate_wrap_width(SoftWrap::EditorWidth, editor_width, em_width),
13587            Some(px(800.0)),
13588        );
13589
13590        assert_eq!(
13591            calculate_wrap_width(SoftWrap::Column(72), editor_width, em_width),
13592            Some(px((72.0 * 8.0_f32).ceil())),
13593        );
13594
13595        assert_eq!(
13596            calculate_wrap_width(SoftWrap::Bounded(72), editor_width, em_width),
13597            Some(px((72.0 * 8.0_f32).ceil())),
13598        );
13599        assert_eq!(
13600            calculate_wrap_width(SoftWrap::Bounded(200), px(400.0), em_width),
13601            Some(px(400.0)),
13602        );
13603    }
13604}