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