element.rs

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