element.rs

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