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