element.rs

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