element.rs

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