element.rs

    1use crate::{
    2    ActiveDiagnostic, BUFFER_HEADER_PADDING, BlockId, CURSORS_VISIBLE_FOR, ChunkRendererContext,
    3    ChunkReplacement, CodeActionSource, ColumnarMode, ConflictsOurs, ConflictsOursMarker,
    4    ConflictsOuter, ConflictsTheirs, ConflictsTheirsMarker, ContextMenuPlacement, CursorShape,
    5    CustomBlockId, DisplayDiffHunk, DisplayPoint, DisplayRow, EditDisplayMode, EditPrediction,
    6    Editor, EditorMode, EditorSettings, EditorSnapshot, EditorStyle, FILE_HEADER_HEIGHT,
    7    FocusedBlock, GutterDimensions, GutterHoverButton, HalfPageDown, HalfPageUp, HandleInput,
    8    HoveredCursor, InlayHintRefreshReason, JumpData, LineDown, LineHighlight, LineUp, MAX_LINE_LEN,
    9    MINIMAP_FONT_SIZE, MULTI_BUFFER_EXCERPT_HEADER_HEIGHT, OpenExcerpts, PageDown, PageUp,
   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, HashSet};
   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, Corners, CursorStyle, DispatchPhase,
   44    Edges, Element, ElementInputHandler, Entity, Focusable as _, Font, FontId, FontWeight,
   45    GlobalElementId, Hitbox, HitboxBehavior, Hsla, InteractiveElement, IntoElement, IsZero, Length,
   46    Modifiers, ModifiersChangedEvent, MouseButton, MouseClickEvent, MouseDownEvent, MouseMoveEvent,
   47    MousePressureEvent, MouseUpEvent, PaintQuad, ParentElement, Pixels, PressureStage, ScrollDelta,
   48    ScrollHandle, ScrollWheelEvent, ShapedLine, SharedString, Size, StatefulInteractiveElement,
   49    Style, Styled, StyledText, TextAlign, TextRun, TextStyleRefinement, WeakEntity, Window,
   50    anchored, deferred, div, fill, linear_color_stop, linear_gradient, outline, pattern_slash,
   51    point, px, quad, relative, size, solid_background, transparent_black,
   52};
   53use itertools::Itertools;
   54use language::{
   55    HighlightedText, IndentGuideSettings, LanguageAwareStyling,
   56    language_settings::ShowWhitespaceSetting,
   57};
   58use markdown::Markdown;
   59use multi_buffer::{
   60    Anchor, ExcerptBoundaryInfo, ExpandExcerptDirection, ExpandInfo, MultiBufferPoint,
   61    MultiBufferRow, RowInfo,
   62};
   63
   64use project::{
   65    DisableAiSettings, Entry,
   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, PlayerColor};
   90use theme_settings::BufferLineHeight;
   91use ui::utils::ensure_minimum_contrast;
   92use ui::{
   93    ButtonLike, ContextMenu, Indicator, KeyBinding, POPOVER_Y_PADDING, Tooltip, prelude::*,
   94    right_click_menu, scrollbars::ShowScrollbar, text_for_keystroke,
   95};
   96use unicode_segmentation::UnicodeSegmentation;
   97use util::post_inc;
   98use util::{RangeExt, ResultExt, debug_panic};
   99use workspace::{
  100    CollaboratorId, ItemHandle, ItemSettings, OpenInTerminal, OpenTerminal, RevealInProjectPanel,
  101    Workspace,
  102    item::{Item, ItemBufferKind},
  103};
  104
  105/// Determines what kinds of highlights should be applied to a lines background.
  106#[derive(Clone, Copy, Default)]
  107struct LineHighlightSpec {
  108    selection: bool,
  109    breakpoint: bool,
  110    _active_stack_frame: bool,
  111}
  112
  113#[derive(Debug)]
  114struct SelectionLayout {
  115    head: DisplayPoint,
  116    cursor_shape: CursorShape,
  117    is_newest: bool,
  118    is_local: bool,
  119    range: Range<DisplayPoint>,
  120    active_rows: Range<DisplayRow>,
  121    user_name: Option<SharedString>,
  122}
  123
  124struct InlineBlameLayout {
  125    element: AnyElement,
  126    bounds: Bounds<Pixels>,
  127    buffer_id: BufferId,
  128    entry: BlameEntry,
  129}
  130
  131impl SelectionLayout {
  132    fn new<T: ToPoint + ToDisplayPoint + Clone>(
  133        selection: Selection<T>,
  134        line_mode: bool,
  135        cursor_offset: bool,
  136        cursor_shape: CursorShape,
  137        map: &DisplaySnapshot,
  138        is_newest: bool,
  139        is_local: bool,
  140        user_name: Option<SharedString>,
  141    ) -> Self {
  142        let point_selection = selection.map(|p| p.to_point(map.buffer_snapshot()));
  143        let display_selection = point_selection.map(|p| p.to_display_point(map));
  144        let mut range = display_selection.range();
  145        let mut head = display_selection.head();
  146        let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
  147            ..map.next_line_boundary(point_selection.end).1.row();
  148
  149        // vim visual line mode
  150        if line_mode {
  151            let point_range = map.expand_to_line(point_selection.range());
  152            range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
  153        }
  154
  155        // any vim visual mode (including line mode)
  156        if cursor_offset && !range.is_empty() && !selection.reversed {
  157            if head.column() > 0 {
  158                head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left);
  159            } else if head.row().0 > 0 && head != map.max_point() {
  160                head = map.clip_point(
  161                    DisplayPoint::new(
  162                        head.row().previous_row(),
  163                        map.line_len(head.row().previous_row()),
  164                    ),
  165                    Bias::Left,
  166                );
  167                // updating range.end is a no-op unless you're cursor is
  168                // on the newline containing a multi-buffer divider
  169                // in which case the clip_point may have moved the head up
  170                // an additional row.
  171                range.end = DisplayPoint::new(head.row().next_row(), 0);
  172                active_rows.end = head.row();
  173            }
  174        }
  175
  176        Self {
  177            head,
  178            cursor_shape,
  179            is_newest,
  180            is_local,
  181            range,
  182            active_rows,
  183            user_name,
  184        }
  185    }
  186}
  187
  188#[derive(Default)]
  189struct RenderBlocksOutput {
  190    // We store spacer blocks separately because they paint in a different order
  191    // (spacers -> indent guides -> non-spacers)
  192    non_spacer_blocks: Vec<BlockLayout>,
  193    spacer_blocks: Vec<BlockLayout>,
  194    row_block_types: HashMap<DisplayRow, bool>,
  195    resized_blocks: Option<HashMap<CustomBlockId, u32>>,
  196}
  197
  198pub struct EditorElement {
  199    editor: Entity<Editor>,
  200    style: EditorStyle,
  201    split_side: Option<SplitSide>,
  202}
  203
  204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  205pub enum SplitSide {
  206    Left,
  207    Right,
  208}
  209
  210impl EditorElement {
  211    pub(crate) const SCROLLBAR_WIDTH: Pixels = px(15.);
  212
  213    pub fn new(editor: &Entity<Editor>, style: EditorStyle) -> Self {
  214        Self {
  215            editor: editor.clone(),
  216            style,
  217            split_side: None,
  218        }
  219    }
  220
  221    pub fn set_split_side(&mut self, side: SplitSide) {
  222        self.split_side = Some(side);
  223    }
  224
  225    fn should_show_buffer_headers(&self) -> bool {
  226        self.split_side.is_none()
  227    }
  228
  229    fn register_actions(&self, window: &mut Window, cx: &mut App) {
  230        let editor = &self.editor;
  231        editor.update(cx, |editor, cx| {
  232            for action in editor.editor_actions.borrow().values() {
  233                (action)(editor, window, cx)
  234            }
  235        });
  236
  237        crate::rust_analyzer_ext::apply_related_actions(editor, window, cx);
  238        crate::clangd_ext::apply_related_actions(editor, window, cx);
  239
  240        register_action(editor, window, Editor::open_context_menu);
  241        register_action(editor, window, Editor::move_left);
  242        register_action(editor, window, Editor::move_right);
  243        register_action(editor, window, Editor::move_down);
  244        register_action(editor, window, Editor::move_down_by_lines);
  245        register_action(editor, window, Editor::select_down_by_lines);
  246        register_action(editor, window, Editor::move_up);
  247        register_action(editor, window, Editor::move_up_by_lines);
  248        register_action(editor, window, Editor::select_up_by_lines);
  249        register_action(editor, window, Editor::select_page_down);
  250        register_action(editor, window, Editor::select_page_up);
  251        register_action(editor, window, Editor::cancel);
  252        register_action(editor, window, Editor::newline);
  253        register_action(editor, window, Editor::newline_above);
  254        register_action(editor, window, Editor::newline_below);
  255        register_action(editor, window, Editor::backspace);
  256        register_action(editor, window, Editor::blame_hover);
  257        register_action(editor, window, Editor::delete);
  258        register_action(editor, window, Editor::tab);
  259        register_action(editor, window, Editor::next_snippet_tabstop);
  260        register_action(editor, window, Editor::previous_snippet_tabstop);
  261        register_action(editor, window, Editor::backtab);
  262        register_action(editor, window, Editor::indent);
  263        register_action(editor, window, Editor::outdent);
  264        register_action(editor, window, Editor::autoindent);
  265        register_action(editor, window, Editor::delete_line);
  266        register_action(editor, window, Editor::join_lines);
  267        register_action(editor, window, Editor::sort_lines_by_length);
  268        register_action(editor, window, Editor::sort_lines_case_sensitive);
  269        register_action(editor, window, Editor::sort_lines_case_insensitive);
  270        register_action(editor, window, Editor::reverse_lines);
  271        register_action(editor, window, Editor::shuffle_lines);
  272        register_action(editor, window, Editor::rotate_selections_forward);
  273        register_action(editor, window, Editor::rotate_selections_backward);
  274        register_action(editor, window, Editor::convert_indentation_to_spaces);
  275        register_action(editor, window, Editor::convert_indentation_to_tabs);
  276        register_action(editor, window, Editor::convert_to_upper_case);
  277        register_action(editor, window, Editor::convert_to_lower_case);
  278        register_action(editor, window, Editor::convert_to_title_case);
  279        register_action(editor, window, Editor::convert_to_snake_case);
  280        register_action(editor, window, Editor::convert_to_kebab_case);
  281        register_action(editor, window, Editor::convert_to_upper_camel_case);
  282        register_action(editor, window, Editor::convert_to_lower_camel_case);
  283        register_action(editor, window, Editor::convert_to_opposite_case);
  284        register_action(editor, window, Editor::convert_to_sentence_case);
  285        register_action(editor, window, Editor::toggle_case);
  286        register_action(editor, window, Editor::convert_to_rot13);
  287        register_action(editor, window, Editor::convert_to_rot47);
  288        register_action(editor, window, Editor::delete_to_previous_word_start);
  289        register_action(editor, window, Editor::delete_to_previous_subword_start);
  290        register_action(editor, window, Editor::delete_to_next_word_end);
  291        register_action(editor, window, Editor::delete_to_next_subword_end);
  292        register_action(editor, window, Editor::delete_to_beginning_of_line);
  293        register_action(editor, window, Editor::delete_to_end_of_line);
  294        register_action(editor, window, Editor::cut_to_end_of_line);
  295        register_action(editor, window, Editor::duplicate_line_up);
  296        register_action(editor, window, Editor::duplicate_line_down);
  297        register_action(editor, window, Editor::duplicate_selection);
  298        register_action(editor, window, Editor::move_line_up);
  299        register_action(editor, window, Editor::move_line_down);
  300        register_action(editor, window, Editor::transpose);
  301        register_action(editor, window, Editor::rewrap);
  302        register_action(editor, window, Editor::cut);
  303        register_action(editor, window, Editor::kill_ring_cut);
  304        register_action(editor, window, Editor::kill_ring_yank);
  305        register_action(editor, window, Editor::copy);
  306        register_action(editor, window, Editor::copy_and_trim);
  307        register_action(editor, window, Editor::diff_clipboard_with_selection);
  308        register_action(editor, window, Editor::paste);
  309        register_action(editor, window, Editor::undo);
  310        register_action(editor, window, Editor::redo);
  311        register_action(editor, window, Editor::move_page_up);
  312        register_action(editor, window, Editor::move_page_down);
  313        register_action(editor, window, Editor::next_screen);
  314        register_action(editor, window, Editor::scroll_cursor_top);
  315        register_action(editor, window, Editor::scroll_cursor_center);
  316        register_action(editor, window, Editor::scroll_cursor_bottom);
  317        register_action(editor, window, Editor::scroll_cursor_center_top_bottom);
  318        register_action(editor, window, |editor, _: &LineDown, window, cx| {
  319            editor.scroll_screen(&ScrollAmount::Line(1.), window, cx)
  320        });
  321        register_action(editor, window, |editor, _: &LineUp, window, cx| {
  322            editor.scroll_screen(&ScrollAmount::Line(-1.), window, cx)
  323        });
  324        register_action(editor, window, |editor, _: &HalfPageDown, window, cx| {
  325            editor.scroll_screen(&ScrollAmount::Page(0.5), window, cx)
  326        });
  327        register_action(
  328            editor,
  329            window,
  330            |editor, HandleInput(text): &HandleInput, window, cx| {
  331                if text.is_empty() {
  332                    return;
  333                }
  334                editor.handle_input(text, window, cx);
  335            },
  336        );
  337        register_action(editor, window, |editor, _: &HalfPageUp, window, cx| {
  338            editor.scroll_screen(&ScrollAmount::Page(-0.5), window, cx)
  339        });
  340        register_action(editor, window, |editor, _: &PageDown, window, cx| {
  341            editor.scroll_screen(&ScrollAmount::Page(1.), window, cx)
  342        });
  343        register_action(editor, window, |editor, _: &PageUp, window, cx| {
  344            editor.scroll_screen(&ScrollAmount::Page(-1.), window, cx)
  345        });
  346        register_action(editor, window, Editor::move_to_previous_word_start);
  347        register_action(editor, window, Editor::move_to_previous_subword_start);
  348        register_action(editor, window, Editor::move_to_next_word_end);
  349        register_action(editor, window, Editor::move_to_next_subword_end);
  350        register_action(editor, window, Editor::move_to_beginning_of_line);
  351        register_action(editor, window, Editor::move_to_end_of_line);
  352        register_action(editor, window, Editor::move_to_start_of_paragraph);
  353        register_action(editor, window, Editor::move_to_end_of_paragraph);
  354        register_action(editor, window, Editor::move_to_beginning);
  355        register_action(editor, window, Editor::move_to_end);
  356        register_action(editor, window, Editor::move_to_start_of_excerpt);
  357        register_action(editor, window, Editor::move_to_start_of_next_excerpt);
  358        register_action(editor, window, Editor::move_to_end_of_excerpt);
  359        register_action(editor, window, Editor::move_to_end_of_previous_excerpt);
  360        register_action(editor, window, Editor::select_up);
  361        register_action(editor, window, Editor::select_down);
  362        register_action(editor, window, Editor::select_left);
  363        register_action(editor, window, Editor::select_right);
  364        register_action(editor, window, Editor::select_to_previous_word_start);
  365        register_action(editor, window, Editor::select_to_previous_subword_start);
  366        register_action(editor, window, Editor::select_to_next_word_end);
  367        register_action(editor, window, Editor::select_to_next_subword_end);
  368        register_action(editor, window, Editor::select_to_beginning_of_line);
  369        register_action(editor, window, Editor::select_to_end_of_line);
  370        register_action(editor, window, Editor::select_to_start_of_paragraph);
  371        register_action(editor, window, Editor::select_to_end_of_paragraph);
  372        register_action(editor, window, Editor::select_to_start_of_excerpt);
  373        register_action(editor, window, Editor::select_to_start_of_next_excerpt);
  374        register_action(editor, window, Editor::select_to_end_of_excerpt);
  375        register_action(editor, window, Editor::select_to_end_of_previous_excerpt);
  376        register_action(editor, window, Editor::select_to_beginning);
  377        register_action(editor, window, Editor::select_to_end);
  378        register_action(editor, window, Editor::select_all);
  379        register_action(editor, window, |editor, action, window, cx| {
  380            editor.select_all_matches(action, window, cx).log_err();
  381        });
  382        register_action(editor, window, Editor::select_line);
  383        register_action(editor, window, Editor::split_selection_into_lines);
  384        register_action(editor, window, Editor::add_selection_above);
  385        register_action(editor, window, Editor::add_selection_below);
  386        register_action(editor, window, Editor::insert_snippet_at_selections);
  387        register_action(editor, window, |editor, action, window, cx| {
  388            editor.select_next(action, window, cx).log_err();
  389        });
  390        register_action(editor, window, |editor, action, window, cx| {
  391            editor.select_previous(action, window, cx).log_err();
  392        });
  393        register_action(editor, window, |editor, action, window, cx| {
  394            editor.find_next_match(action, window, cx).log_err();
  395        });
  396        register_action(editor, window, |editor, action, window, cx| {
  397            editor.find_previous_match(action, window, cx).log_err();
  398        });
  399        register_action(editor, window, Editor::toggle_comments);
  400        register_action(editor, window, Editor::toggle_block_comments);
  401        register_action(editor, window, Editor::select_larger_syntax_node);
  402        register_action(editor, window, Editor::select_smaller_syntax_node);
  403        register_action(editor, window, Editor::select_next_syntax_node);
  404        register_action(editor, window, Editor::select_prev_syntax_node);
  405        register_action(
  406            editor,
  407            window,
  408            Editor::select_to_start_of_larger_syntax_node,
  409        );
  410        register_action(editor, window, Editor::select_to_end_of_larger_syntax_node);
  411        register_action(editor, window, Editor::unwrap_syntax_node);
  412        register_action(editor, window, Editor::move_to_start_of_larger_syntax_node);
  413        register_action(editor, window, Editor::move_to_end_of_larger_syntax_node);
  414        register_action(editor, window, Editor::select_enclosing_symbol);
  415        register_action(editor, window, Editor::move_to_enclosing_bracket);
  416        register_action(editor, window, Editor::undo_selection);
  417        register_action(editor, window, Editor::redo_selection);
  418        if editor.read(cx).buffer_kind(cx) == ItemBufferKind::Multibuffer {
  419            register_action(editor, window, Editor::expand_excerpts);
  420            register_action(editor, window, Editor::expand_excerpts_up);
  421            register_action(editor, window, Editor::expand_excerpts_down);
  422        }
  423        register_action(editor, window, Editor::go_to_diagnostic);
  424        register_action(editor, window, Editor::go_to_prev_diagnostic);
  425        register_action(editor, window, Editor::go_to_next_hunk);
  426        register_action(editor, window, Editor::go_to_prev_hunk);
  427        register_action(editor, window, Editor::go_to_next_document_highlight);
  428        register_action(editor, window, Editor::go_to_prev_document_highlight);
  429        register_action(editor, window, |editor, action, window, cx| {
  430            editor
  431                .go_to_definition(action, window, cx)
  432                .detach_and_log_err(cx);
  433        });
  434        register_action(editor, window, |editor, action, window, cx| {
  435            editor
  436                .go_to_definition_split(action, window, cx)
  437                .detach_and_log_err(cx);
  438        });
  439        register_action(editor, window, |editor, action, window, cx| {
  440            editor
  441                .go_to_declaration(action, window, cx)
  442                .detach_and_log_err(cx);
  443        });
  444        register_action(editor, window, |editor, action, window, cx| {
  445            editor
  446                .go_to_declaration_split(action, window, cx)
  447                .detach_and_log_err(cx);
  448        });
  449        register_action(editor, window, |editor, action, window, cx| {
  450            editor
  451                .go_to_implementation(action, window, cx)
  452                .detach_and_log_err(cx);
  453        });
  454        register_action(editor, window, |editor, action, window, cx| {
  455            editor
  456                .go_to_implementation_split(action, window, cx)
  457                .detach_and_log_err(cx);
  458        });
  459        register_action(editor, window, |editor, action, window, cx| {
  460            editor
  461                .go_to_type_definition(action, window, cx)
  462                .detach_and_log_err(cx);
  463        });
  464        register_action(editor, window, |editor, action, window, cx| {
  465            editor
  466                .go_to_type_definition_split(action, window, cx)
  467                .detach_and_log_err(cx);
  468        });
  469        register_action(editor, window, Editor::open_url);
  470        register_action(editor, window, Editor::open_selected_filename);
  471        register_action(editor, window, Editor::fold);
  472        register_action(editor, window, Editor::fold_at_level);
  473        register_action(editor, window, Editor::fold_at_level_1);
  474        register_action(editor, window, Editor::fold_at_level_2);
  475        register_action(editor, window, Editor::fold_at_level_3);
  476        register_action(editor, window, Editor::fold_at_level_4);
  477        register_action(editor, window, Editor::fold_at_level_5);
  478        register_action(editor, window, Editor::fold_at_level_6);
  479        register_action(editor, window, Editor::fold_at_level_7);
  480        register_action(editor, window, Editor::fold_at_level_8);
  481        register_action(editor, window, Editor::fold_at_level_9);
  482        register_action(editor, window, Editor::fold_all);
  483        register_action(editor, window, Editor::fold_function_bodies);
  484        register_action(editor, window, Editor::fold_recursive);
  485        register_action(editor, window, Editor::toggle_fold);
  486        register_action(editor, window, Editor::toggle_fold_recursive);
  487        register_action(editor, window, Editor::toggle_fold_all);
  488        register_action(editor, window, Editor::unfold_lines);
  489        register_action(editor, window, Editor::unfold_recursive);
  490        register_action(editor, window, Editor::unfold_all);
  491        register_action(editor, window, Editor::fold_selected_ranges);
  492        register_action(editor, window, Editor::set_mark);
  493        register_action(editor, window, Editor::swap_selection_ends);
  494        register_action(editor, window, Editor::show_completions);
  495        register_action(editor, window, Editor::show_word_completions);
  496        register_action(editor, window, Editor::toggle_code_actions);
  497        register_action(editor, window, Editor::open_excerpts);
  498        register_action(editor, window, Editor::open_excerpts_in_split);
  499        register_action(editor, window, Editor::toggle_soft_wrap);
  500        register_action(editor, window, Editor::toggle_tab_bar);
  501        register_action(editor, window, Editor::toggle_line_numbers);
  502        register_action(editor, window, Editor::toggle_relative_line_numbers);
  503        register_action(editor, window, Editor::toggle_indent_guides);
  504        register_action(editor, window, Editor::toggle_inlay_hints);
  505        register_action(editor, window, Editor::toggle_code_lens_action);
  506        register_action(editor, window, Editor::toggle_semantic_highlights);
  507        register_action(editor, window, Editor::toggle_edit_predictions);
  508        if editor.read(cx).diagnostics_enabled() {
  509            register_action(editor, window, Editor::toggle_diagnostics);
  510        }
  511        if editor.read(cx).inline_diagnostics_enabled() {
  512            register_action(editor, window, Editor::toggle_inline_diagnostics);
  513        }
  514        if editor.read(cx).supports_minimap(cx) {
  515            register_action(editor, window, Editor::toggle_minimap);
  516        }
  517        register_action(editor, window, hover_popover::hover);
  518        register_action(editor, window, Editor::reveal_in_finder);
  519        register_action(editor, window, Editor::copy_path);
  520        register_action(editor, window, Editor::copy_relative_path);
  521        register_action(editor, window, Editor::copy_file_name);
  522        register_action(editor, window, Editor::copy_file_name_without_extension);
  523        register_action(editor, window, Editor::copy_highlight_json);
  524        register_action(editor, window, Editor::copy_permalink_to_line);
  525        register_action(editor, window, Editor::open_permalink_to_line);
  526        register_action(editor, window, Editor::copy_file_location);
  527        register_action(editor, window, Editor::toggle_git_blame);
  528        register_action(editor, window, Editor::toggle_git_blame_inline);
  529        register_action(editor, window, Editor::open_git_blame_commit);
  530        register_action(editor, window, Editor::toggle_selected_diff_hunks);
  531        register_action(editor, window, Editor::toggle_staged_selected_diff_hunks);
  532        register_action(editor, window, Editor::stage_and_next);
  533        register_action(editor, window, Editor::unstage_and_next);
  534        register_action(editor, window, Editor::expand_all_diff_hunks);
  535        register_action(editor, window, Editor::collapse_all_diff_hunks);
  536        register_action(editor, window, Editor::toggle_review_comments_expanded);
  537        register_action(editor, window, Editor::submit_diff_review_comment_action);
  538        register_action(editor, window, Editor::edit_review_comment);
  539        register_action(editor, window, Editor::delete_review_comment);
  540        register_action(editor, window, Editor::confirm_edit_review_comment_action);
  541        register_action(editor, window, Editor::cancel_edit_review_comment_action);
  542        register_action(editor, window, Editor::go_to_previous_change);
  543        register_action(editor, window, Editor::go_to_next_change);
  544        register_action(editor, window, Editor::go_to_prev_reference);
  545        register_action(editor, window, Editor::go_to_next_reference);
  546        register_action(editor, window, Editor::go_to_previous_symbol);
  547        register_action(editor, window, Editor::go_to_next_symbol);
  548
  549        register_action(editor, window, |editor, action, window, cx| {
  550            if let Some(task) = editor.format(action, window, cx) {
  551                editor.detach_and_notify_err(task, window, cx);
  552            } else {
  553                cx.propagate();
  554            }
  555        });
  556        if editor.read(cx).can_format_selections(cx) {
  557            register_action(editor, window, |editor, action, window, cx| {
  558                if let Some(task) = editor.format_selections(action, window, cx) {
  559                    editor.detach_and_notify_err(task, window, cx);
  560                } else {
  561                    cx.propagate();
  562                }
  563            });
  564        }
  565        register_action(editor, window, |editor, action, window, cx| {
  566            if let Some(task) = editor.organize_imports(action, window, cx) {
  567                editor.detach_and_notify_err(task, window, cx);
  568            } else {
  569                cx.propagate();
  570            }
  571        });
  572        register_action(editor, window, Editor::restart_language_server);
  573        register_action(editor, window, Editor::stop_language_server);
  574        register_action(editor, window, Editor::show_character_palette);
  575        register_action(editor, window, |editor, action, window, cx| {
  576            if let Some(task) = editor.confirm_completion(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_replace(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.confirm_completion_insert(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.compose_completion(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.confirm_code_action(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.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.confirm_rename(action, window, cx) {
  619                editor.detach_and_notify_err(task, window, cx);
  620            } else {
  621                cx.propagate();
  622            }
  623        });
  624        register_action(editor, window, |editor, action, window, cx| {
  625            if let Some(task) = editor.find_all_references(action, window, cx) {
  626                task.detach_and_log_err(cx);
  627            } else {
  628                cx.propagate();
  629            }
  630        });
  631        register_action(editor, window, Editor::show_signature_help);
  632        register_action(editor, window, Editor::signature_help_prev);
  633        register_action(editor, window, Editor::signature_help_next);
  634        register_action(editor, window, Editor::show_edit_prediction);
  635        register_action(editor, window, Editor::context_menu_first);
  636        register_action(editor, window, Editor::context_menu_prev);
  637        register_action(editor, window, Editor::context_menu_next);
  638        register_action(editor, window, Editor::context_menu_last);
  639        register_action(editor, window, Editor::display_cursor_names);
  640        register_action(editor, window, Editor::unique_lines_case_insensitive);
  641        register_action(editor, window, Editor::unique_lines_case_sensitive);
  642        register_action(editor, window, Editor::accept_next_word_edit_prediction);
  643        register_action(editor, window, Editor::accept_next_line_edit_prediction);
  644        register_action(editor, window, Editor::accept_edit_prediction);
  645        register_action(editor, window, Editor::restore_file);
  646        register_action(editor, window, Editor::git_restore);
  647        register_action(editor, window, Editor::restore_and_next);
  648        register_action(editor, window, Editor::apply_all_diff_hunks);
  649        register_action(editor, window, Editor::apply_selected_diff_hunks);
  650        register_action(editor, window, Editor::open_active_item_in_terminal);
  651        register_action(editor, window, Editor::reload_file);
  652        register_action(editor, window, Editor::spawn_nearest_task);
  653        register_action(editor, window, Editor::insert_uuid_v4);
  654        register_action(editor, window, Editor::insert_uuid_v7);
  655        register_action(editor, window, Editor::open_selections_in_multibuffer);
  656        register_action(editor, window, Editor::toggle_bookmark);
  657        register_action(editor, window, Editor::go_to_next_bookmark);
  658        register_action(editor, window, Editor::go_to_previous_bookmark);
  659        register_action(editor, window, Editor::toggle_breakpoint);
  660        register_action(editor, window, Editor::edit_log_breakpoint);
  661        register_action(editor, window, Editor::enable_breakpoint);
  662        register_action(editor, window, Editor::disable_breakpoint);
  663        register_action(editor, window, Editor::toggle_read_only);
  664        register_action(editor, window, Editor::align_selections);
  665        if editor.read(cx).enable_wrap_selections_in_tag(cx) {
  666            register_action(editor, window, Editor::wrap_selections_in_tag);
  667        }
  668    }
  669
  670    fn register_key_listeners(&self, window: &mut Window, _: &mut App, layout: &EditorLayout) {
  671        let position_map = layout.position_map.clone();
  672        window.on_key_event({
  673            let editor = self.editor.clone();
  674            move |event: &ModifiersChangedEvent, phase, window, cx| {
  675                if phase != DispatchPhase::Bubble {
  676                    return;
  677                }
  678                editor.update(cx, |editor, cx| {
  679                    let inlay_hint_settings = inlay_hint_settings(
  680                        editor.selections.newest_anchor().head(),
  681                        &editor.buffer.read(cx).snapshot(cx),
  682                        cx,
  683                    );
  684
  685                    if let Some(inlay_modifiers) = inlay_hint_settings
  686                        .toggle_on_modifiers_press
  687                        .as_ref()
  688                        .filter(|modifiers| modifiers.modified())
  689                    {
  690                        editor.refresh_inlay_hints(
  691                            InlayHintRefreshReason::ModifiersChanged(
  692                                inlay_modifiers == &event.modifiers,
  693                            ),
  694                            cx,
  695                        );
  696                    }
  697
  698                    if editor.hover_state.focused(window, cx) {
  699                        return;
  700                    }
  701
  702                    editor.handle_modifiers_changed(event.modifiers, &position_map, window, cx);
  703                })
  704            }
  705        });
  706    }
  707
  708    fn mouse_left_down(
  709        editor: &mut Editor,
  710        event: &MouseDownEvent,
  711        position_map: &PositionMap,
  712        line_numbers: &HashMap<MultiBufferRow, LineNumberLayout>,
  713        window: &mut Window,
  714        cx: &mut Context<Editor>,
  715    ) {
  716        if window.default_prevented() {
  717            return;
  718        }
  719
  720        let text_hitbox = &position_map.text_hitbox;
  721        let gutter_hitbox = &position_map.gutter_hitbox;
  722        let point_for_position = position_map.point_for_position(event.position);
  723        let mut click_count = event.click_count;
  724        let mut modifiers = event.modifiers;
  725
  726        if let Some(hovered_hunk) =
  727            position_map
  728                .display_hunks
  729                .iter()
  730                .find_map(|(hunk, hunk_hitbox)| match hunk {
  731                    DisplayDiffHunk::Folded { .. } => None,
  732                    DisplayDiffHunk::Unfolded {
  733                        multi_buffer_range, ..
  734                    } => hunk_hitbox
  735                        .as_ref()
  736                        .is_some_and(|hitbox| hitbox.is_hovered(window))
  737                        .then(|| multi_buffer_range.clone()),
  738                })
  739        {
  740            editor.toggle_single_diff_hunk(hovered_hunk, cx);
  741            cx.notify();
  742            return;
  743        } else if gutter_hitbox.is_hovered(window) {
  744            click_count = 3; // Simulate triple-click when clicking the gutter to select lines
  745        } else if !text_hitbox.is_hovered(window) {
  746            return;
  747        }
  748
  749        if EditorSettings::get_global(cx)
  750            .drag_and_drop_selection
  751            .enabled
  752            && click_count == 1
  753            && !modifiers.shift
  754        {
  755            let newest_anchor = editor.selections.newest_anchor();
  756            let snapshot = editor.snapshot(window, cx);
  757            let selection = newest_anchor.map(|anchor| anchor.to_display_point(&snapshot));
  758            if point_for_position.intersects_selection(&selection) {
  759                editor.selection_drag_state = SelectionDragState::ReadyToDrag {
  760                    selection: newest_anchor.clone(),
  761                    click_position: event.position,
  762                    mouse_down_time: Instant::now(),
  763                };
  764                cx.stop_propagation();
  765                return;
  766            }
  767        }
  768
  769        let is_singleton = editor.buffer().read(cx).is_singleton();
  770
  771        if click_count == 2 && !is_singleton {
  772            match EditorSettings::get_global(cx).double_click_in_multibuffer {
  773                DoubleClickInMultibuffer::Select => {
  774                    // do nothing special on double click, all selection logic is below
  775                }
  776                DoubleClickInMultibuffer::Open => {
  777                    if modifiers.alt {
  778                        // if double click is made with alt, pretend it's a regular double click without opening and alt,
  779                        // and run the selection logic.
  780                        modifiers.alt = false;
  781                    } else {
  782                        let scroll_position_row = position_map.scroll_position.y;
  783                        let display_row = (((event.position - gutter_hitbox.bounds.origin).y
  784                            / position_map.line_height)
  785                            as f64
  786                            + position_map.scroll_position.y)
  787                            as u32;
  788                        let multi_buffer_row = position_map
  789                            .snapshot
  790                            .display_point_to_point(
  791                                DisplayPoint::new(DisplayRow(display_row), 0),
  792                                Bias::Right,
  793                            )
  794                            .row;
  795                        let line_offset_from_top = display_row - scroll_position_row as u32;
  796                        // if double click is made without alt, open the corresponding excerp
  797                        editor.open_excerpts_common(
  798                            Some(JumpData::MultiBufferRow {
  799                                row: MultiBufferRow(multi_buffer_row),
  800                                line_offset_from_top,
  801                            }),
  802                            false,
  803                            window,
  804                            cx,
  805                        );
  806                        return;
  807                    }
  808                }
  809            }
  810        }
  811
  812        if !is_singleton {
  813            let display_row = (ScrollPixelOffset::from(
  814                (event.position - gutter_hitbox.bounds.origin).y / position_map.line_height,
  815            ) + position_map.scroll_position.y) as u32;
  816            let multi_buffer_row = position_map
  817                .snapshot
  818                .display_point_to_point(DisplayPoint::new(DisplayRow(display_row), 0), Bias::Right)
  819                .row;
  820            if line_numbers
  821                .get(&MultiBufferRow(multi_buffer_row))
  822                .is_some_and(|line_layout| {
  823                    line_layout.segments.iter().any(|segment| {
  824                        segment
  825                            .hitbox
  826                            .as_ref()
  827                            .is_some_and(|hitbox| hitbox.contains(&event.position))
  828                    })
  829                })
  830            {
  831                let line_offset_from_top = display_row - position_map.scroll_position.y as u32;
  832
  833                editor.open_excerpts_common(
  834                    Some(JumpData::MultiBufferRow {
  835                        row: MultiBufferRow(multi_buffer_row),
  836                        line_offset_from_top,
  837                    }),
  838                    modifiers.alt,
  839                    window,
  840                    cx,
  841                );
  842                cx.stop_propagation();
  843                return;
  844            }
  845        }
  846
  847        let position = point_for_position.nearest_valid;
  848        if let Some(mode) = Editor::columnar_selection_mode(&modifiers, cx) {
  849            editor.select(
  850                SelectPhase::BeginColumnar {
  851                    position,
  852                    reset: match mode {
  853                        ColumnarMode::FromMouse => true,
  854                        ColumnarMode::FromSelection => false,
  855                    },
  856                    mode,
  857                    goal_column: point_for_position.exact_unclipped.column(),
  858                },
  859                window,
  860                cx,
  861            );
  862        } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
  863        {
  864            editor.select(
  865                SelectPhase::Extend {
  866                    position,
  867                    click_count,
  868                },
  869                window,
  870                cx,
  871            );
  872        } else {
  873            editor.select(
  874                SelectPhase::Begin {
  875                    position,
  876                    add: Editor::is_alt_pressed(&modifiers, cx),
  877                    click_count,
  878                },
  879                window,
  880                cx,
  881            );
  882        }
  883        cx.stop_propagation();
  884    }
  885
  886    fn mouse_right_down(
  887        editor: &mut Editor,
  888        event: &MouseDownEvent,
  889        position_map: &PositionMap,
  890        window: &mut Window,
  891        cx: &mut Context<Editor>,
  892    ) {
  893        if position_map.gutter_hitbox.is_hovered(window) {
  894            let gutter_right_padding = editor.gutter_dimensions.right_padding;
  895            let hitbox = &position_map.gutter_hitbox;
  896
  897            if event.position.x <= hitbox.bounds.right() - gutter_right_padding
  898                && editor.collaboration_hub.is_none()
  899            {
  900                let point_for_position = position_map.point_for_position(event.position);
  901                editor.set_gutter_context_menu(
  902                    point_for_position.nearest_valid.row(),
  903                    None,
  904                    event.position,
  905                    window,
  906                    cx,
  907                );
  908            }
  909            return;
  910        }
  911
  912        if !position_map.text_hitbox.is_hovered(window) {
  913            return;
  914        }
  915
  916        let point_for_position = position_map.point_for_position(event.position);
  917        mouse_context_menu::deploy_context_menu(
  918            editor,
  919            Some(event.position),
  920            point_for_position.nearest_valid,
  921            window,
  922            cx,
  923        );
  924        cx.stop_propagation();
  925    }
  926
  927    fn mouse_middle_down(
  928        editor: &mut Editor,
  929        event: &MouseDownEvent,
  930        position_map: &PositionMap,
  931        window: &mut Window,
  932        cx: &mut Context<Editor>,
  933    ) {
  934        if !position_map.text_hitbox.is_hovered(window) || window.default_prevented() {
  935            return;
  936        }
  937
  938        let point_for_position = position_map.point_for_position(event.position);
  939        let position = point_for_position.nearest_valid;
  940
  941        editor.select(
  942            SelectPhase::BeginColumnar {
  943                position,
  944                reset: true,
  945                mode: ColumnarMode::FromMouse,
  946                goal_column: point_for_position.exact_unclipped.column(),
  947            },
  948            window,
  949            cx,
  950        );
  951    }
  952
  953    fn mouse_up(
  954        editor: &mut Editor,
  955        event: &MouseUpEvent,
  956        position_map: &PositionMap,
  957        window: &mut Window,
  958        cx: &mut Context<Editor>,
  959    ) {
  960        // Handle diff review drag completion
  961        if editor.diff_review_drag_state.is_some() {
  962            editor.end_diff_review_drag(window, cx);
  963            cx.stop_propagation();
  964            return;
  965        }
  966
  967        let text_hitbox = &position_map.text_hitbox;
  968        let end_selection = editor.has_pending_selection();
  969        let pending_nonempty_selections = editor.has_pending_nonempty_selection();
  970        let point_for_position = position_map.point_for_position(event.position);
  971
  972        match editor.selection_drag_state {
  973            SelectionDragState::ReadyToDrag {
  974                selection: _,
  975                ref click_position,
  976                mouse_down_time: _,
  977            } => {
  978                if event.position == *click_position {
  979                    editor.select(
  980                        SelectPhase::Begin {
  981                            position: point_for_position.nearest_valid,
  982                            add: false,
  983                            click_count: 1, // ready to drag state only occurs on click count 1
  984                        },
  985                        window,
  986                        cx,
  987                    );
  988                    editor.selection_drag_state = SelectionDragState::None;
  989                    cx.stop_propagation();
  990                    return;
  991                } else {
  992                    debug_panic!("drag state can never be in ready state after drag")
  993                }
  994            }
  995            SelectionDragState::Dragging { ref selection, .. } => {
  996                let snapshot = editor.snapshot(window, cx);
  997                let selection_display = selection.map(|anchor| anchor.to_display_point(&snapshot));
  998                if !point_for_position.intersects_selection(&selection_display)
  999                    && text_hitbox.is_hovered(window)
 1000                {
 1001                    let is_cut = !(cfg!(target_os = "macos") && event.modifiers.alt
 1002                        || cfg!(not(target_os = "macos")) && event.modifiers.control);
 1003                    editor.move_selection_on_drop(
 1004                        &selection.clone(),
 1005                        point_for_position.nearest_valid,
 1006                        is_cut,
 1007                        window,
 1008                        cx,
 1009                    );
 1010                }
 1011                editor.selection_drag_state = SelectionDragState::None;
 1012                cx.stop_propagation();
 1013                cx.notify();
 1014                return;
 1015            }
 1016            _ => {}
 1017        }
 1018
 1019        if end_selection {
 1020            editor.select(SelectPhase::End, window, cx);
 1021        }
 1022
 1023        if end_selection && pending_nonempty_selections {
 1024            cx.stop_propagation();
 1025        } else if cfg!(any(target_os = "linux", target_os = "freebsd"))
 1026            && event.button == MouseButton::Middle
 1027        {
 1028            #[allow(
 1029                clippy::collapsible_if,
 1030                clippy::needless_return,
 1031                reason = "The cfg-block below makes this a false positive"
 1032            )]
 1033            if !text_hitbox.is_hovered(window) || editor.read_only(cx) {
 1034                return;
 1035            }
 1036
 1037            #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1038            if EditorSettings::get_global(cx).middle_click_paste {
 1039                if let Some(text) = cx.read_from_primary().and_then(|item| item.text()) {
 1040                    let point_for_position = position_map.point_for_position(event.position);
 1041                    let position = point_for_position.nearest_valid;
 1042
 1043                    editor.select(
 1044                        SelectPhase::Begin {
 1045                            position,
 1046                            add: false,
 1047                            click_count: 1,
 1048                        },
 1049                        window,
 1050                        cx,
 1051                    );
 1052                    editor.insert(&text, window, cx);
 1053                }
 1054                cx.stop_propagation()
 1055            }
 1056        }
 1057    }
 1058
 1059    fn click(
 1060        editor: &mut Editor,
 1061        event: &ClickEvent,
 1062        position_map: &PositionMap,
 1063        window: &mut Window,
 1064        cx: &mut Context<Editor>,
 1065    ) {
 1066        let text_hitbox = &position_map.text_hitbox;
 1067        let pending_nonempty_selections = editor.has_pending_nonempty_selection();
 1068
 1069        let hovered_link_modifier = Editor::is_cmd_or_ctrl_pressed(&event.modifiers(), cx);
 1070        let mouse_down_hovered_link_modifier = if let ClickEvent::Mouse(mouse_event) = event {
 1071            Editor::is_cmd_or_ctrl_pressed(&mouse_event.down.modifiers, cx)
 1072        } else {
 1073            true
 1074        };
 1075
 1076        if let Some(mouse_position) = event.mouse_position()
 1077            && !pending_nonempty_selections
 1078            && hovered_link_modifier
 1079            && mouse_down_hovered_link_modifier
 1080            && text_hitbox.is_hovered(window)
 1081            && !matches!(
 1082                editor.selection_drag_state,
 1083                SelectionDragState::Dragging { .. }
 1084            )
 1085        {
 1086            let point = position_map.point_for_position(mouse_position);
 1087            editor.handle_click_hovered_link(point, event.modifiers(), window, cx);
 1088            editor.selection_drag_state = SelectionDragState::None;
 1089
 1090            cx.stop_propagation();
 1091        }
 1092    }
 1093
 1094    fn pressure_click(
 1095        editor: &mut Editor,
 1096        event: &MousePressureEvent,
 1097        position_map: &PositionMap,
 1098        window: &mut Window,
 1099        cx: &mut Context<Editor>,
 1100    ) {
 1101        let text_hitbox = &position_map.text_hitbox;
 1102        let force_click_possible =
 1103            matches!(editor.prev_pressure_stage, Some(PressureStage::Normal))
 1104                && event.stage == PressureStage::Force;
 1105
 1106        editor.prev_pressure_stage = Some(event.stage);
 1107
 1108        if force_click_possible && text_hitbox.is_hovered(window) {
 1109            let point = position_map.point_for_position(event.position);
 1110            editor.handle_click_hovered_link(point, event.modifiers, window, cx);
 1111            editor.selection_drag_state = SelectionDragState::None;
 1112            cx.stop_propagation();
 1113        }
 1114    }
 1115
 1116    fn mouse_dragged(
 1117        editor: &mut Editor,
 1118        event: &MouseMoveEvent,
 1119        position_map: &PositionMap,
 1120        window: &mut Window,
 1121        cx: &mut Context<Editor>,
 1122    ) {
 1123        if !editor.has_pending_selection()
 1124            && matches!(editor.selection_drag_state, SelectionDragState::None)
 1125        {
 1126            return;
 1127        }
 1128
 1129        let point_for_position = position_map.point_for_position(event.position);
 1130        let text_hitbox = &position_map.text_hitbox;
 1131
 1132        let scroll_delta = {
 1133            let text_bounds = text_hitbox.bounds;
 1134            let mut scroll_delta = gpui::Point::<f32>::default();
 1135            let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
 1136            let top = text_bounds.origin.y + vertical_margin;
 1137            let bottom = text_bounds.bottom_left().y - vertical_margin;
 1138            if event.position.y < top {
 1139                scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
 1140            }
 1141            if event.position.y > bottom {
 1142                scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
 1143            }
 1144
 1145            // We need horizontal width of text
 1146            let style = editor.style.clone().unwrap_or_default();
 1147            let font_id = window.text_system().resolve_font(&style.text.font());
 1148            let font_size = style.text.font_size.to_pixels(window.rem_size());
 1149            let em_width = window.text_system().em_width(font_id, font_size).unwrap();
 1150
 1151            let scroll_margin_x = EditorSettings::get_global(cx).horizontal_scroll_margin;
 1152
 1153            let scroll_space: Pixels = scroll_margin_x * em_width;
 1154
 1155            let left = text_bounds.origin.x + scroll_space;
 1156            let right = text_bounds.top_right().x - scroll_space;
 1157
 1158            if event.position.x < left {
 1159                scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
 1160            }
 1161            if event.position.x > right {
 1162                scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
 1163            }
 1164            scroll_delta
 1165        };
 1166
 1167        if !editor.has_pending_selection() {
 1168            let drop_anchor = position_map
 1169                .snapshot
 1170                .display_point_to_anchor(point_for_position.nearest_valid, Bias::Left);
 1171            match editor.selection_drag_state {
 1172                SelectionDragState::Dragging {
 1173                    ref mut drop_cursor,
 1174                    ref mut hide_drop_cursor,
 1175                    ..
 1176                } => {
 1177                    drop_cursor.start = drop_anchor;
 1178                    drop_cursor.end = drop_anchor;
 1179                    *hide_drop_cursor = !text_hitbox.is_hovered(window);
 1180                    editor.apply_scroll_delta(scroll_delta, window, cx);
 1181                    cx.notify();
 1182                }
 1183                SelectionDragState::ReadyToDrag {
 1184                    ref selection,
 1185                    ref click_position,
 1186                    ref mouse_down_time,
 1187                } => {
 1188                    let drag_and_drop_delay = Duration::from_millis(
 1189                        EditorSettings::get_global(cx)
 1190                            .drag_and_drop_selection
 1191                            .delay
 1192                            .0,
 1193                    );
 1194                    if mouse_down_time.elapsed() >= drag_and_drop_delay {
 1195                        let drop_cursor = Selection {
 1196                            id: post_inc(&mut editor.selections.next_selection_id()),
 1197                            start: drop_anchor,
 1198                            end: drop_anchor,
 1199                            reversed: false,
 1200                            goal: SelectionGoal::None,
 1201                        };
 1202                        editor.selection_drag_state = SelectionDragState::Dragging {
 1203                            selection: selection.clone(),
 1204                            drop_cursor,
 1205                            hide_drop_cursor: false,
 1206                        };
 1207                        editor.apply_scroll_delta(scroll_delta, window, cx);
 1208                        cx.notify();
 1209                    } else {
 1210                        let click_point = position_map.point_for_position(*click_position);
 1211                        editor.selection_drag_state = SelectionDragState::None;
 1212                        editor.select(
 1213                            SelectPhase::Begin {
 1214                                position: click_point.nearest_valid,
 1215                                add: false,
 1216                                click_count: 1,
 1217                            },
 1218                            window,
 1219                            cx,
 1220                        );
 1221                        editor.select(
 1222                            SelectPhase::Update {
 1223                                position: point_for_position.nearest_valid,
 1224                                goal_column: point_for_position.exact_unclipped.column(),
 1225                                scroll_delta,
 1226                            },
 1227                            window,
 1228                            cx,
 1229                        );
 1230                    }
 1231                }
 1232                _ => {}
 1233            }
 1234        } else {
 1235            editor.select(
 1236                SelectPhase::Update {
 1237                    position: point_for_position.nearest_valid,
 1238                    goal_column: point_for_position.exact_unclipped.column(),
 1239                    scroll_delta,
 1240                },
 1241                window,
 1242                cx,
 1243            );
 1244        }
 1245    }
 1246
 1247    pub(crate) fn mouse_moved(
 1248        editor: &mut Editor,
 1249        event: &MouseMoveEvent,
 1250        position_map: &PositionMap,
 1251        split_side: Option<SplitSide>,
 1252        window: &mut Window,
 1253        cx: &mut Context<Editor>,
 1254    ) {
 1255        let text_hitbox = &position_map.text_hitbox;
 1256        let gutter_hitbox = &position_map.gutter_hitbox;
 1257        let modifiers = event.modifiers;
 1258        let text_hovered = text_hitbox.is_hovered(window);
 1259        let gutter_hovered = gutter_hitbox.is_hovered(window);
 1260        editor.set_gutter_hovered(gutter_hovered, cx);
 1261        editor.show_mouse_cursor(cx);
 1262
 1263        let point_for_position = position_map.point_for_position(event.position);
 1264        let valid_point = point_for_position.nearest_valid;
 1265
 1266        // Update diff review drag state if we're dragging
 1267        if editor.diff_review_drag_state.is_some() {
 1268            editor.update_diff_review_drag(valid_point.row(), window, cx);
 1269        }
 1270
 1271        let hovered_diff_control = position_map
 1272            .diff_hunk_control_bounds
 1273            .iter()
 1274            .find(|(_, bounds)| bounds.contains(&event.position))
 1275            .map(|(row, _)| *row);
 1276
 1277        let hovered_diff_hunk_row = if let Some(control_row) = hovered_diff_control {
 1278            Some(control_row)
 1279        } else if text_hovered {
 1280            let current_row = valid_point.row();
 1281            position_map.display_hunks.iter().find_map(|(hunk, _)| {
 1282                if let DisplayDiffHunk::Unfolded {
 1283                    display_row_range, ..
 1284                } = hunk
 1285                {
 1286                    if display_row_range.contains(&current_row) {
 1287                        Some(display_row_range.start)
 1288                    } else {
 1289                        None
 1290                    }
 1291                } else {
 1292                    None
 1293                }
 1294            })
 1295        } else {
 1296            None
 1297        };
 1298
 1299        if hovered_diff_hunk_row != editor.hovered_diff_hunk_row {
 1300            editor.hovered_diff_hunk_row = hovered_diff_hunk_row;
 1301            cx.notify();
 1302        }
 1303
 1304        if text_hovered
 1305            && let Some((bounds, buffer_id, blame_entry)) = &position_map.inline_blame_bounds
 1306        {
 1307            let mouse_over_inline_blame = bounds.contains(&event.position);
 1308            let mouse_over_popover = editor
 1309                .inline_blame_popover
 1310                .as_ref()
 1311                .and_then(|state| state.popover_bounds)
 1312                .is_some_and(|bounds| bounds.contains(&event.position));
 1313            let keyboard_grace = editor
 1314                .inline_blame_popover
 1315                .as_ref()
 1316                .is_some_and(|state| state.keyboard_grace);
 1317
 1318            if mouse_over_inline_blame || mouse_over_popover {
 1319                editor.show_blame_popover(*buffer_id, blame_entry, event.position, false, cx);
 1320            } else if !keyboard_grace {
 1321                editor.hide_blame_popover(false, cx);
 1322            }
 1323        } else {
 1324            let keyboard_grace = editor
 1325                .inline_blame_popover
 1326                .as_ref()
 1327                .is_some_and(|state| state.keyboard_grace);
 1328            if !keyboard_grace {
 1329                editor.hide_blame_popover(false, cx);
 1330            }
 1331        }
 1332
 1333        // Handle diff review indicator when gutter is hovered in diff mode with AI enabled
 1334        let show_diff_review = editor.show_diff_review_button()
 1335            && cx.has_flag::<DiffReviewFeatureFlag>()
 1336            && !DisableAiSettings::is_ai_disabled_for_buffer(
 1337                editor.buffer.read(cx).as_singleton().as_ref(),
 1338                cx,
 1339            );
 1340
 1341        let diff_review_indicator = if gutter_hovered && show_diff_review {
 1342            let is_visible = editor
 1343                .gutter_diff_review_indicator
 1344                .0
 1345                .is_some_and(|indicator| indicator.is_active);
 1346
 1347            if !is_visible {
 1348                editor
 1349                    .gutter_diff_review_indicator
 1350                    .1
 1351                    .get_or_insert_with(|| {
 1352                        cx.spawn(async move |this, cx| {
 1353                            cx.background_executor()
 1354                                .timer(Duration::from_millis(200))
 1355                                .await;
 1356
 1357                            this.update(cx, |this, cx| {
 1358                                if let Some(indicator) =
 1359                                    this.gutter_diff_review_indicator.0.as_mut()
 1360                                {
 1361                                    indicator.is_active = true;
 1362                                    cx.notify();
 1363                                }
 1364                            })
 1365                            .ok();
 1366                        })
 1367                    });
 1368            }
 1369
 1370            let anchor = position_map
 1371                .snapshot
 1372                .display_point_to_anchor(valid_point, Bias::Left);
 1373            Some(PhantomDiffReviewIndicator {
 1374                start: anchor,
 1375                end: anchor,
 1376                is_active: is_visible,
 1377            })
 1378        } else {
 1379            editor.gutter_diff_review_indicator.1 = None;
 1380            None
 1381        };
 1382
 1383        if diff_review_indicator != editor.gutter_diff_review_indicator.0 {
 1384            editor.gutter_diff_review_indicator.0 = diff_review_indicator;
 1385            cx.notify();
 1386        }
 1387
 1388        // Don't show breakpoint indicator when diff review indicator is active on this row
 1389        let is_on_diff_review_button_row = diff_review_indicator.is_some_and(|indicator| {
 1390            let start_row = indicator
 1391                .start
 1392                .to_display_point(&position_map.snapshot.display_snapshot)
 1393                .row();
 1394            indicator.is_active && start_row == valid_point.row()
 1395        });
 1396
 1397        let breakpoint_indicator = if gutter_hovered
 1398            && !is_on_diff_review_button_row
 1399            && split_side != Some(SplitSide::Left)
 1400        {
 1401            let buffer_anchor = position_map
 1402                .snapshot
 1403                .display_point_to_anchor(valid_point, Bias::Left);
 1404
 1405            if position_map
 1406                .snapshot
 1407                .buffer_snapshot()
 1408                .anchor_to_buffer_anchor(buffer_anchor)
 1409                .is_some()
 1410            {
 1411                let is_visible = editor
 1412                    .gutter_hover_button
 1413                    .0
 1414                    .is_some_and(|indicator| indicator.is_active);
 1415
 1416                if !is_visible {
 1417                    editor.gutter_hover_button.1.get_or_insert_with(|| {
 1418                        cx.spawn(async move |this, cx| {
 1419                            cx.background_executor()
 1420                                .timer(Duration::from_millis(200))
 1421                                .await;
 1422
 1423                            this.update(cx, |this, cx| {
 1424                                if let Some(indicator) = this.gutter_hover_button.0.as_mut() {
 1425                                    indicator.is_active = true;
 1426                                    cx.notify();
 1427                                }
 1428                            })
 1429                            .ok();
 1430                        })
 1431                    });
 1432                }
 1433
 1434                Some(GutterHoverButton {
 1435                    display_row: valid_point.row(),
 1436                    is_active: is_visible,
 1437                })
 1438            } else {
 1439                editor.gutter_hover_button.1 = None;
 1440                None
 1441            }
 1442        } else {
 1443            editor.gutter_hover_button.1 = None;
 1444            None
 1445        };
 1446
 1447        if &breakpoint_indicator != &editor.gutter_hover_button.0 {
 1448            editor.gutter_hover_button.0 = breakpoint_indicator;
 1449            cx.notify();
 1450        }
 1451
 1452        // Don't trigger hover popover if mouse is hovering over context menu
 1453        if text_hovered {
 1454            editor.update_hovered_link(
 1455                point_for_position,
 1456                Some(event.position),
 1457                &position_map.snapshot,
 1458                modifiers,
 1459                window,
 1460                cx,
 1461            );
 1462
 1463            if let Some(point) = point_for_position.as_valid() {
 1464                let anchor = position_map
 1465                    .snapshot
 1466                    .buffer_snapshot()
 1467                    .anchor_before(point.to_offset(&position_map.snapshot, Bias::Left));
 1468                hover_at(editor, Some(anchor), Some(event.position), window, cx);
 1469                Self::update_visible_cursor(editor, point, position_map, window, cx);
 1470            } else {
 1471                editor.update_inlay_link_and_hover_points(
 1472                    &position_map.snapshot,
 1473                    point_for_position,
 1474                    Some(event.position),
 1475                    modifiers.secondary(),
 1476                    modifiers.shift,
 1477                    window,
 1478                    cx,
 1479                );
 1480            }
 1481        } else {
 1482            editor.hide_hovered_link(cx);
 1483            hover_at(editor, None, Some(event.position), window, cx);
 1484        }
 1485    }
 1486
 1487    fn update_visible_cursor(
 1488        editor: &mut Editor,
 1489        point: DisplayPoint,
 1490        position_map: &PositionMap,
 1491        window: &mut Window,
 1492        cx: &mut Context<Editor>,
 1493    ) {
 1494        let snapshot = &position_map.snapshot;
 1495        let Some(hub) = editor.collaboration_hub() else {
 1496            return;
 1497        };
 1498        let start = snapshot.display_snapshot.clip_point(
 1499            DisplayPoint::new(point.row(), point.column().saturating_sub(1)),
 1500            Bias::Left,
 1501        );
 1502        let end = snapshot.display_snapshot.clip_point(
 1503            DisplayPoint::new(
 1504                point.row(),
 1505                (point.column() + 1).min(snapshot.line_len(point.row())),
 1506            ),
 1507            Bias::Right,
 1508        );
 1509
 1510        let range = snapshot
 1511            .buffer_snapshot()
 1512            .anchor_before(start.to_point(&snapshot.display_snapshot))
 1513            ..snapshot
 1514                .buffer_snapshot()
 1515                .anchor_after(end.to_point(&snapshot.display_snapshot));
 1516
 1517        let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
 1518            return;
 1519        };
 1520        let key = crate::HoveredCursor {
 1521            replica_id: selection.replica_id,
 1522            selection_id: selection.selection.id,
 1523        };
 1524        editor.hovered_cursors.insert(
 1525            key.clone(),
 1526            cx.spawn_in(window, async move |editor, cx| {
 1527                cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 1528                editor
 1529                    .update(cx, |editor, cx| {
 1530                        editor.hovered_cursors.remove(&key);
 1531                        cx.notify();
 1532                    })
 1533                    .ok();
 1534            }),
 1535        );
 1536        cx.notify()
 1537    }
 1538
 1539    fn layout_selections(
 1540        &self,
 1541        start_anchor: Anchor,
 1542        end_anchor: Anchor,
 1543        local_selections: &[Selection<Point>],
 1544        snapshot: &EditorSnapshot,
 1545        start_row: DisplayRow,
 1546        end_row: DisplayRow,
 1547        window: &mut Window,
 1548        cx: &mut App,
 1549    ) -> (
 1550        Vec<(PlayerColor, Vec<SelectionLayout>)>,
 1551        BTreeMap<DisplayRow, LineHighlightSpec>,
 1552        Option<DisplayPoint>,
 1553    ) {
 1554        let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
 1555        let mut active_rows = BTreeMap::new();
 1556        let mut newest_selection_head = None;
 1557
 1558        let Some(editor_with_selections) = self.editor_with_selections(cx) else {
 1559            return (selections, active_rows, newest_selection_head);
 1560        };
 1561
 1562        editor_with_selections.update(cx, |editor, cx| {
 1563            if editor.show_local_selections {
 1564                let mut layouts = Vec::new();
 1565                let newest = editor.selections.newest(&editor.display_snapshot(cx));
 1566                for selection in local_selections.iter().cloned() {
 1567                    let is_empty = selection.start == selection.end;
 1568                    let is_newest = selection == newest;
 1569
 1570                    let layout = SelectionLayout::new(
 1571                        selection,
 1572                        editor.selections.line_mode(),
 1573                        editor.cursor_offset_on_selection,
 1574                        editor.cursor_shape,
 1575                        &snapshot.display_snapshot,
 1576                        is_newest,
 1577                        editor.leader_id.is_none(),
 1578                        None,
 1579                    );
 1580                    if is_newest {
 1581                        newest_selection_head = Some(layout.head);
 1582                    }
 1583
 1584                    for row in cmp::max(layout.active_rows.start.0, start_row.0)
 1585                        ..=cmp::min(layout.active_rows.end.0, end_row.0)
 1586                    {
 1587                        let contains_non_empty_selection = active_rows
 1588                            .entry(DisplayRow(row))
 1589                            .or_insert_with(LineHighlightSpec::default);
 1590                        contains_non_empty_selection.selection |= !is_empty;
 1591                    }
 1592                    layouts.push(layout);
 1593                }
 1594
 1595                let mut player = editor.current_user_player_color(cx);
 1596                if !editor.is_focused(window) {
 1597                    const UNFOCUS_EDITOR_SELECTION_OPACITY: f32 = 0.5;
 1598                    player.selection = player.selection.opacity(UNFOCUS_EDITOR_SELECTION_OPACITY);
 1599                }
 1600                selections.push((player, layouts));
 1601
 1602                if let SelectionDragState::Dragging {
 1603                    ref selection,
 1604                    ref drop_cursor,
 1605                    ref hide_drop_cursor,
 1606                } = editor.selection_drag_state
 1607                    && !hide_drop_cursor
 1608                    && (drop_cursor
 1609                        .start
 1610                        .cmp(&selection.start, &snapshot.buffer_snapshot())
 1611                        .eq(&Ordering::Less)
 1612                        || drop_cursor
 1613                            .end
 1614                            .cmp(&selection.end, &snapshot.buffer_snapshot())
 1615                            .eq(&Ordering::Greater))
 1616                {
 1617                    let drag_cursor_layout = SelectionLayout::new(
 1618                        drop_cursor.clone(),
 1619                        false,
 1620                        editor.cursor_offset_on_selection,
 1621                        CursorShape::Bar,
 1622                        &snapshot.display_snapshot,
 1623                        false,
 1624                        false,
 1625                        None,
 1626                    );
 1627                    let absent_color = cx.theme().players().absent();
 1628                    selections.push((absent_color, vec![drag_cursor_layout]));
 1629                }
 1630            }
 1631
 1632            if let Some(collaboration_hub) = &editor.collaboration_hub {
 1633                // When following someone, render the local selections in their color.
 1634                if let Some(leader_id) = editor.leader_id {
 1635                    match leader_id {
 1636                        CollaboratorId::PeerId(peer_id) => {
 1637                            if let Some(collaborator) =
 1638                                collaboration_hub.collaborators(cx).get(&peer_id)
 1639                                && let Some(participant_index) = collaboration_hub
 1640                                    .user_participant_indices(cx)
 1641                                    .get(&collaborator.user_id)
 1642                                && let Some((local_selection_style, _)) = selections.first_mut()
 1643                            {
 1644                                *local_selection_style = cx
 1645                                    .theme()
 1646                                    .players()
 1647                                    .color_for_participant(participant_index.0);
 1648                            }
 1649                        }
 1650                        CollaboratorId::Agent => {
 1651                            if let Some((local_selection_style, _)) = selections.first_mut() {
 1652                                *local_selection_style = cx.theme().players().agent();
 1653                            }
 1654                        }
 1655                    }
 1656                }
 1657
 1658                let mut remote_selections = HashMap::default();
 1659                for selection in snapshot.remote_selections_in_range(
 1660                    &(start_anchor..end_anchor),
 1661                    collaboration_hub.as_ref(),
 1662                    cx,
 1663                ) {
 1664                    // Don't re-render the leader's selections, since the local selections
 1665                    // match theirs.
 1666                    if Some(selection.collaborator_id) == editor.leader_id {
 1667                        continue;
 1668                    }
 1669                    let key = HoveredCursor {
 1670                        replica_id: selection.replica_id,
 1671                        selection_id: selection.selection.id,
 1672                    };
 1673
 1674                    let is_shown =
 1675                        editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
 1676
 1677                    remote_selections
 1678                        .entry(selection.replica_id)
 1679                        .or_insert((selection.color, Vec::new()))
 1680                        .1
 1681                        .push(SelectionLayout::new(
 1682                            selection.selection,
 1683                            selection.line_mode,
 1684                            editor.cursor_offset_on_selection,
 1685                            selection.cursor_shape,
 1686                            &snapshot.display_snapshot,
 1687                            false,
 1688                            false,
 1689                            if is_shown { selection.user_name } else { None },
 1690                        ));
 1691                }
 1692
 1693                selections.extend(remote_selections.into_values());
 1694            } else if !editor.is_focused(window) && editor.show_cursor_when_unfocused {
 1695                let cursor_offset_on_selection = editor.cursor_offset_on_selection;
 1696
 1697                let layouts = snapshot
 1698                    .buffer_snapshot()
 1699                    .selections_in_range(&(start_anchor..end_anchor), true)
 1700                    .map(move |(_, line_mode, cursor_shape, selection)| {
 1701                        SelectionLayout::new(
 1702                            selection,
 1703                            line_mode,
 1704                            cursor_offset_on_selection,
 1705                            cursor_shape,
 1706                            &snapshot.display_snapshot,
 1707                            false,
 1708                            false,
 1709                            None,
 1710                        )
 1711                    })
 1712                    .collect::<Vec<_>>();
 1713                let player = editor.current_user_player_color(cx);
 1714                selections.push((player, layouts));
 1715            }
 1716        });
 1717
 1718        #[cfg(debug_assertions)]
 1719        Self::layout_debug_ranges(
 1720            &mut selections,
 1721            start_anchor..end_anchor,
 1722            &snapshot.display_snapshot,
 1723            cx,
 1724        );
 1725
 1726        (selections, active_rows, newest_selection_head)
 1727    }
 1728
 1729    fn collect_cursors(
 1730        &self,
 1731        snapshot: &EditorSnapshot,
 1732        cx: &mut App,
 1733    ) -> Vec<(DisplayPoint, Hsla)> {
 1734        let editor = self.editor.read(cx);
 1735        let mut cursors = Vec::new();
 1736        let mut skip_local = false;
 1737        let mut add_cursor = |anchor: Anchor, color| {
 1738            cursors.push((anchor.to_display_point(&snapshot.display_snapshot), color));
 1739        };
 1740        // Remote cursors
 1741        if let Some(collaboration_hub) = &editor.collaboration_hub {
 1742            for remote_selection in snapshot.remote_selections_in_range(
 1743                &(Anchor::Min..Anchor::Max),
 1744                collaboration_hub.deref(),
 1745                cx,
 1746            ) {
 1747                add_cursor(
 1748                    remote_selection.selection.head(),
 1749                    remote_selection.color.cursor,
 1750                );
 1751                if Some(remote_selection.collaborator_id) == editor.leader_id {
 1752                    skip_local = true;
 1753                }
 1754            }
 1755        }
 1756        // Local cursors
 1757        if !skip_local {
 1758            let color = cx.theme().players().local().cursor;
 1759            editor
 1760                .selections
 1761                .disjoint_anchors()
 1762                .iter()
 1763                .for_each(|selection| {
 1764                    add_cursor(selection.head(), color);
 1765                });
 1766            if let Some(ref selection) = editor.selections.pending_anchor() {
 1767                add_cursor(selection.head(), color);
 1768            }
 1769        }
 1770        cursors
 1771    }
 1772
 1773    fn layout_visible_cursors(
 1774        &self,
 1775        snapshot: &EditorSnapshot,
 1776        selections: &[(PlayerColor, Vec<SelectionLayout>)],
 1777        row_block_types: &HashMap<DisplayRow, bool>,
 1778        visible_display_row_range: Range<DisplayRow>,
 1779        line_layouts: &[LineWithInvisibles],
 1780        text_hitbox: &Hitbox,
 1781        content_origin: gpui::Point<Pixels>,
 1782        scroll_position: gpui::Point<ScrollOffset>,
 1783        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 1784        line_height: Pixels,
 1785        em_width: Pixels,
 1786        em_advance: Pixels,
 1787        autoscroll_containing_element: bool,
 1788        redacted_ranges: &[Range<DisplayPoint>],
 1789        window: &mut Window,
 1790        cx: &mut App,
 1791    ) -> Vec<CursorLayout> {
 1792        let mut autoscroll_bounds = None;
 1793        let cursor_layouts = self.editor.update(cx, |editor, cx| {
 1794            let mut cursors = Vec::new();
 1795
 1796            let show_local_cursors = editor.show_local_cursors(window, cx);
 1797
 1798            for (player_color, selections) in selections {
 1799                for selection in selections {
 1800                    let cursor_position = selection.head;
 1801
 1802                    let in_range = visible_display_row_range.contains(&cursor_position.row());
 1803                    if (selection.is_local && !show_local_cursors)
 1804                        || !in_range
 1805                        || row_block_types.get(&cursor_position.row()) == Some(&true)
 1806                    {
 1807                        continue;
 1808                    }
 1809
 1810                    let cursor_row_layout = &line_layouts
 1811                        [cursor_position.row().minus(visible_display_row_range.start) as usize];
 1812                    let cursor_column = cursor_position.column() as usize;
 1813
 1814                    let cursor_character_x = cursor_row_layout.x_for_index(cursor_column)
 1815                        + cursor_row_layout
 1816                            .alignment_offset(self.style.text.text_align, text_hitbox.size.width);
 1817                    let cursor_next_x = cursor_row_layout.x_for_index(cursor_column + 1)
 1818                        + cursor_row_layout
 1819                            .alignment_offset(self.style.text.text_align, text_hitbox.size.width);
 1820                    let mut cell_width = cursor_next_x - cursor_character_x;
 1821                    if cell_width == Pixels::ZERO {
 1822                        cell_width = em_advance;
 1823                    }
 1824
 1825                    let mut block_width = cell_width;
 1826                    let mut block_text = None;
 1827
 1828                    let is_cursor_in_redacted_range = redacted_ranges
 1829                        .iter()
 1830                        .any(|range| range.start <= cursor_position && cursor_position < range.end);
 1831
 1832                    if selection.cursor_shape == CursorShape::Block && !is_cursor_in_redacted_range
 1833                    {
 1834                        if let Some(text) = snapshot.grapheme_at(cursor_position).or_else(|| {
 1835                            if snapshot.is_empty() {
 1836                                snapshot.placeholder_text().and_then(|s| {
 1837                                    s.graphemes(true).next().map(|s| s.to_string().into())
 1838                                })
 1839                            } else {
 1840                                None
 1841                            }
 1842                        }) {
 1843                            let is_ascii_whitespace_only =
 1844                                text.as_ref().chars().all(|c| c.is_ascii_whitespace());
 1845                            let len = text.len();
 1846
 1847                            let mut font = cursor_row_layout
 1848                                .font_id_for_index(cursor_column)
 1849                                .and_then(|cursor_font_id| {
 1850                                    window.text_system().get_font_for_id(cursor_font_id)
 1851                                })
 1852                                .unwrap_or(self.style.text.font());
 1853                            font.features = self.style.text.font_features.clone();
 1854
 1855                            // Invert the text color for the block cursor. Ensure that the text
 1856                            // color is opaque enough to be visible against the background color.
 1857                            //
 1858                            // 0.75 is an arbitrary threshold to determine if the background color is
 1859                            // opaque enough to use as a text color.
 1860                            //
 1861                            // TODO: In the future we should ensure themes have a `text_inverse` color.
 1862                            let color = if cx.theme().colors().editor_background.a < 0.75 {
 1863                                match cx.theme().appearance {
 1864                                    Appearance::Dark => Hsla::black(),
 1865                                    Appearance::Light => Hsla::white(),
 1866                                }
 1867                            } else {
 1868                                cx.theme().colors().editor_background
 1869                            };
 1870
 1871                            let shaped = window.text_system().shape_line(
 1872                                text,
 1873                                cursor_row_layout.font_size,
 1874                                &[TextRun {
 1875                                    len,
 1876                                    font,
 1877                                    color,
 1878                                    ..Default::default()
 1879                                }],
 1880                                None,
 1881                            );
 1882                            if !is_ascii_whitespace_only {
 1883                                block_width = block_width.max(shaped.width);
 1884                            }
 1885                            block_text = Some(shaped);
 1886                        }
 1887                    }
 1888
 1889                    let x = cursor_character_x - scroll_pixel_position.x.into();
 1890                    let y = ((cursor_position.row().as_f64() - scroll_position.y)
 1891                        * ScrollPixelOffset::from(line_height))
 1892                    .into();
 1893                    if selection.is_newest {
 1894                        editor.pixel_position_of_newest_cursor = Some(point(
 1895                            text_hitbox.origin.x + x + block_width / 2.,
 1896                            text_hitbox.origin.y + y + line_height / 2.,
 1897                        ));
 1898
 1899                        if autoscroll_containing_element {
 1900                            let top = text_hitbox.origin.y
 1901                                + ((cursor_position.row().as_f64() - scroll_position.y - 3.)
 1902                                    .max(0.)
 1903                                    * ScrollPixelOffset::from(line_height))
 1904                                .into();
 1905                            let left = text_hitbox.origin.x
 1906                                + ((cursor_position.column() as ScrollOffset
 1907                                    - scroll_position.x
 1908                                    - 3.)
 1909                                    .max(0.)
 1910                                    * ScrollPixelOffset::from(em_width))
 1911                                .into();
 1912
 1913                            let bottom = text_hitbox.origin.y
 1914                                + ((cursor_position.row().as_f64() - scroll_position.y + 4.)
 1915                                    * ScrollPixelOffset::from(line_height))
 1916                                .into();
 1917                            let right = text_hitbox.origin.x
 1918                                + ((cursor_position.column() as ScrollOffset - scroll_position.x
 1919                                    + 4.)
 1920                                    * ScrollPixelOffset::from(em_width))
 1921                                .into();
 1922
 1923                            autoscroll_bounds =
 1924                                Some(Bounds::from_corners(point(left, top), point(right, bottom)))
 1925                        }
 1926                    }
 1927
 1928                    let mut cursor = CursorLayout {
 1929                        color: player_color.cursor,
 1930                        block_width,
 1931                        origin: point(x, y),
 1932                        line_height,
 1933                        shape: selection.cursor_shape,
 1934                        block_text,
 1935                        cursor_name: None,
 1936                    };
 1937                    let cursor_name = selection.user_name.clone().map(|name| CursorName {
 1938                        string: name,
 1939                        color: self.style.background,
 1940                        is_top_row: cursor_position.row().0 == 0,
 1941                    });
 1942                    cursor.layout(content_origin, cursor_name, window, cx);
 1943                    cursors.push(cursor);
 1944                }
 1945            }
 1946
 1947            cursors
 1948        });
 1949
 1950        if let Some(bounds) = autoscroll_bounds {
 1951            window.request_autoscroll(bounds);
 1952        }
 1953
 1954        cursor_layouts
 1955    }
 1956
 1957    fn layout_navigation_overlays(
 1958        &self,
 1959        snapshot: &EditorSnapshot,
 1960        visible_display_row_range: Range<DisplayRow>,
 1961        line_layouts: &[LineWithInvisibles],
 1962        text_hitbox: &Hitbox,
 1963        content_origin: gpui::Point<Pixels>,
 1964        scroll_position: gpui::Point<ScrollOffset>,
 1965        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 1966        line_height: Pixels,
 1967        window: &mut Window,
 1968        cx: &mut App,
 1969    ) -> Vec<NavigationOverlayPaintCommand> {
 1970        let mut overlay_sets = self
 1971            .editor
 1972            .read(cx)
 1973            .navigation_overlay_sets()
 1974            .iter()
 1975            .map(|(key, overlays)| (*key, overlays.clone()))
 1976            .collect::<Vec<_>>();
 1977        if overlay_sets.is_empty() {
 1978            return Vec::new();
 1979        }
 1980        overlay_sets.sort_by_key(|(key, _)| *key);
 1981
 1982        let layout_context = NavigationOverlayLayoutContext {
 1983            display_snapshot: &snapshot.display_snapshot,
 1984            visible_display_row_range: &visible_display_row_range,
 1985            line_layouts,
 1986            text_align: self.style.text.text_align,
 1987            content_width: text_hitbox.size.width,
 1988            content_origin,
 1989            scroll_position,
 1990            scroll_pixel_position,
 1991            line_height,
 1992            editor_font: self.style.text.font(),
 1993            editor_font_size: self.style.text.font_size.to_pixels(window.rem_size()),
 1994        };
 1995        let mut navigation_overlay_paint_commands = Vec::new();
 1996
 1997        for (_, overlays) in overlay_sets {
 1998            for overlay in overlays.as_ref() {
 1999                Self::layout_navigation_label(
 2000                    overlay,
 2001                    &layout_context,
 2002                    window,
 2003                    cx,
 2004                    &mut navigation_overlay_paint_commands,
 2005                );
 2006            }
 2007        }
 2008
 2009        navigation_overlay_paint_commands
 2010    }
 2011
 2012    fn layout_navigation_label(
 2013        overlay: &crate::NavigationTargetOverlay,
 2014        context: &NavigationOverlayLayoutContext<'_>,
 2015        window: &mut Window,
 2016        cx: &mut App,
 2017        paint_commands: &mut Vec<NavigationOverlayPaintCommand>,
 2018    ) {
 2019        let label = &overlay.label;
 2020        let label_display_point = overlay
 2021            .target_range
 2022            .start
 2023            .to_display_point(context.display_snapshot);
 2024        let label_row = label_display_point.row();
 2025        if !context.visible_display_row_range.contains(&label_row) {
 2026            return;
 2027        }
 2028
 2029        let row_index = label_row.minus(context.visible_display_row_range.start) as usize;
 2030        let row_layout = &context.line_layouts[row_index];
 2031        let label_column = label_display_point.column().min(row_layout.len as u32) as usize;
 2032        let label_x = row_layout.x_for_index(label_column)
 2033            + row_layout.alignment_offset(context.text_align, context.content_width)
 2034            - context.scroll_pixel_position.x.into()
 2035            + label.x_offset;
 2036        let label_y = ((label_row.as_f64() - context.scroll_position.y)
 2037            * ScrollPixelOffset::from(context.line_height))
 2038        .into();
 2039        let label_text_size = (context.editor_font_size * label.scale_factor.max(0.0)).max(px(1.0));
 2040        let origin = context.content_origin + point(label_x, label_y);
 2041
 2042        let mut element = div()
 2043            .block_mouse_except_scroll()
 2044            .font(context.editor_font.clone())
 2045            .text_size(label_text_size)
 2046            .text_color(label.text_color)
 2047            .line_height(context.line_height)
 2048            .child(label.text.clone())
 2049            .into_any_element();
 2050        element.prepaint_as_root(origin, AvailableSpace::min_size(), window, cx);
 2051
 2052        paint_commands.push(NavigationOverlayPaintCommand::Label(
 2053            NavigationLabelLayout { element, origin },
 2054        ));
 2055    }
 2056
 2057    fn layout_scrollbars(
 2058        &self,
 2059        snapshot: &EditorSnapshot,
 2060        scrollbar_layout_information: &ScrollbarLayoutInformation,
 2061        content_offset: gpui::Point<Pixels>,
 2062        scroll_position: gpui::Point<ScrollOffset>,
 2063        non_visible_cursors: bool,
 2064        right_margin: Pixels,
 2065        editor_width: Pixels,
 2066        window: &mut Window,
 2067        cx: &mut App,
 2068    ) -> Option<EditorScrollbars> {
 2069        let show_scrollbars = self.editor.read(cx).show_scrollbars;
 2070        if (!show_scrollbars.horizontal && !show_scrollbars.vertical)
 2071            || self.style.scrollbar_width.is_zero()
 2072        {
 2073            return None;
 2074        }
 2075
 2076        // If a drag took place after we started dragging the scrollbar,
 2077        // cancel the scrollbar drag.
 2078        if cx.has_active_drag() {
 2079            self.editor.update(cx, |editor, cx| {
 2080                editor.scroll_manager.reset_scrollbar_state(cx)
 2081            });
 2082        }
 2083
 2084        let editor_settings = EditorSettings::get_global(cx);
 2085        let scrollbar_settings = editor_settings.scrollbar;
 2086        let show_scrollbars = match scrollbar_settings.show {
 2087            ShowScrollbar::Auto => {
 2088                let editor = self.editor.read(cx);
 2089                let is_singleton = editor.buffer_kind(cx) == ItemBufferKind::Singleton;
 2090                // Git
 2091                (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot().has_diff_hunks())
 2092                ||
 2093                // Buffer Search Results
 2094                (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights(HighlightKey::BufferSearchHighlights))
 2095                ||
 2096                // Selected Text Occurrences
 2097                (is_singleton && scrollbar_settings.selected_text && editor.has_background_highlights(HighlightKey::SelectedTextHighlight))
 2098                ||
 2099                // Selected Symbol Occurrences
 2100                (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights(HighlightKey::DocumentHighlightRead) || editor.has_background_highlights(HighlightKey::DocumentHighlightWrite)))
 2101                ||
 2102                // Diagnostics
 2103                (is_singleton && scrollbar_settings.diagnostics != ScrollbarDiagnostics::None && snapshot.buffer_snapshot().has_diagnostics())
 2104                ||
 2105                // Cursors out of sight
 2106                non_visible_cursors
 2107                ||
 2108                // Scrollmanager
 2109                editor.scroll_manager.scrollbars_visible()
 2110            }
 2111            ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
 2112            ShowScrollbar::Always => true,
 2113            ShowScrollbar::Never => return None,
 2114        };
 2115
 2116        // The horizontal scrollbar is usually slightly offset to align nicely with
 2117        // indent guides. However, this offset is not needed if indent guides are
 2118        // disabled for the current editor.
 2119        let content_offset = self
 2120            .editor
 2121            .read(cx)
 2122            .show_indent_guides
 2123            .is_none_or(|should_show| should_show)
 2124            .then_some(content_offset)
 2125            .unwrap_or_default();
 2126
 2127        Some(EditorScrollbars::from_scrollbar_axes(
 2128            ScrollbarAxes {
 2129                horizontal: scrollbar_settings.axes.horizontal
 2130                    && self.editor.read(cx).show_scrollbars.horizontal,
 2131                vertical: scrollbar_settings.axes.vertical
 2132                    && self.editor.read(cx).show_scrollbars.vertical,
 2133            },
 2134            scrollbar_layout_information,
 2135            content_offset,
 2136            scroll_position,
 2137            self.style.scrollbar_width,
 2138            right_margin,
 2139            editor_width,
 2140            show_scrollbars,
 2141            self.editor.read(cx).scroll_manager.active_scrollbar_state(),
 2142            window,
 2143        ))
 2144    }
 2145
 2146    fn layout_minimap(
 2147        &self,
 2148        snapshot: &EditorSnapshot,
 2149        minimap_width: Pixels,
 2150        scroll_position: gpui::Point<f64>,
 2151        scrollbar_layout_information: &ScrollbarLayoutInformation,
 2152        scrollbar_layout: Option<&EditorScrollbars>,
 2153        window: &mut Window,
 2154        cx: &mut App,
 2155    ) -> Option<MinimapLayout> {
 2156        let minimap_editor = self.editor.read(cx).minimap().cloned()?;
 2157
 2158        let minimap_settings = EditorSettings::get_global(cx).minimap;
 2159
 2160        if minimap_settings.on_active_editor() {
 2161            let active_editor = self.editor.read(cx).workspace().and_then(|ws| {
 2162                ws.read(cx)
 2163                    .active_pane()
 2164                    .read(cx)
 2165                    .active_item()
 2166                    .and_then(|i| i.act_as::<Editor>(cx))
 2167            });
 2168            if active_editor.is_some_and(|e| e != self.editor) {
 2169                return None;
 2170            }
 2171        }
 2172
 2173        if !snapshot.mode.is_full()
 2174            || minimap_width.is_zero()
 2175            || matches!(
 2176                minimap_settings.show,
 2177                ShowMinimap::Auto if scrollbar_layout.is_none_or(|layout| !layout.visible)
 2178            )
 2179        {
 2180            return None;
 2181        }
 2182
 2183        const MINIMAP_AXIS: ScrollbarAxis = ScrollbarAxis::Vertical;
 2184
 2185        let ScrollbarLayoutInformation {
 2186            editor_bounds,
 2187            scroll_range,
 2188            glyph_grid_cell,
 2189        } = scrollbar_layout_information;
 2190
 2191        let line_height = glyph_grid_cell.height;
 2192        let scroll_position = scroll_position.along(MINIMAP_AXIS);
 2193
 2194        let top_right_anchor = scrollbar_layout
 2195            .and_then(|layout| layout.vertical.as_ref())
 2196            .map(|vertical_scrollbar| vertical_scrollbar.hitbox.origin)
 2197            .unwrap_or_else(|| editor_bounds.top_right());
 2198
 2199        let thumb_state = self
 2200            .editor
 2201            .read_with(cx, |editor, _| editor.scroll_manager.minimap_thumb_state());
 2202
 2203        let show_thumb = match minimap_settings.thumb {
 2204            MinimapThumb::Always => true,
 2205            MinimapThumb::Hover => thumb_state.is_some(),
 2206        };
 2207
 2208        let minimap_bounds = Bounds::from_anchor_and_size(
 2209            gpui::Anchor::TopRight,
 2210            top_right_anchor,
 2211            size(minimap_width, editor_bounds.size.height),
 2212        );
 2213        let minimap_line_height = self.get_minimap_line_height(
 2214            minimap_editor
 2215                .read(cx)
 2216                .text_style_refinement
 2217                .as_ref()
 2218                .and_then(|refinement| refinement.font_size)
 2219                .unwrap_or(MINIMAP_FONT_SIZE),
 2220            window,
 2221            cx,
 2222        );
 2223        let minimap_height = minimap_bounds.size.height;
 2224
 2225        let visible_editor_lines = (editor_bounds.size.height / line_height) as f64;
 2226        let total_editor_lines = (scroll_range.height / line_height) as f64;
 2227        let minimap_lines = (minimap_height / minimap_line_height) as f64;
 2228
 2229        let minimap_scroll_top = MinimapLayout::calculate_minimap_top_offset(
 2230            total_editor_lines,
 2231            visible_editor_lines,
 2232            minimap_lines,
 2233            scroll_position,
 2234        );
 2235
 2236        let layout = ScrollbarLayout::for_minimap(
 2237            window.insert_hitbox(minimap_bounds, HitboxBehavior::Normal),
 2238            visible_editor_lines,
 2239            total_editor_lines,
 2240            minimap_line_height,
 2241            scroll_position,
 2242            minimap_scroll_top,
 2243            show_thumb,
 2244        )
 2245        .with_thumb_state(thumb_state);
 2246
 2247        minimap_editor.update(cx, |editor, cx| {
 2248            editor.set_scroll_position(point(0., minimap_scroll_top), window, cx)
 2249        });
 2250
 2251        // Required for the drop shadow to be visible
 2252        const PADDING_OFFSET: Pixels = px(4.);
 2253
 2254        let mut minimap = div()
 2255            .size_full()
 2256            .shadow_xs()
 2257            .px(PADDING_OFFSET)
 2258            .child(minimap_editor)
 2259            .into_any_element();
 2260
 2261        let extended_bounds = minimap_bounds.extend(Edges {
 2262            right: PADDING_OFFSET,
 2263            left: PADDING_OFFSET,
 2264            ..Default::default()
 2265        });
 2266        minimap.layout_as_root(extended_bounds.size.into(), window, cx);
 2267        window.with_absolute_element_offset(extended_bounds.origin, |window| {
 2268            minimap.prepaint(window, cx)
 2269        });
 2270
 2271        Some(MinimapLayout {
 2272            minimap,
 2273            thumb_layout: layout,
 2274            thumb_border_style: minimap_settings.thumb_border,
 2275            minimap_line_height,
 2276            minimap_scroll_top,
 2277            max_scroll_top: total_editor_lines,
 2278        })
 2279    }
 2280
 2281    fn get_minimap_line_height(
 2282        &self,
 2283        font_size: AbsoluteLength,
 2284        window: &mut Window,
 2285        cx: &mut App,
 2286    ) -> Pixels {
 2287        let rem_size = self.rem_size(cx).unwrap_or(window.rem_size());
 2288        let mut text_style = self.style.text.clone();
 2289        text_style.font_size = font_size;
 2290        text_style.line_height_in_pixels(rem_size)
 2291    }
 2292
 2293    fn get_minimap_width(
 2294        &self,
 2295        minimap_settings: &Minimap,
 2296        scrollbars_shown: bool,
 2297        text_width: Pixels,
 2298        em_width: Pixels,
 2299        font_size: Pixels,
 2300        rem_size: Pixels,
 2301        cx: &App,
 2302    ) -> Option<Pixels> {
 2303        if minimap_settings.show == ShowMinimap::Auto && !scrollbars_shown {
 2304            return None;
 2305        }
 2306
 2307        let minimap_font_size = self.editor.read_with(cx, |editor, cx| {
 2308            editor.minimap().map(|minimap_editor| {
 2309                minimap_editor
 2310                    .read(cx)
 2311                    .text_style_refinement
 2312                    .as_ref()
 2313                    .and_then(|refinement| refinement.font_size)
 2314                    .unwrap_or(MINIMAP_FONT_SIZE)
 2315            })
 2316        })?;
 2317
 2318        let minimap_em_width = em_width * (minimap_font_size.to_pixels(rem_size) / font_size);
 2319
 2320        let minimap_width = (text_width * MinimapLayout::MINIMAP_WIDTH_PCT)
 2321            .min(minimap_em_width * minimap_settings.max_width_columns.get() as f32);
 2322
 2323        (minimap_width >= minimap_em_width * MinimapLayout::MINIMAP_MIN_WIDTH_COLUMNS)
 2324            .then_some(minimap_width)
 2325    }
 2326
 2327    fn prepaint_crease_toggles(
 2328        &self,
 2329        crease_toggles: &mut [Option<AnyElement>],
 2330        line_height: Pixels,
 2331        gutter_dimensions: &GutterDimensions,
 2332        gutter_settings: crate::editor_settings::Gutter,
 2333        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 2334        gutter_hitbox: &Hitbox,
 2335        window: &mut Window,
 2336        cx: &mut App,
 2337    ) {
 2338        for (ix, crease_toggle) in crease_toggles.iter_mut().enumerate() {
 2339            if let Some(crease_toggle) = crease_toggle {
 2340                debug_assert!(gutter_settings.folds);
 2341                let available_space = size(
 2342                    AvailableSpace::MinContent,
 2343                    AvailableSpace::Definite(line_height * 0.55),
 2344                );
 2345                let crease_toggle_size = crease_toggle.layout_as_root(available_space, window, cx);
 2346
 2347                let position = point(
 2348                    gutter_dimensions.width - gutter_dimensions.right_padding,
 2349                    ix as f32 * line_height
 2350                        - (scroll_pixel_position.y % ScrollPixelOffset::from(line_height)).into(),
 2351                );
 2352                let centering_offset = point(
 2353                    (gutter_dimensions.fold_area_width() - crease_toggle_size.width) / 2.,
 2354                    (line_height - crease_toggle_size.height) / 2.,
 2355                );
 2356                let origin = gutter_hitbox.origin + position + centering_offset;
 2357                crease_toggle.prepaint_as_root(origin, available_space, window, cx);
 2358            }
 2359        }
 2360    }
 2361
 2362    fn prepaint_expand_toggles(
 2363        &self,
 2364        expand_toggles: &mut [Option<(AnyElement, gpui::Point<Pixels>)>],
 2365        window: &mut Window,
 2366        cx: &mut App,
 2367    ) {
 2368        for (expand_toggle, origin) in expand_toggles.iter_mut().flatten() {
 2369            let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
 2370            expand_toggle.layout_as_root(available_space, window, cx);
 2371            expand_toggle.prepaint_as_root(*origin, available_space, window, cx);
 2372        }
 2373    }
 2374
 2375    fn prepaint_crease_trailers(
 2376        &self,
 2377        trailers: Vec<Option<AnyElement>>,
 2378        lines: &[LineWithInvisibles],
 2379        line_height: Pixels,
 2380        content_origin: gpui::Point<Pixels>,
 2381        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 2382        em_width: Pixels,
 2383        window: &mut Window,
 2384        cx: &mut App,
 2385    ) -> Vec<Option<CreaseTrailerLayout>> {
 2386        trailers
 2387            .into_iter()
 2388            .enumerate()
 2389            .map(|(ix, element)| {
 2390                let mut element = element?;
 2391                let available_space = size(
 2392                    AvailableSpace::MinContent,
 2393                    AvailableSpace::Definite(line_height),
 2394                );
 2395                let size = element.layout_as_root(available_space, window, cx);
 2396
 2397                let line = &lines[ix];
 2398                let padding = if line.width == Pixels::ZERO {
 2399                    Pixels::ZERO
 2400                } else {
 2401                    4. * em_width
 2402                };
 2403                let position = point(
 2404                    Pixels::from(scroll_pixel_position.x) + line.width + padding,
 2405                    ix as f32 * line_height
 2406                        - (scroll_pixel_position.y % ScrollPixelOffset::from(line_height)).into(),
 2407                );
 2408                let centering_offset = point(px(0.), (line_height - size.height) / 2.);
 2409                let origin = content_origin + position + centering_offset;
 2410                element.prepaint_as_root(origin, available_space, window, cx);
 2411                Some(CreaseTrailerLayout {
 2412                    element,
 2413                    bounds: Bounds::new(origin, size),
 2414                })
 2415            })
 2416            .collect()
 2417    }
 2418
 2419    // Folds contained in a hunk are ignored apart from shrinking visual size
 2420    // If a fold contains any hunks then that fold line is marked as modified
 2421    fn layout_gutter_diff_hunks(
 2422        &self,
 2423        line_height: Pixels,
 2424        gutter_hitbox: &Hitbox,
 2425        display_rows: Range<DisplayRow>,
 2426        snapshot: &EditorSnapshot,
 2427        window: &mut Window,
 2428        cx: &mut App,
 2429    ) -> Vec<(DisplayDiffHunk, Option<Hitbox>)> {
 2430        let folded_buffers = self.editor.read(cx).folded_buffers(cx);
 2431        let mut display_hunks = snapshot
 2432            .display_diff_hunks_for_rows(display_rows, folded_buffers)
 2433            .map(|hunk| (hunk, None))
 2434            .collect::<Vec<_>>();
 2435        let git_gutter_setting = ProjectSettings::get_global(cx).git.git_gutter;
 2436        if let GitGutterSetting::TrackedFiles = git_gutter_setting {
 2437            for (hunk, hitbox) in &mut display_hunks {
 2438                if matches!(hunk, DisplayDiffHunk::Unfolded { .. }) {
 2439                    let hunk_bounds =
 2440                        Self::diff_hunk_bounds(snapshot, line_height, gutter_hitbox.bounds, hunk);
 2441                    *hitbox = Some(window.insert_hitbox(hunk_bounds, HitboxBehavior::BlockMouse));
 2442                }
 2443            }
 2444        }
 2445
 2446        display_hunks
 2447    }
 2448
 2449    fn layout_inline_diagnostics(
 2450        &self,
 2451        line_layouts: &[LineWithInvisibles],
 2452        crease_trailers: &[Option<CreaseTrailerLayout>],
 2453        row_block_types: &HashMap<DisplayRow, bool>,
 2454        content_origin: gpui::Point<Pixels>,
 2455        scroll_position: gpui::Point<ScrollOffset>,
 2456        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 2457        edit_prediction_popover_origin: Option<gpui::Point<Pixels>>,
 2458        start_row: DisplayRow,
 2459        end_row: DisplayRow,
 2460        line_height: Pixels,
 2461        em_width: Pixels,
 2462        style: &EditorStyle,
 2463        window: &mut Window,
 2464        cx: &mut App,
 2465    ) -> HashMap<DisplayRow, AnyElement> {
 2466        let max_severity = match self
 2467            .editor
 2468            .read(cx)
 2469            .inline_diagnostics_enabled()
 2470            .then(|| {
 2471                ProjectSettings::get_global(cx)
 2472                    .diagnostics
 2473                    .inline
 2474                    .max_severity
 2475                    .unwrap_or_else(|| self.editor.read(cx).diagnostics_max_severity)
 2476                    .into_lsp()
 2477            })
 2478            .flatten()
 2479        {
 2480            Some(max_severity) => max_severity,
 2481            None => return HashMap::default(),
 2482        };
 2483
 2484        let active_diagnostics_group =
 2485            if let ActiveDiagnostic::Group(group) = &self.editor.read(cx).active_diagnostics {
 2486                Some(group.group_id)
 2487            } else {
 2488                None
 2489            };
 2490
 2491        let diagnostics_by_rows = self.editor.update(cx, |editor, cx| {
 2492            let snapshot = editor.snapshot(window, cx);
 2493            editor
 2494                .inline_diagnostics
 2495                .iter()
 2496                .filter(|(_, diagnostic)| diagnostic.severity <= max_severity)
 2497                .filter(|(_, diagnostic)| match active_diagnostics_group {
 2498                    Some(active_diagnostics_group) => {
 2499                        // Active diagnostics are all shown in the editor already, no need to display them inline
 2500                        diagnostic.group_id != active_diagnostics_group
 2501                    }
 2502                    None => true,
 2503                })
 2504                .map(|(point, diag)| (point.to_display_point(&snapshot), diag.clone()))
 2505                .skip_while(|(point, _)| point.row() < start_row)
 2506                .take_while(|(point, _)| point.row() < end_row)
 2507                .filter(|(point, _)| !row_block_types.contains_key(&point.row()))
 2508                .fold(HashMap::default(), |mut acc, (point, diagnostic)| {
 2509                    acc.entry(point.row())
 2510                        .or_insert_with(Vec::new)
 2511                        .push(diagnostic);
 2512                    acc
 2513                })
 2514        });
 2515
 2516        if diagnostics_by_rows.is_empty() {
 2517            return HashMap::default();
 2518        }
 2519
 2520        let severity_to_color = |sev: &lsp::DiagnosticSeverity| match sev {
 2521            &lsp::DiagnosticSeverity::ERROR => Color::Error,
 2522            &lsp::DiagnosticSeverity::WARNING => Color::Warning,
 2523            &lsp::DiagnosticSeverity::INFORMATION => Color::Info,
 2524            &lsp::DiagnosticSeverity::HINT => Color::Hint,
 2525            _ => Color::Error,
 2526        };
 2527
 2528        let padding = ProjectSettings::get_global(cx).diagnostics.inline.padding as f32 * em_width;
 2529        let min_x = column_pixels(
 2530            &self.style,
 2531            ProjectSettings::get_global(cx)
 2532                .diagnostics
 2533                .inline
 2534                .min_column as usize,
 2535            window,
 2536        );
 2537
 2538        let mut elements = HashMap::default();
 2539        for (row, mut diagnostics) in diagnostics_by_rows {
 2540            diagnostics.sort_by_key(|diagnostic| {
 2541                (
 2542                    diagnostic.severity,
 2543                    std::cmp::Reverse(diagnostic.is_primary),
 2544                    diagnostic.start.row,
 2545                    diagnostic.start.column,
 2546                )
 2547            });
 2548
 2549            let Some(diagnostic_to_render) = diagnostics
 2550                .iter()
 2551                .find(|diagnostic| diagnostic.is_primary)
 2552                .or_else(|| diagnostics.first())
 2553            else {
 2554                continue;
 2555            };
 2556
 2557            let pos_y = content_origin.y + line_height * (row.0 as f64 - scroll_position.y) as f32;
 2558
 2559            let window_ix = row.0.saturating_sub(start_row.0) as usize;
 2560            let pos_x = {
 2561                let crease_trailer_layout = &crease_trailers[window_ix];
 2562                let line_layout = &line_layouts[window_ix];
 2563
 2564                let line_end = if let Some(crease_trailer) = crease_trailer_layout {
 2565                    crease_trailer.bounds.right()
 2566                } else {
 2567                    Pixels::from(
 2568                        ScrollPixelOffset::from(content_origin.x + line_layout.width)
 2569                            - scroll_pixel_position.x,
 2570                    )
 2571                };
 2572
 2573                let padded_line = line_end + padding;
 2574                let min_start = Pixels::from(
 2575                    ScrollPixelOffset::from(content_origin.x + min_x) - scroll_pixel_position.x,
 2576                );
 2577
 2578                cmp::max(padded_line, min_start)
 2579            };
 2580
 2581            let behind_edit_prediction_popover = edit_prediction_popover_origin
 2582                .as_ref()
 2583                .is_some_and(|edit_prediction_popover_origin| {
 2584                    (pos_y..pos_y + line_height).contains(&edit_prediction_popover_origin.y)
 2585                });
 2586            let opacity = if behind_edit_prediction_popover {
 2587                0.5
 2588            } else {
 2589                1.0
 2590            };
 2591
 2592            let mut element = h_flex()
 2593                .id(("diagnostic", row.0))
 2594                .h(line_height)
 2595                .w_full()
 2596                .px_1()
 2597                .rounded_xs()
 2598                .opacity(opacity)
 2599                .bg(severity_to_color(&diagnostic_to_render.severity)
 2600                    .color(cx)
 2601                    .opacity(0.05))
 2602                .text_color(severity_to_color(&diagnostic_to_render.severity).color(cx))
 2603                .text_sm()
 2604                .font(style.text.font())
 2605                .child(diagnostic_to_render.message.clone())
 2606                .into_any();
 2607
 2608            element.prepaint_as_root(point(pos_x, pos_y), AvailableSpace::min_size(), window, cx);
 2609
 2610            elements.insert(row, element);
 2611        }
 2612
 2613        elements
 2614    }
 2615
 2616    fn layout_inline_code_actions(
 2617        &self,
 2618        display_point: DisplayPoint,
 2619        content_origin: gpui::Point<Pixels>,
 2620        scroll_position: gpui::Point<ScrollOffset>,
 2621        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 2622        line_height: Pixels,
 2623        snapshot: &EditorSnapshot,
 2624        window: &mut Window,
 2625        cx: &mut App,
 2626    ) -> Option<AnyElement> {
 2627        // Don't show code actions in split diff view
 2628        if self.split_side.is_some() {
 2629            return None;
 2630        }
 2631
 2632        if !snapshot
 2633            .show_code_actions
 2634            .unwrap_or(EditorSettings::get_global(cx).inline_code_actions)
 2635        {
 2636            return None;
 2637        }
 2638
 2639        let icon_size = ui::IconSize::XSmall;
 2640        let mut button = self.editor.update(cx, |editor, cx| {
 2641            if !editor.has_available_code_actions_for_selection() {
 2642                return None;
 2643            }
 2644            let active = editor
 2645                .context_menu
 2646                .borrow()
 2647                .as_ref()
 2648                .and_then(|menu| {
 2649                    if let crate::CodeContextMenu::CodeActions(CodeActionsMenu {
 2650                        deployed_from,
 2651                        ..
 2652                    }) = menu
 2653                    {
 2654                        deployed_from.as_ref()
 2655                    } else {
 2656                        None
 2657                    }
 2658                })
 2659                .is_some_and(|source| matches!(source, CodeActionSource::Indicator(..)));
 2660            Some(editor.render_inline_code_actions(icon_size, display_point.row(), active, cx))
 2661        })?;
 2662
 2663        let buffer_point = display_point.to_point(&snapshot.display_snapshot);
 2664
 2665        // do not show code action for folded line
 2666        if snapshot.is_line_folded(MultiBufferRow(buffer_point.row)) {
 2667            return None;
 2668        }
 2669
 2670        // do not show code action for blank line with cursor
 2671        let line_indent = snapshot
 2672            .display_snapshot
 2673            .buffer_snapshot()
 2674            .line_indent_for_row(MultiBufferRow(buffer_point.row));
 2675        if line_indent.is_line_blank() {
 2676            return None;
 2677        }
 2678
 2679        const INLINE_SLOT_CHAR_LIMIT: u32 = 4;
 2680        const MAX_ALTERNATE_DISTANCE: u32 = 8;
 2681
 2682        let is_valid_row = |row_candidate: u32| -> bool {
 2683            // move to other row if folded row
 2684            if snapshot.is_line_folded(MultiBufferRow(row_candidate)) {
 2685                return false;
 2686            }
 2687            if buffer_point.row == row_candidate {
 2688                // move to other row if cursor is in slot
 2689                if buffer_point.column < INLINE_SLOT_CHAR_LIMIT {
 2690                    return false;
 2691                }
 2692            } else {
 2693                let candidate_point = MultiBufferPoint {
 2694                    row: row_candidate,
 2695                    column: 0,
 2696                };
 2697                // move to other row if different excerpt
 2698                let range = if candidate_point < buffer_point {
 2699                    candidate_point..buffer_point
 2700                } else {
 2701                    buffer_point..candidate_point
 2702                };
 2703                if snapshot
 2704                    .display_snapshot
 2705                    .buffer_snapshot()
 2706                    .excerpt_containing(range)
 2707                    .is_none()
 2708                {
 2709                    return false;
 2710                }
 2711            }
 2712            let line_indent = snapshot
 2713                .display_snapshot
 2714                .buffer_snapshot()
 2715                .line_indent_for_row(MultiBufferRow(row_candidate));
 2716            // use this row if it's blank
 2717            if line_indent.is_line_blank() {
 2718                true
 2719            } else {
 2720                // use this row if code starts after slot
 2721                let indent_size = snapshot
 2722                    .display_snapshot
 2723                    .buffer_snapshot()
 2724                    .indent_size_for_line(MultiBufferRow(row_candidate));
 2725                indent_size.len >= INLINE_SLOT_CHAR_LIMIT
 2726            }
 2727        };
 2728
 2729        let new_buffer_row = if is_valid_row(buffer_point.row) {
 2730            Some(buffer_point.row)
 2731        } else {
 2732            let max_row = snapshot.display_snapshot.buffer_snapshot().max_point().row;
 2733            (1..=MAX_ALTERNATE_DISTANCE).find_map(|offset| {
 2734                let row_above = buffer_point.row.saturating_sub(offset);
 2735                let row_below = buffer_point.row + offset;
 2736                if row_above != buffer_point.row && is_valid_row(row_above) {
 2737                    Some(row_above)
 2738                } else if row_below <= max_row && is_valid_row(row_below) {
 2739                    Some(row_below)
 2740                } else {
 2741                    None
 2742                }
 2743            })
 2744        }?;
 2745
 2746        let new_display_row = snapshot
 2747            .display_snapshot
 2748            .point_to_display_point(
 2749                Point {
 2750                    row: new_buffer_row,
 2751                    column: buffer_point.column,
 2752                },
 2753                text::Bias::Left,
 2754            )
 2755            .row();
 2756
 2757        let start_y = content_origin.y
 2758            + (((new_display_row.as_f64() - scroll_position.y) as f32) * line_height)
 2759            + (line_height / 2.0)
 2760            - (icon_size.square(window, cx) / 2.);
 2761        let start_x = (ScrollPixelOffset::from(content_origin.x) - scroll_pixel_position.x
 2762            + ScrollPixelOffset::from(window.rem_size() * 0.1))
 2763        .into();
 2764
 2765        let absolute_offset = gpui::point(start_x, start_y);
 2766        button.layout_as_root(gpui::AvailableSpace::min_size(), window, cx);
 2767        button.prepaint_as_root(
 2768            absolute_offset,
 2769            gpui::AvailableSpace::min_size(),
 2770            window,
 2771            cx,
 2772        );
 2773        Some(button)
 2774    }
 2775
 2776    fn layout_inline_blame(
 2777        &self,
 2778        display_row: DisplayRow,
 2779        row_info: &RowInfo,
 2780        line_layout: &LineWithInvisibles,
 2781        crease_trailer: Option<&CreaseTrailerLayout>,
 2782        em_width: Pixels,
 2783        content_origin: gpui::Point<Pixels>,
 2784        scroll_position: gpui::Point<ScrollOffset>,
 2785        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 2786        line_height: Pixels,
 2787        window: &mut Window,
 2788        cx: &mut App,
 2789    ) -> Option<InlineBlameLayout> {
 2790        if !self
 2791            .editor
 2792            .update(cx, |editor, cx| editor.render_git_blame_inline(window, cx))
 2793        {
 2794            return None;
 2795        }
 2796
 2797        let editor = self.editor.read(cx);
 2798        let blame = editor.blame.clone()?;
 2799        let padding = {
 2800            const INLINE_ACCEPT_SUGGESTION_EM_WIDTHS: f32 = 14.;
 2801
 2802            let mut padding = ProjectSettings::get_global(cx).git.inline_blame.padding as f32;
 2803
 2804            if let Some(edit_prediction) = editor.active_edit_prediction.as_ref()
 2805                && let EditPrediction::Edit {
 2806                    display_mode: EditDisplayMode::TabAccept,
 2807                    ..
 2808                } = &edit_prediction.completion
 2809            {
 2810                padding += INLINE_ACCEPT_SUGGESTION_EM_WIDTHS
 2811            }
 2812
 2813            padding * em_width
 2814        };
 2815
 2816        let (buffer_id, entry) = blame
 2817            .update(cx, |blame, cx| {
 2818                blame.blame_for_rows(&[*row_info], cx).next()
 2819            })
 2820            .flatten()?;
 2821
 2822        let mut element = render_inline_blame_entry(entry.clone(), &self.style, cx)?;
 2823
 2824        let start_y =
 2825            content_origin.y + line_height * ((display_row.as_f64() - scroll_position.y) as f32);
 2826
 2827        let start_x = {
 2828            let line_end = if let Some(crease_trailer) = crease_trailer {
 2829                crease_trailer.bounds.right()
 2830            } else {
 2831                Pixels::from(
 2832                    ScrollPixelOffset::from(content_origin.x + line_layout.width)
 2833                        - scroll_pixel_position.x,
 2834                )
 2835            };
 2836
 2837            let padded_line_end = line_end + padding;
 2838
 2839            let min_column_in_pixels = column_pixels(
 2840                &self.style,
 2841                ProjectSettings::get_global(cx).git.inline_blame.min_column as usize,
 2842                window,
 2843            );
 2844            let min_start = Pixels::from(
 2845                ScrollPixelOffset::from(content_origin.x + min_column_in_pixels)
 2846                    - scroll_pixel_position.x,
 2847            );
 2848
 2849            cmp::max(padded_line_end, min_start)
 2850        };
 2851
 2852        let absolute_offset = point(start_x, start_y);
 2853        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 2854        let bounds = Bounds::new(absolute_offset, size);
 2855
 2856        element.prepaint_as_root(absolute_offset, AvailableSpace::min_size(), window, cx);
 2857
 2858        Some(InlineBlameLayout {
 2859            element,
 2860            bounds,
 2861            buffer_id,
 2862            entry,
 2863        })
 2864    }
 2865
 2866    fn layout_blame_popover(
 2867        &self,
 2868        editor_snapshot: &EditorSnapshot,
 2869        text_hitbox: &Hitbox,
 2870        line_height: Pixels,
 2871        window: &mut Window,
 2872        cx: &mut App,
 2873    ) {
 2874        if !self.editor.read(cx).inline_blame_popover.is_some() {
 2875            return;
 2876        }
 2877
 2878        let Some(blame) = self.editor.read(cx).blame.clone() else {
 2879            return;
 2880        };
 2881        let cursor_point = self
 2882            .editor
 2883            .read(cx)
 2884            .selections
 2885            .newest::<language::Point>(&editor_snapshot.display_snapshot)
 2886            .head();
 2887
 2888        let Some((buffer, buffer_point)) = editor_snapshot
 2889            .buffer_snapshot()
 2890            .point_to_buffer_point(cursor_point)
 2891        else {
 2892            return;
 2893        };
 2894
 2895        let row_info = RowInfo {
 2896            buffer_id: Some(buffer.remote_id()),
 2897            buffer_row: Some(buffer_point.row),
 2898            ..Default::default()
 2899        };
 2900
 2901        let Some((buffer_id, blame_entry)) = blame
 2902            .update(cx, |blame, cx| blame.blame_for_rows(&[row_info], cx).next())
 2903            .flatten()
 2904        else {
 2905            return;
 2906        };
 2907
 2908        let Some((popover_state, target_point)) = self.editor.read_with(cx, |editor, _| {
 2909            editor
 2910                .inline_blame_popover
 2911                .as_ref()
 2912                .map(|state| (state.popover_state.clone(), state.position))
 2913        }) else {
 2914            return;
 2915        };
 2916
 2917        let workspace = self
 2918            .editor
 2919            .read_with(cx, |editor, _| editor.workspace().map(|w| w.downgrade()));
 2920
 2921        let maybe_element = workspace.and_then(|workspace| {
 2922            render_blame_entry_popover(
 2923                blame_entry,
 2924                popover_state.scroll_handle,
 2925                popover_state.commit_message,
 2926                popover_state.markdown,
 2927                workspace,
 2928                &blame,
 2929                buffer_id,
 2930                window,
 2931                cx,
 2932            )
 2933        });
 2934
 2935        if let Some(mut element) = maybe_element {
 2936            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 2937            let overall_height = size.height + HOVER_POPOVER_GAP;
 2938            let popover_origin = if target_point.y > overall_height {
 2939                point(target_point.x, target_point.y - size.height)
 2940            } else {
 2941                point(
 2942                    target_point.x,
 2943                    target_point.y + line_height + HOVER_POPOVER_GAP,
 2944                )
 2945            };
 2946
 2947            let horizontal_offset = (text_hitbox.top_right().x
 2948                - POPOVER_RIGHT_OFFSET
 2949                - (popover_origin.x + size.width))
 2950                .min(Pixels::ZERO);
 2951
 2952            let origin = point(popover_origin.x + horizontal_offset, popover_origin.y);
 2953            let popover_bounds = Bounds::new(origin, size);
 2954
 2955            self.editor.update(cx, |editor, _| {
 2956                if let Some(state) = &mut editor.inline_blame_popover {
 2957                    state.popover_bounds = Some(popover_bounds);
 2958                }
 2959            });
 2960
 2961            window.defer_draw(element, origin, 2, None);
 2962        }
 2963    }
 2964
 2965    fn layout_blame_entries(
 2966        &self,
 2967        buffer_rows: &[RowInfo],
 2968        em_width: Pixels,
 2969        scroll_position: gpui::Point<ScrollOffset>,
 2970        line_height: Pixels,
 2971        gutter_hitbox: &Hitbox,
 2972        max_width: Option<Pixels>,
 2973        window: &mut Window,
 2974        cx: &mut App,
 2975    ) -> Option<Vec<AnyElement>> {
 2976        if !self
 2977            .editor
 2978            .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
 2979        {
 2980            return None;
 2981        }
 2982
 2983        let blame = self.editor.read(cx).blame.clone()?;
 2984        let workspace = self.editor.read(cx).workspace()?;
 2985        let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
 2986            blame.blame_for_rows(buffer_rows, cx).collect()
 2987        });
 2988
 2989        let width = if let Some(max_width) = max_width {
 2990            AvailableSpace::Definite(max_width)
 2991        } else {
 2992            AvailableSpace::MaxContent
 2993        };
 2994        let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
 2995        let start_x = em_width;
 2996
 2997        let mut last_used_color: Option<(Hsla, Oid)> = None;
 2998        let blame_renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 2999
 3000        let shaped_lines = blamed_rows
 3001            .into_iter()
 3002            .enumerate()
 3003            .flat_map(|(ix, blame_entry)| {
 3004                let (buffer_id, blame_entry) = blame_entry?;
 3005                let mut element = render_blame_entry(
 3006                    ix,
 3007                    &blame,
 3008                    blame_entry,
 3009                    &self.style,
 3010                    &mut last_used_color,
 3011                    self.editor.clone(),
 3012                    workspace.clone(),
 3013                    buffer_id,
 3014                    &*blame_renderer,
 3015                    window,
 3016                    cx,
 3017                )?;
 3018
 3019                let start_y = ix as f32 * line_height
 3020                    - Pixels::from(scroll_top % ScrollPixelOffset::from(line_height));
 3021                let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
 3022
 3023                element.prepaint_as_root(
 3024                    absolute_offset,
 3025                    size(width, AvailableSpace::MinContent),
 3026                    window,
 3027                    cx,
 3028                );
 3029
 3030                Some(element)
 3031            })
 3032            .collect();
 3033
 3034        Some(shaped_lines)
 3035    }
 3036
 3037    fn layout_indent_guides(
 3038        &self,
 3039        content_origin: gpui::Point<Pixels>,
 3040        text_origin: gpui::Point<Pixels>,
 3041        visible_buffer_range: Range<MultiBufferRow>,
 3042        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 3043        line_height: Pixels,
 3044        snapshot: &DisplaySnapshot,
 3045        window: &mut Window,
 3046        cx: &mut App,
 3047    ) -> Option<Vec<IndentGuideLayout>> {
 3048        let indent_guides = self.editor.update(cx, |editor, cx| {
 3049            editor.indent_guides(visible_buffer_range, snapshot, cx)
 3050        })?;
 3051
 3052        let active_indent_guide_indices = self.editor.update(cx, |editor, cx| {
 3053            editor
 3054                .find_active_indent_guide_indices(&indent_guides, snapshot, window, cx)
 3055                .unwrap_or_default()
 3056        });
 3057
 3058        Some(
 3059            indent_guides
 3060                .into_iter()
 3061                .enumerate()
 3062                .filter_map(|(i, indent_guide)| {
 3063                    let single_indent_width =
 3064                        column_pixels(&self.style, indent_guide.tab_size as usize, window);
 3065                    let total_width = single_indent_width * indent_guide.depth as f32;
 3066                    let start_x = Pixels::from(
 3067                        ScrollOffset::from(content_origin.x + total_width)
 3068                            - scroll_pixel_position.x,
 3069                    );
 3070                    if start_x >= text_origin.x {
 3071                        let (offset_y, length, display_row_range) =
 3072                            Self::calculate_indent_guide_bounds(
 3073                                indent_guide.start_row..indent_guide.end_row,
 3074                                line_height,
 3075                                snapshot,
 3076                            );
 3077
 3078                        let start_y = Pixels::from(
 3079                            ScrollOffset::from(content_origin.y) + offset_y
 3080                                - scroll_pixel_position.y,
 3081                        );
 3082
 3083                        Some(IndentGuideLayout {
 3084                            origin: point(start_x, start_y),
 3085                            length,
 3086                            single_indent_width,
 3087                            display_row_range,
 3088                            depth: indent_guide.depth,
 3089                            active: active_indent_guide_indices.contains(&i),
 3090                            settings: indent_guide.settings,
 3091                        })
 3092                    } else {
 3093                        None
 3094                    }
 3095                })
 3096                .collect(),
 3097        )
 3098    }
 3099
 3100    fn depth_zero_indent_guide_padding_for_row(
 3101        indent_guides: &[IndentGuideLayout],
 3102        row: DisplayRow,
 3103    ) -> Pixels {
 3104        indent_guides
 3105            .iter()
 3106            .find(|guide| guide.depth == 0 && guide.display_row_range.contains(&row))
 3107            .and_then(|guide| {
 3108                guide
 3109                    .settings
 3110                    .visible_line_width(guide.active)
 3111                    .map(|width| px(width as f32 * 2.0))
 3112            })
 3113            .unwrap_or(px(0.0))
 3114    }
 3115
 3116    fn layout_wrap_guides(
 3117        &self,
 3118        em_advance: Pixels,
 3119        scroll_position: gpui::Point<f64>,
 3120        content_origin: gpui::Point<Pixels>,
 3121        scrollbar_layout: Option<&EditorScrollbars>,
 3122        vertical_scrollbar_width: Pixels,
 3123        hitbox: &Hitbox,
 3124        window: &Window,
 3125        cx: &App,
 3126    ) -> SmallVec<[(Pixels, bool); 2]> {
 3127        let scroll_left = scroll_position.x as f32 * em_advance;
 3128        let content_origin = content_origin.x;
 3129        let horizontal_offset = content_origin - scroll_left;
 3130        let vertical_scrollbar_width = scrollbar_layout
 3131            .and_then(|layout| layout.visible.then_some(vertical_scrollbar_width))
 3132            .unwrap_or_default();
 3133
 3134        self.editor
 3135            .read(cx)
 3136            .wrap_guides(cx)
 3137            .into_iter()
 3138            .flat_map(|(guide, active)| {
 3139                let wrap_position = column_pixels(&self.style, guide, window);
 3140                let wrap_guide_x = wrap_position + horizontal_offset;
 3141                let display_wrap_guide = wrap_guide_x >= content_origin
 3142                    && wrap_guide_x <= hitbox.bounds.right() - vertical_scrollbar_width;
 3143
 3144                display_wrap_guide.then_some((wrap_guide_x, active))
 3145            })
 3146            .collect()
 3147    }
 3148
 3149    fn calculate_indent_guide_bounds(
 3150        row_range: Range<MultiBufferRow>,
 3151        line_height: Pixels,
 3152        snapshot: &DisplaySnapshot,
 3153    ) -> (f64, gpui::Pixels, Range<DisplayRow>) {
 3154        let start_point = Point::new(row_range.start.0, 0);
 3155        let end_point = Point::new(row_range.end.0, 0);
 3156
 3157        let mut row_range = start_point.to_display_point(snapshot).row()
 3158            ..end_point.to_display_point(snapshot).row();
 3159
 3160        let mut prev_line = start_point;
 3161        prev_line.row = prev_line.row.saturating_sub(1);
 3162        let prev_line = prev_line.to_display_point(snapshot).row();
 3163
 3164        let mut cons_line = end_point;
 3165        cons_line.row += 1;
 3166        let cons_line = cons_line.to_display_point(snapshot).row();
 3167
 3168        let mut offset_y = row_range.start.as_f64() * f64::from(line_height);
 3169        let mut length = (cons_line.0.saturating_sub(row_range.start.0)) as f32 * line_height;
 3170
 3171        // If we are at the end of the buffer, ensure that the indent guide extends to the end of the line.
 3172        if row_range.end == cons_line {
 3173            length += line_height;
 3174        }
 3175
 3176        // If there is a block (e.g. diagnostic) in between the start of the indent guide and the line above,
 3177        // we want to extend the indent guide to the start of the block.
 3178        let mut block_height = 0;
 3179        let mut block_offset = 0;
 3180        let mut found_excerpt_header = false;
 3181        for (_, block) in snapshot.blocks_in_range(prev_line..row_range.start) {
 3182            if matches!(
 3183                block,
 3184                Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
 3185            ) {
 3186                found_excerpt_header = true;
 3187                break;
 3188            }
 3189            block_offset += block.height();
 3190            block_height += block.height();
 3191        }
 3192        if !found_excerpt_header {
 3193            offset_y -= block_offset as f64 * f64::from(line_height);
 3194            length += block_height as f32 * line_height;
 3195            row_range = DisplayRow(row_range.start.0.saturating_sub(block_offset))..row_range.end;
 3196        }
 3197
 3198        // If there is a block (e.g. diagnostic) at the end of an multibuffer excerpt,
 3199        // we want to ensure that the indent guide stops before the excerpt header.
 3200        let mut block_height = 0;
 3201        let mut found_excerpt_header = false;
 3202        for (_, block) in snapshot.blocks_in_range(row_range.end..cons_line) {
 3203            if matches!(
 3204                block,
 3205                Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
 3206            ) {
 3207                found_excerpt_header = true;
 3208            }
 3209            block_height += block.height();
 3210        }
 3211        if found_excerpt_header {
 3212            length -= block_height as f32 * line_height;
 3213        } else {
 3214            row_range = row_range.start..cons_line;
 3215        }
 3216
 3217        (offset_y, length, row_range)
 3218    }
 3219
 3220    fn layout_bookmarks(
 3221        &self,
 3222        gutter: &Gutter<'_>,
 3223        bookmarks: &HashSet<DisplayRow>,
 3224        window: &mut Window,
 3225        cx: &mut App,
 3226    ) -> Vec<AnyElement> {
 3227        if self.split_side == Some(SplitSide::Left) {
 3228            return Vec::new();
 3229        }
 3230
 3231        self.editor.update(cx, |editor, cx| {
 3232            bookmarks
 3233                .iter()
 3234                .filter_map(|row| {
 3235                    gutter.layout_item_skipping_folds(
 3236                        *row,
 3237                        |cx, _| editor.render_bookmark(*row, cx).into_any_element(),
 3238                        window,
 3239                        cx,
 3240                    )
 3241                })
 3242                .collect_vec()
 3243        })
 3244    }
 3245
 3246    fn layout_gutter_hover_button(
 3247        &self,
 3248        gutter: &Gutter,
 3249        position: Anchor,
 3250        row: DisplayRow,
 3251        window: &mut Window,
 3252        cx: &mut App,
 3253    ) -> Option<AnyElement> {
 3254        if self.split_side == Some(SplitSide::Left) {
 3255            return None;
 3256        }
 3257
 3258        self.editor.update(cx, |editor, cx| {
 3259            gutter.layout_item_skipping_folds(
 3260                row,
 3261                |cx, window| {
 3262                    editor
 3263                        .render_gutter_hover_button(position, row, window, cx)
 3264                        .into_any_element()
 3265                },
 3266                window,
 3267                cx,
 3268            )
 3269        })
 3270    }
 3271
 3272    fn layout_breakpoints(
 3273        &self,
 3274        gutter: &Gutter,
 3275        breakpoints: &HashMap<DisplayRow, (Anchor, Breakpoint, Option<BreakpointSessionState>)>,
 3276        window: &mut Window,
 3277        cx: &mut App,
 3278    ) -> Vec<AnyElement> {
 3279        if self.split_side == Some(SplitSide::Left) {
 3280            return Vec::new();
 3281        }
 3282
 3283        self.editor.update(cx, |editor, cx| {
 3284            breakpoints
 3285                .iter()
 3286                .filter_map(|(row, (text_anchor, bp, state))| {
 3287                    gutter.layout_item_skipping_folds(
 3288                        *row,
 3289                        |cx, _| {
 3290                            editor
 3291                                .render_breakpoint(*text_anchor, *row, &bp, *state, cx)
 3292                                .into_any_element()
 3293                        },
 3294                        window,
 3295                        cx,
 3296                    )
 3297                })
 3298                .collect_vec()
 3299        })
 3300    }
 3301
 3302    fn should_render_diff_review_button(
 3303        &self,
 3304        range: Range<DisplayRow>,
 3305        row_infos: &[RowInfo],
 3306        snapshot: &EditorSnapshot,
 3307        cx: &App,
 3308    ) -> Option<(DisplayRow, Option<u32>)> {
 3309        if !cx.has_flag::<DiffReviewFeatureFlag>() {
 3310            return None;
 3311        }
 3312
 3313        let show_diff_review_button = self.editor.read(cx).show_diff_review_button();
 3314        if !show_diff_review_button {
 3315            return None;
 3316        }
 3317
 3318        let indicator = self.editor.read(cx).gutter_diff_review_indicator.0?;
 3319        if !indicator.is_active {
 3320            return None;
 3321        }
 3322
 3323        let display_row = indicator
 3324            .start
 3325            .to_display_point(&snapshot.display_snapshot)
 3326            .row();
 3327        let row_index = (display_row.0.saturating_sub(range.start.0)) as usize;
 3328
 3329        let row_info = row_infos.get(row_index);
 3330        if row_info.is_some_and(|row_info| row_info.expand_info.is_some()) {
 3331            return None;
 3332        }
 3333
 3334        let buffer_id = row_info.and_then(|info| info.buffer_id);
 3335        if buffer_id.is_none() {
 3336            return None;
 3337        }
 3338
 3339        let editor = self.editor.read(cx);
 3340        if buffer_id.is_some_and(|buffer_id| editor.is_buffer_folded(buffer_id, cx)) {
 3341            return None;
 3342        }
 3343
 3344        let buffer_row = row_info.and_then(|info| info.buffer_row);
 3345        Some((display_row, buffer_row))
 3346    }
 3347
 3348    fn layout_run_indicators(
 3349        &self,
 3350        gutter: &Gutter,
 3351        run_indicators: &HashSet<DisplayRow>,
 3352        breakpoints: &HashMap<DisplayRow, (Anchor, Breakpoint, Option<BreakpointSessionState>)>,
 3353        window: &mut Window,
 3354        cx: &mut App,
 3355    ) -> Vec<AnyElement> {
 3356        if self.split_side == Some(SplitSide::Left) {
 3357            return Vec::new();
 3358        }
 3359
 3360        self.editor.update(cx, |editor, cx| {
 3361            let active_task_indicator_row =
 3362                // TODO: add edit button on the right side of each row in the context menu
 3363                if let Some(crate::CodeContextMenu::CodeActions(CodeActionsMenu {
 3364                    deployed_from,
 3365                    actions,
 3366                    ..
 3367                })) = editor.context_menu.borrow().as_ref()
 3368                {
 3369                    actions
 3370                        .tasks()
 3371                        .map(|tasks| tasks.position.to_display_point(gutter.snapshot).row())
 3372                        .or_else(|| match deployed_from {
 3373                            Some(CodeActionSource::Indicator(row)) => Some(*row),
 3374                            _ => None,
 3375                        })
 3376                } else {
 3377                    None
 3378                };
 3379
 3380            run_indicators
 3381                .iter()
 3382                .filter_map(|display_row| {
 3383                    gutter.layout_item(
 3384                        *display_row,
 3385                        |cx, _| {
 3386                            editor
 3387                                .render_run_indicator(
 3388                                    &self.style,
 3389                                    Some(*display_row) == active_task_indicator_row,
 3390                                    breakpoints.get(&display_row).map(|(anchor, _, _)| *anchor),
 3391                                    *display_row,
 3392                                    cx,
 3393                                )
 3394                                .into_any_element()
 3395                        },
 3396                        window,
 3397                        cx,
 3398                    )
 3399                })
 3400                .collect_vec()
 3401        })
 3402    }
 3403
 3404    fn layout_expand_toggles(
 3405        &self,
 3406        gutter_hitbox: &Hitbox,
 3407        gutter_dimensions: GutterDimensions,
 3408        em_width: Pixels,
 3409        line_height: Pixels,
 3410        scroll_position: gpui::Point<ScrollOffset>,
 3411        buffer_rows: &[RowInfo],
 3412        window: &mut Window,
 3413        cx: &mut App,
 3414    ) -> Vec<Option<(AnyElement, gpui::Point<Pixels>)>> {
 3415        if self.editor.read(cx).disable_expand_excerpt_buttons {
 3416            return vec![];
 3417        }
 3418
 3419        let editor_font_size = self.style.text.font_size.to_pixels(window.rem_size()) * 1.2;
 3420
 3421        let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
 3422
 3423        let max_line_number_length = self
 3424            .editor
 3425            .read(cx)
 3426            .buffer()
 3427            .read(cx)
 3428            .snapshot(cx)
 3429            .widest_line_number()
 3430            .ilog10()
 3431            + 1;
 3432
 3433        let git_gutter_width = Self::gutter_strip_width(line_height)
 3434            + gutter_dimensions
 3435                .git_blame_entries_width
 3436                .unwrap_or_default();
 3437        let available_width = gutter_dimensions.left_padding - git_gutter_width;
 3438
 3439        buffer_rows
 3440            .iter()
 3441            .enumerate()
 3442            .map(|(ix, row_info)| {
 3443                let ExpandInfo {
 3444                    direction,
 3445                    start_anchor,
 3446                } = row_info.expand_info?;
 3447
 3448                let icon_name = match direction {
 3449                    ExpandExcerptDirection::Up => IconName::ExpandUp,
 3450                    ExpandExcerptDirection::Down => IconName::ExpandDown,
 3451                    ExpandExcerptDirection::UpAndDown => IconName::ExpandVertical,
 3452                };
 3453
 3454                let editor = self.editor.clone();
 3455                let is_wide = max_line_number_length
 3456                    >= EditorSettings::get_global(cx).gutter.min_line_number_digits as u32
 3457                    && row_info
 3458                        .buffer_row
 3459                        .is_some_and(|row| (row + 1).ilog10() + 1 == max_line_number_length)
 3460                    || gutter_dimensions.right_padding == px(0.);
 3461
 3462                let width = if is_wide {
 3463                    available_width - px(5.)
 3464                } else {
 3465                    available_width + em_width - px(5.)
 3466                };
 3467
 3468                let toggle = IconButton::new(("expand", ix), icon_name)
 3469                    .icon_color(Color::Custom(cx.theme().colors().editor_line_number))
 3470                    .icon_size(IconSize::Custom(rems(editor_font_size / window.rem_size())))
 3471                    .width(width)
 3472                    .on_click(move |_, window, cx| {
 3473                        editor.update(cx, |editor, cx| {
 3474                            editor.expand_excerpt(start_anchor, direction, window, cx);
 3475                        });
 3476                    })
 3477                    .tooltip(Tooltip::for_action_title(
 3478                        "Expand Excerpt",
 3479                        &crate::actions::ExpandExcerpts::default(),
 3480                    ))
 3481                    .into_any_element();
 3482
 3483                let position = point(
 3484                    git_gutter_width + px(1.),
 3485                    ix as f32 * line_height
 3486                        - Pixels::from(scroll_top % ScrollPixelOffset::from(line_height))
 3487                        + px(1.),
 3488                );
 3489                let origin = gutter_hitbox.origin + position;
 3490
 3491                Some((toggle, origin))
 3492            })
 3493            .collect()
 3494    }
 3495
 3496    fn layout_line_numbers(
 3497        &self,
 3498        gutter: &Gutter<'_>,
 3499        active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
 3500        current_selection_head: Option<DisplayRow>,
 3501        window: &mut Window,
 3502        cx: &mut App,
 3503    ) -> Arc<HashMap<MultiBufferRow, LineNumberLayout>> {
 3504        let include_line_numbers = gutter
 3505            .snapshot
 3506            .show_line_numbers
 3507            .unwrap_or_else(|| EditorSettings::get_global(cx).gutter.line_numbers);
 3508        if !include_line_numbers {
 3509            return Arc::default();
 3510        }
 3511
 3512        let relative = self.editor.read(cx).relative_line_numbers(cx);
 3513
 3514        let relative_line_numbers_enabled = relative.enabled();
 3515        let relative_rows = if relative_line_numbers_enabled
 3516            && let Some(current_selection_head) = current_selection_head
 3517        {
 3518            gutter.snapshot.calculate_relative_line_numbers(
 3519                &gutter.range,
 3520                current_selection_head,
 3521                relative.wrapped(),
 3522            )
 3523        } else {
 3524            Default::default()
 3525        };
 3526
 3527        let mut line_number = String::new();
 3528        let segments = gutter
 3529            .row_infos
 3530            .iter()
 3531            .enumerate()
 3532            .flat_map(|(ix, row_info)| {
 3533                let display_row = DisplayRow(gutter.range.start.0 + ix as u32);
 3534                line_number.clear();
 3535                let non_relative_number = if relative.wrapped() {
 3536                    row_info.buffer_row.or(row_info.wrapped_buffer_row)? + 1
 3537                } else {
 3538                    row_info.buffer_row? + 1
 3539                };
 3540                let relative_number = relative_rows.get(&display_row);
 3541                if !(relative_line_numbers_enabled && relative_number.is_some())
 3542                    && !gutter.snapshot.number_deleted_lines
 3543                    && row_info
 3544                        .diff_status
 3545                        .is_some_and(|status| status.is_deleted())
 3546                {
 3547                    return None;
 3548                }
 3549
 3550                let number = relative_number.unwrap_or(&non_relative_number);
 3551                write!(&mut line_number, "{number}").unwrap();
 3552
 3553                let color = active_rows
 3554                    .get(&display_row)
 3555                    .map(|spec| {
 3556                        if spec.breakpoint {
 3557                            cx.theme().colors().debugger_accent
 3558                        } else {
 3559                            cx.theme().colors().editor_active_line_number
 3560                        }
 3561                    })
 3562                    .unwrap_or_else(|| cx.theme().colors().editor_line_number);
 3563                let shaped_line =
 3564                    self.shape_line_number(SharedString::from(&line_number), color, window);
 3565                let scroll_top =
 3566                    gutter.scroll_position.y * ScrollPixelOffset::from(gutter.line_height);
 3567                let line_origin = gutter.hitbox.origin
 3568                    + point(
 3569                        gutter.hitbox.size.width
 3570                            - shaped_line.width
 3571                            - gutter.dimensions.right_padding,
 3572                        ix as f32 * gutter.line_height
 3573                            - Pixels::from(
 3574                                scroll_top % ScrollPixelOffset::from(gutter.line_height),
 3575                            ),
 3576                    );
 3577
 3578                #[cfg(not(test))]
 3579                let hitbox = Some(window.insert_hitbox(
 3580                    Bounds::new(line_origin, size(shaped_line.width, gutter.line_height)),
 3581                    HitboxBehavior::Normal,
 3582                ));
 3583                #[cfg(test)]
 3584                let hitbox = {
 3585                    let _ = line_origin;
 3586                    None
 3587                };
 3588
 3589                let segment = LineNumberSegment {
 3590                    shaped_line,
 3591                    hitbox,
 3592                };
 3593
 3594                let buffer_row = DisplayPoint::new(display_row, 0)
 3595                    .to_point(gutter.snapshot)
 3596                    .row;
 3597                let multi_buffer_row = MultiBufferRow(buffer_row);
 3598
 3599                Some((multi_buffer_row, segment))
 3600            });
 3601
 3602        let mut line_numbers: HashMap<MultiBufferRow, LineNumberLayout> = HashMap::default();
 3603        for (buffer_row, segment) in segments {
 3604            line_numbers
 3605                .entry(buffer_row)
 3606                .or_insert_with(|| LineNumberLayout {
 3607                    segments: Default::default(),
 3608                })
 3609                .segments
 3610                .push(segment);
 3611        }
 3612        Arc::new(line_numbers)
 3613    }
 3614
 3615    fn layout_crease_toggles(
 3616        &self,
 3617        rows: Range<DisplayRow>,
 3618        row_infos: &[RowInfo],
 3619        active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
 3620        snapshot: &EditorSnapshot,
 3621        window: &mut Window,
 3622        cx: &mut App,
 3623    ) -> Vec<Option<AnyElement>> {
 3624        let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
 3625            && snapshot.mode.is_full()
 3626            && self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
 3627        if include_fold_statuses {
 3628            row_infos
 3629                .iter()
 3630                .enumerate()
 3631                .map(|(ix, info)| {
 3632                    if info.expand_info.is_some() {
 3633                        return None;
 3634                    }
 3635                    let row = info.multibuffer_row?;
 3636                    let display_row = DisplayRow(rows.start.0 + ix as u32);
 3637                    let active = active_rows.contains_key(&display_row);
 3638
 3639                    snapshot.render_crease_toggle(row, active, self.editor.clone(), window, cx)
 3640                })
 3641                .collect()
 3642        } else {
 3643            Vec::new()
 3644        }
 3645    }
 3646
 3647    fn layout_crease_trailers(
 3648        &self,
 3649        buffer_rows: impl IntoIterator<Item = RowInfo>,
 3650        snapshot: &EditorSnapshot,
 3651        window: &mut Window,
 3652        cx: &mut App,
 3653    ) -> Vec<Option<AnyElement>> {
 3654        buffer_rows
 3655            .into_iter()
 3656            .map(|row_info| {
 3657                if row_info.expand_info.is_some() {
 3658                    return None;
 3659                }
 3660                if let Some(row) = row_info.multibuffer_row {
 3661                    snapshot.render_crease_trailer(row, window, cx)
 3662                } else {
 3663                    None
 3664                }
 3665            })
 3666            .collect()
 3667    }
 3668
 3669    fn bg_segments_per_row(
 3670        rows: Range<DisplayRow>,
 3671        selections: &[(PlayerColor, Vec<SelectionLayout>)],
 3672        highlight_ranges: &[(Range<DisplayPoint>, Hsla)],
 3673        base_background: Hsla,
 3674    ) -> Vec<Vec<(Range<DisplayPoint>, Hsla)>> {
 3675        if rows.start >= rows.end {
 3676            return Vec::new();
 3677        }
 3678        if !base_background.is_opaque() {
 3679            // We don't actually know what color is behind this editor.
 3680            return Vec::new();
 3681        }
 3682        let highlight_iter = highlight_ranges.iter().cloned();
 3683        let selection_iter = selections.iter().flat_map(|(player_color, layouts)| {
 3684            let color = player_color.selection;
 3685            layouts.iter().filter_map(move |selection_layout| {
 3686                if selection_layout.range.start != selection_layout.range.end {
 3687                    Some((selection_layout.range.clone(), color))
 3688                } else {
 3689                    None
 3690                }
 3691            })
 3692        });
 3693        let mut per_row_map = vec![Vec::new(); rows.len()];
 3694        for (range, color) in highlight_iter.chain(selection_iter) {
 3695            let covered_rows = if range.end.column() == 0 {
 3696                cmp::max(range.start.row(), rows.start)..cmp::min(range.end.row(), rows.end)
 3697            } else {
 3698                cmp::max(range.start.row(), rows.start)
 3699                    ..cmp::min(range.end.row().next_row(), rows.end)
 3700            };
 3701            for row in covered_rows.iter_rows() {
 3702                let seg_start = if row == range.start.row() {
 3703                    range.start
 3704                } else {
 3705                    DisplayPoint::new(row, 0)
 3706                };
 3707                let seg_end = if row == range.end.row() && range.end.column() != 0 {
 3708                    range.end
 3709                } else {
 3710                    DisplayPoint::new(row, u32::MAX)
 3711                };
 3712                let ix = row.minus(rows.start) as usize;
 3713                debug_assert!(row >= rows.start && row < rows.end);
 3714                debug_assert!(ix < per_row_map.len());
 3715                per_row_map[ix].push((seg_start..seg_end, color));
 3716            }
 3717        }
 3718        for row_segments in per_row_map.iter_mut() {
 3719            if row_segments.is_empty() {
 3720                continue;
 3721            }
 3722            let segments = mem::take(row_segments);
 3723            let merged = Self::merge_overlapping_ranges(segments, base_background);
 3724            *row_segments = merged;
 3725        }
 3726        per_row_map
 3727    }
 3728
 3729    /// Merge overlapping ranges by splitting at all range boundaries and blending colors where
 3730    /// multiple ranges overlap. The result contains non-overlapping ranges ordered from left to right.
 3731    ///
 3732    /// Expects `start.row() == end.row()` for each range.
 3733    fn merge_overlapping_ranges(
 3734        ranges: Vec<(Range<DisplayPoint>, Hsla)>,
 3735        base_background: Hsla,
 3736    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
 3737        struct Boundary {
 3738            pos: DisplayPoint,
 3739            is_start: bool,
 3740            index: usize,
 3741            color: Hsla,
 3742        }
 3743
 3744        let mut boundaries: SmallVec<[Boundary; 16]> = SmallVec::with_capacity(ranges.len() * 2);
 3745        for (index, (range, color)) in ranges.iter().enumerate() {
 3746            debug_assert!(
 3747                range.start.row() == range.end.row(),
 3748                "expects single-row ranges"
 3749            );
 3750            if range.start < range.end {
 3751                boundaries.push(Boundary {
 3752                    pos: range.start,
 3753                    is_start: true,
 3754                    index,
 3755                    color: *color,
 3756                });
 3757                boundaries.push(Boundary {
 3758                    pos: range.end,
 3759                    is_start: false,
 3760                    index,
 3761                    color: *color,
 3762                });
 3763            }
 3764        }
 3765
 3766        if boundaries.is_empty() {
 3767            return Vec::new();
 3768        }
 3769
 3770        boundaries
 3771            .sort_unstable_by(|a, b| a.pos.cmp(&b.pos).then_with(|| a.is_start.cmp(&b.is_start)));
 3772
 3773        let mut processed_ranges: Vec<(Range<DisplayPoint>, Hsla)> = Vec::new();
 3774        let mut active_ranges: SmallVec<[(usize, Hsla); 8]> = SmallVec::new();
 3775
 3776        let mut i = 0;
 3777        let mut start_pos = boundaries[0].pos;
 3778
 3779        let boundaries_len = boundaries.len();
 3780        while i < boundaries_len {
 3781            let current_boundary_pos = boundaries[i].pos;
 3782            if start_pos < current_boundary_pos {
 3783                if !active_ranges.is_empty() {
 3784                    let mut color = base_background;
 3785                    for &(_, c) in &active_ranges {
 3786                        color = Hsla::blend(color, c);
 3787                    }
 3788                    if let Some((last_range, last_color)) = processed_ranges.last_mut() {
 3789                        if *last_color == color && last_range.end == start_pos {
 3790                            last_range.end = current_boundary_pos;
 3791                        } else {
 3792                            processed_ranges.push((start_pos..current_boundary_pos, color));
 3793                        }
 3794                    } else {
 3795                        processed_ranges.push((start_pos..current_boundary_pos, color));
 3796                    }
 3797                }
 3798            }
 3799            while i < boundaries_len && boundaries[i].pos == current_boundary_pos {
 3800                let active_range = &boundaries[i];
 3801                if active_range.is_start {
 3802                    let idx = active_range.index;
 3803                    let pos = active_ranges
 3804                        .binary_search_by_key(&idx, |(i, _)| *i)
 3805                        .unwrap_or_else(|p| p);
 3806                    active_ranges.insert(pos, (idx, active_range.color));
 3807                } else {
 3808                    let idx = active_range.index;
 3809                    if let Ok(pos) = active_ranges.binary_search_by_key(&idx, |(i, _)| *i) {
 3810                        active_ranges.remove(pos);
 3811                    }
 3812                }
 3813                i += 1;
 3814            }
 3815            start_pos = current_boundary_pos;
 3816        }
 3817
 3818        processed_ranges
 3819    }
 3820
 3821    fn layout_lines(
 3822        rows: Range<DisplayRow>,
 3823        snapshot: &EditorSnapshot,
 3824        style: &EditorStyle,
 3825        editor_width: Pixels,
 3826        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 3827        bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
 3828        window: &mut Window,
 3829        cx: &mut App,
 3830    ) -> Vec<LineWithInvisibles> {
 3831        if rows.start >= rows.end {
 3832            return Vec::new();
 3833        }
 3834
 3835        // Show the placeholder when the editor is empty
 3836        if snapshot.is_empty() {
 3837            let font_size = style.text.font_size.to_pixels(window.rem_size());
 3838            let placeholder_color = cx.theme().colors().text_placeholder;
 3839            let placeholder_text = snapshot.placeholder_text();
 3840
 3841            let placeholder_lines = placeholder_text
 3842                .as_ref()
 3843                .map_or(Vec::new(), |text| text.split('\n').collect::<Vec<_>>());
 3844
 3845            let placeholder_line_count = placeholder_lines.len();
 3846
 3847            placeholder_lines
 3848                .into_iter()
 3849                .skip(rows.start.0 as usize)
 3850                .chain(iter::repeat(""))
 3851                .take(cmp::max(rows.len(), placeholder_line_count))
 3852                .map(move |line| {
 3853                    let run = TextRun {
 3854                        len: line.len(),
 3855                        font: style.text.font(),
 3856                        color: placeholder_color,
 3857                        ..Default::default()
 3858                    };
 3859                    let line = window.text_system().shape_line(
 3860                        line.to_string().into(),
 3861                        font_size,
 3862                        &[run],
 3863                        None,
 3864                    );
 3865                    LineWithInvisibles {
 3866                        width: line.width,
 3867                        len: line.len,
 3868                        fragments: smallvec![LineFragment::Text(line)],
 3869                        invisibles: Vec::new(),
 3870                        font_size,
 3871                    }
 3872                })
 3873                .collect()
 3874        } else {
 3875            let use_tree_sitter = !snapshot.semantic_tokens_enabled
 3876                || snapshot.use_tree_sitter_for_syntax(rows.start, cx);
 3877            let language_aware = LanguageAwareStyling {
 3878                tree_sitter: use_tree_sitter,
 3879                diagnostics: true,
 3880            };
 3881            let chunks = snapshot.highlighted_chunks(rows.clone(), language_aware, style);
 3882            LineWithInvisibles::from_chunks(
 3883                chunks,
 3884                style,
 3885                MAX_LINE_LEN,
 3886                rows.len(),
 3887                &snapshot.mode,
 3888                editor_width,
 3889                is_row_soft_wrapped,
 3890                bg_segments_per_row,
 3891                window,
 3892                cx,
 3893            )
 3894        }
 3895    }
 3896
 3897    fn prepaint_lines(
 3898        &self,
 3899        start_row: DisplayRow,
 3900        line_layouts: &mut [LineWithInvisibles],
 3901        line_height: Pixels,
 3902        scroll_position: gpui::Point<ScrollOffset>,
 3903        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 3904        content_origin: gpui::Point<Pixels>,
 3905        window: &mut Window,
 3906        cx: &mut App,
 3907    ) -> SmallVec<[AnyElement; 1]> {
 3908        let mut line_elements = SmallVec::new();
 3909        for (ix, line) in line_layouts.iter_mut().enumerate() {
 3910            let row = start_row + DisplayRow(ix as u32);
 3911            line.prepaint(
 3912                line_height,
 3913                scroll_position,
 3914                scroll_pixel_position,
 3915                row,
 3916                content_origin,
 3917                &mut line_elements,
 3918                window,
 3919                cx,
 3920            );
 3921        }
 3922        line_elements
 3923    }
 3924
 3925    fn render_block(
 3926        &self,
 3927        block: &Block,
 3928        available_width: AvailableSpace,
 3929        block_id: BlockId,
 3930        block_row_start: DisplayRow,
 3931        snapshot: &EditorSnapshot,
 3932        text_x: Pixels,
 3933        rows: &Range<DisplayRow>,
 3934        line_layouts: &[LineWithInvisibles],
 3935        editor_margins: &EditorMargins,
 3936        line_height: Pixels,
 3937        em_width: Pixels,
 3938        text_hitbox: &Hitbox,
 3939        editor_width: Pixels,
 3940        scroll_width: &mut Pixels,
 3941        resized_blocks: &mut HashMap<CustomBlockId, u32>,
 3942        row_block_types: &mut HashMap<DisplayRow, bool>,
 3943        selections: &[Selection<Point>],
 3944        selected_buffer_ids: &Vec<BufferId>,
 3945        latest_selection_anchors: &HashMap<BufferId, Anchor>,
 3946        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 3947        sticky_header_excerpt_id: Option<BufferId>,
 3948        indent_guides: &Option<Vec<IndentGuideLayout>>,
 3949        block_resize_offset: &mut i32,
 3950        window: &mut Window,
 3951        cx: &mut App,
 3952    ) -> Option<(AnyElement, Size<Pixels>, DisplayRow, Pixels)> {
 3953        let mut x_position = None;
 3954        let mut element = match block {
 3955            Block::Custom(custom) => {
 3956                let block_start = custom.start().to_point(&snapshot.buffer_snapshot());
 3957                let block_end = custom.end().to_point(&snapshot.buffer_snapshot());
 3958                if block.place_near() && snapshot.is_line_folded(MultiBufferRow(block_start.row)) {
 3959                    return None;
 3960                }
 3961                let align_to = block_start.to_display_point(snapshot);
 3962                let x_and_width = |layout: &LineWithInvisibles| {
 3963                    Some((
 3964                        text_x + layout.x_for_index(align_to.column() as usize),
 3965                        text_x + layout.width,
 3966                    ))
 3967                };
 3968                let line_ix = align_to.row().0.checked_sub(rows.start.0);
 3969                x_position =
 3970                    if let Some(layout) = line_ix.and_then(|ix| line_layouts.get(ix as usize)) {
 3971                        x_and_width(layout)
 3972                    } else {
 3973                        x_and_width(&layout_line(
 3974                            align_to.row(),
 3975                            snapshot,
 3976                            &self.style,
 3977                            editor_width,
 3978                            is_row_soft_wrapped,
 3979                            window,
 3980                            cx,
 3981                        ))
 3982                    };
 3983
 3984                let anchor_x = x_position.unwrap().0;
 3985
 3986                let selected = selections
 3987                    .binary_search_by(|selection| {
 3988                        if selection.end <= block_start {
 3989                            Ordering::Less
 3990                        } else if selection.start >= block_end {
 3991                            Ordering::Greater
 3992                        } else {
 3993                            Ordering::Equal
 3994                        }
 3995                    })
 3996                    .is_ok();
 3997
 3998                div()
 3999                    .size_full()
 4000                    .child(
 4001                        custom.render(&mut BlockContext {
 4002                            window,
 4003                            app: cx,
 4004                            anchor_x,
 4005                            margins: editor_margins,
 4006                            line_height,
 4007                            em_width,
 4008                            block_id,
 4009                            height: custom.height.unwrap_or(1),
 4010                            selected,
 4011                            max_width: text_hitbox.size.width.max(*scroll_width),
 4012                            editor_style: &self.style,
 4013                            indent_guide_padding: indent_guides
 4014                                .as_ref()
 4015                                .map(|guides| {
 4016                                    Self::depth_zero_indent_guide_padding_for_row(
 4017                                        guides,
 4018                                        block_row_start,
 4019                                    )
 4020                                })
 4021                                .unwrap_or(px(0.0)),
 4022                        }),
 4023                    )
 4024                    .into_any()
 4025            }
 4026
 4027            Block::FoldedBuffer {
 4028                first_excerpt,
 4029                height,
 4030                ..
 4031            } => {
 4032                let mut result = v_flex().id(block_id).w_full().pr(editor_margins.right);
 4033
 4034                if self.should_show_buffer_headers() {
 4035                    let selected = selected_buffer_ids.contains(&first_excerpt.buffer_id());
 4036                    let jump_data = header_jump_data(
 4037                        snapshot,
 4038                        block_row_start,
 4039                        *height,
 4040                        first_excerpt,
 4041                        latest_selection_anchors,
 4042                    );
 4043                    result = result.child(self.render_buffer_header(
 4044                        first_excerpt,
 4045                        true,
 4046                        selected,
 4047                        false,
 4048                        jump_data,
 4049                        window,
 4050                        cx,
 4051                    ));
 4052                } else {
 4053                    result =
 4054                        result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
 4055                }
 4056
 4057                result.into_any_element()
 4058            }
 4059
 4060            Block::ExcerptBoundary { .. } => {
 4061                let color = cx.theme().colors().clone();
 4062                let mut result = v_flex().id(block_id).w_full();
 4063
 4064                result = result.child(
 4065                    h_flex().relative().child(
 4066                        div()
 4067                            .top(line_height / 2.)
 4068                            .absolute()
 4069                            .w_full()
 4070                            .h_px()
 4071                            .bg(color.border_variant),
 4072                    ),
 4073                );
 4074
 4075                result.into_any()
 4076            }
 4077
 4078            Block::BufferHeader { excerpt, height } => {
 4079                let mut result = v_flex().id(block_id).w_full();
 4080
 4081                if self.should_show_buffer_headers() {
 4082                    let jump_data = header_jump_data(
 4083                        snapshot,
 4084                        block_row_start,
 4085                        *height,
 4086                        excerpt,
 4087                        latest_selection_anchors,
 4088                    );
 4089
 4090                    if sticky_header_excerpt_id != Some(excerpt.buffer_id()) {
 4091                        let selected = selected_buffer_ids.contains(&excerpt.buffer_id());
 4092
 4093                        result = result.child(div().pr(editor_margins.right).child(
 4094                            self.render_buffer_header(
 4095                                excerpt, false, selected, false, jump_data, window, cx,
 4096                            ),
 4097                        ));
 4098                    } else {
 4099                        result =
 4100                            result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
 4101                    }
 4102                } else {
 4103                    result =
 4104                        result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
 4105                }
 4106
 4107                result.into_any()
 4108            }
 4109
 4110            Block::Spacer { height, .. } => {
 4111                let indent_guide_padding = indent_guides
 4112                    .as_ref()
 4113                    .map(|guides| {
 4114                        Self::depth_zero_indent_guide_padding_for_row(guides, block_row_start)
 4115                    })
 4116                    .unwrap_or(px(0.0));
 4117                Self::render_spacer_block(
 4118                    block_id,
 4119                    *height,
 4120                    line_height,
 4121                    indent_guide_padding,
 4122                    window,
 4123                    cx,
 4124                )
 4125            }
 4126        };
 4127
 4128        // Discover the element's content height, then round up to the nearest multiple of line height.
 4129        let preliminary_size = element.layout_as_root(
 4130            size(available_width, AvailableSpace::MinContent),
 4131            window,
 4132            cx,
 4133        );
 4134        let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
 4135        let final_size = if preliminary_size.height == quantized_height {
 4136            preliminary_size
 4137        } else {
 4138            element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
 4139        };
 4140        let mut element_height_in_lines = ((final_size.height / line_height).ceil() as u32).max(1);
 4141
 4142        let effective_row_start = block_row_start.0 as i32 + *block_resize_offset;
 4143        debug_assert!(effective_row_start >= 0);
 4144        let mut row = DisplayRow(effective_row_start.max(0) as u32);
 4145
 4146        let mut x_offset = px(0.);
 4147        let mut is_block = true;
 4148
 4149        if let BlockId::Custom(custom_block_id) = block_id
 4150            && block.has_height()
 4151        {
 4152            if block.place_near()
 4153                && let Some((x_target, line_width)) = x_position
 4154            {
 4155                let margin = em_width * 2;
 4156                if line_width + final_size.width + margin
 4157                    < editor_width + editor_margins.gutter.full_width()
 4158                    && !row_block_types.contains_key(&(row - 1))
 4159                    && element_height_in_lines == 1
 4160                {
 4161                    // Render inline at end of line (for diagnostic blocks that fit)
 4162                    x_offset = line_width + margin;
 4163                    row = row - 1;
 4164                    is_block = false;
 4165                    element_height_in_lines = 0;
 4166                    row_block_types.insert(row, is_block);
 4167                } else {
 4168                    let max_offset =
 4169                        editor_width + editor_margins.gutter.full_width() - final_size.width;
 4170                    let min_offset = (x_target + em_width - final_size.width)
 4171                        .max(editor_margins.gutter.full_width());
 4172                    x_offset = x_target.min(max_offset).max(min_offset);
 4173                }
 4174            };
 4175            if element_height_in_lines != block.height() {
 4176                *block_resize_offset += element_height_in_lines as i32 - block.height() as i32;
 4177                resized_blocks.insert(custom_block_id, element_height_in_lines);
 4178            }
 4179        }
 4180        for i in 0..element_height_in_lines {
 4181            row_block_types.insert(row + i, is_block);
 4182        }
 4183
 4184        Some((element, final_size, row, x_offset))
 4185    }
 4186
 4187    /// The spacer pattern period must be an even factor of the line height, so
 4188    /// that two consecutive spacer blocks can render contiguously without an
 4189    /// obvious break in the pattern.
 4190    ///
 4191    /// Two consecutive spacers can appear when the other side has a diff hunk
 4192    /// and a custom block next to each other (e.g. merge conflict buttons).
 4193    fn spacer_pattern_period(line_height: f32, target_height: f32) -> f32 {
 4194        let k_approx = line_height / (2.0 * target_height);
 4195        let k_floor = (k_approx.floor() as u32).max(1);
 4196        let k_ceil = (k_approx.ceil() as u32).max(1);
 4197
 4198        let size_floor = line_height / (2 * k_floor) as f32;
 4199        let size_ceil = line_height / (2 * k_ceil) as f32;
 4200
 4201        if (size_floor - target_height).abs() <= (size_ceil - target_height).abs() {
 4202            size_floor
 4203        } else {
 4204            size_ceil
 4205        }
 4206    }
 4207
 4208    pub fn render_spacer_block(
 4209        block_id: BlockId,
 4210        block_height: u32,
 4211        line_height: Pixels,
 4212        indent_guide_padding: Pixels,
 4213        window: &mut Window,
 4214        cx: &App,
 4215    ) -> AnyElement {
 4216        let target_size = 16.0;
 4217        let scale = window.scale_factor();
 4218        let pattern_size =
 4219            Self::spacer_pattern_period(f32::from(line_height) * scale, target_size * scale);
 4220        let color = cx.theme().colors().panel_background;
 4221        let background = pattern_slash(color, 2.0, pattern_size - 2.0);
 4222
 4223        div()
 4224            .id(block_id)
 4225            .cursor(CursorStyle::Arrow)
 4226            .w_full()
 4227            .h((block_height as f32) * line_height)
 4228            .flex()
 4229            .flex_row()
 4230            .child(div().flex_shrink_0().w(indent_guide_padding).h_full())
 4231            .child(
 4232                div()
 4233                    .flex_1()
 4234                    .h_full()
 4235                    .relative()
 4236                    .overflow_x_hidden()
 4237                    .child(
 4238                        div()
 4239                            .absolute()
 4240                            .top_0()
 4241                            .bottom_0()
 4242                            .right_0()
 4243                            .left(-indent_guide_padding)
 4244                            .bg(background),
 4245                    ),
 4246            )
 4247            .into_any()
 4248    }
 4249
 4250    fn render_buffer_header(
 4251        &self,
 4252        for_excerpt: &ExcerptBoundaryInfo,
 4253        is_folded: bool,
 4254        is_selected: bool,
 4255        is_sticky: bool,
 4256        jump_data: JumpData,
 4257        window: &mut Window,
 4258        cx: &mut App,
 4259    ) -> impl IntoElement {
 4260        render_buffer_header(
 4261            &self.editor,
 4262            for_excerpt,
 4263            is_folded,
 4264            is_selected,
 4265            is_sticky,
 4266            jump_data,
 4267            window,
 4268            cx,
 4269        )
 4270    }
 4271
 4272    fn render_blocks(
 4273        &self,
 4274        rows: Range<DisplayRow>,
 4275        snapshot: &EditorSnapshot,
 4276        hitbox: &Hitbox,
 4277        text_hitbox: &Hitbox,
 4278        editor_width: Pixels,
 4279        scroll_width: &mut Pixels,
 4280        editor_margins: &EditorMargins,
 4281        em_width: Pixels,
 4282        text_x: Pixels,
 4283        line_height: Pixels,
 4284        line_layouts: &mut [LineWithInvisibles],
 4285        selections: &[Selection<Point>],
 4286        selected_buffer_ids: &Vec<BufferId>,
 4287        latest_selection_anchors: &HashMap<BufferId, Anchor>,
 4288        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 4289        sticky_header_excerpt_id: Option<BufferId>,
 4290        indent_guides: &Option<Vec<IndentGuideLayout>>,
 4291        window: &mut Window,
 4292        cx: &mut App,
 4293    ) -> RenderBlocksOutput {
 4294        let (fixed_blocks, non_fixed_blocks) = snapshot
 4295            .blocks_in_range(rows.clone())
 4296            .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
 4297
 4298        let mut focused_block = self
 4299            .editor
 4300            .update(cx, |editor, _| editor.take_focused_block());
 4301        let mut fixed_block_max_width = Pixels::ZERO;
 4302        let mut blocks = Vec::new();
 4303        let mut spacer_blocks = Vec::new();
 4304        let mut resized_blocks = HashMap::default();
 4305        let mut row_block_types = HashMap::default();
 4306        let mut block_resize_offset: i32 = 0;
 4307
 4308        for (row, block) in fixed_blocks {
 4309            let block_id = block.id();
 4310
 4311            if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
 4312                focused_block = None;
 4313            }
 4314
 4315            if let Some((element, element_size, row, x_offset)) = self.render_block(
 4316                block,
 4317                AvailableSpace::MinContent,
 4318                block_id,
 4319                row,
 4320                snapshot,
 4321                text_x,
 4322                &rows,
 4323                line_layouts,
 4324                editor_margins,
 4325                line_height,
 4326                em_width,
 4327                text_hitbox,
 4328                editor_width,
 4329                scroll_width,
 4330                &mut resized_blocks,
 4331                &mut row_block_types,
 4332                selections,
 4333                selected_buffer_ids,
 4334                latest_selection_anchors,
 4335                is_row_soft_wrapped,
 4336                sticky_header_excerpt_id,
 4337                indent_guides,
 4338                &mut block_resize_offset,
 4339                window,
 4340                cx,
 4341            ) {
 4342                fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
 4343                blocks.push(BlockLayout {
 4344                    id: block_id,
 4345                    x_offset,
 4346                    row: Some(row),
 4347                    element,
 4348                    available_space: size(AvailableSpace::MinContent, element_size.height.into()),
 4349                    style: BlockStyle::Fixed,
 4350                    overlaps_gutter: true,
 4351                    is_buffer_header: block.is_buffer_header(),
 4352                });
 4353            }
 4354        }
 4355
 4356        for (row, block) in non_fixed_blocks {
 4357            let style = block.style();
 4358            let width = match (style, block.place_near()) {
 4359                (_, true) => AvailableSpace::MinContent,
 4360                (BlockStyle::Sticky, _) => hitbox.size.width.into(),
 4361                (BlockStyle::Flex, _) => hitbox
 4362                    .size
 4363                    .width
 4364                    .max(fixed_block_max_width)
 4365                    .max(
 4366                        editor_margins.gutter.width + *scroll_width + editor_margins.extended_right,
 4367                    )
 4368                    .into(),
 4369                (BlockStyle::Spacer, _) => hitbox
 4370                    .size
 4371                    .width
 4372                    .max(fixed_block_max_width)
 4373                    .max(*scroll_width + editor_margins.extended_right)
 4374                    .into(),
 4375                (BlockStyle::Fixed, _) => unreachable!(),
 4376            };
 4377            let block_id = block.id();
 4378
 4379            if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
 4380                focused_block = None;
 4381            }
 4382
 4383            if let Some((element, element_size, row, x_offset)) = self.render_block(
 4384                block,
 4385                width,
 4386                block_id,
 4387                row,
 4388                snapshot,
 4389                text_x,
 4390                &rows,
 4391                line_layouts,
 4392                editor_margins,
 4393                line_height,
 4394                em_width,
 4395                text_hitbox,
 4396                editor_width,
 4397                scroll_width,
 4398                &mut resized_blocks,
 4399                &mut row_block_types,
 4400                selections,
 4401                selected_buffer_ids,
 4402                latest_selection_anchors,
 4403                is_row_soft_wrapped,
 4404                sticky_header_excerpt_id,
 4405                indent_guides,
 4406                &mut block_resize_offset,
 4407                window,
 4408                cx,
 4409            ) {
 4410                let layout = BlockLayout {
 4411                    id: block_id,
 4412                    x_offset,
 4413                    row: Some(row),
 4414                    element,
 4415                    available_space: size(width, element_size.height.into()),
 4416                    style,
 4417                    overlaps_gutter: !block.place_near() && style != BlockStyle::Spacer,
 4418                    is_buffer_header: block.is_buffer_header(),
 4419                };
 4420                if style == BlockStyle::Spacer {
 4421                    spacer_blocks.push(layout);
 4422                } else {
 4423                    blocks.push(layout);
 4424                }
 4425            }
 4426        }
 4427
 4428        if let Some(focused_block) = focused_block
 4429            && let Some(focus_handle) = focused_block.focus_handle.upgrade()
 4430            && focus_handle.is_focused(window)
 4431            && let Some(block) = snapshot.block_for_id(focused_block.id)
 4432        {
 4433            let style = block.style();
 4434            let width = match style {
 4435                BlockStyle::Fixed => AvailableSpace::MinContent,
 4436                BlockStyle::Flex => {
 4437                    AvailableSpace::Definite(hitbox.size.width.max(fixed_block_max_width).max(
 4438                        editor_margins.gutter.width + *scroll_width + editor_margins.extended_right,
 4439                    ))
 4440                }
 4441                BlockStyle::Spacer => AvailableSpace::Definite(
 4442                    hitbox
 4443                        .size
 4444                        .width
 4445                        .max(fixed_block_max_width)
 4446                        .max(*scroll_width + editor_margins.extended_right),
 4447                ),
 4448                BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
 4449            };
 4450
 4451            if let Some((element, element_size, _, x_offset)) = self.render_block(
 4452                &block,
 4453                width,
 4454                focused_block.id,
 4455                rows.end,
 4456                snapshot,
 4457                text_x,
 4458                &rows,
 4459                line_layouts,
 4460                editor_margins,
 4461                line_height,
 4462                em_width,
 4463                text_hitbox,
 4464                editor_width,
 4465                scroll_width,
 4466                &mut resized_blocks,
 4467                &mut row_block_types,
 4468                selections,
 4469                selected_buffer_ids,
 4470                latest_selection_anchors,
 4471                is_row_soft_wrapped,
 4472                sticky_header_excerpt_id,
 4473                indent_guides,
 4474                &mut block_resize_offset,
 4475                window,
 4476                cx,
 4477            ) {
 4478                blocks.push(BlockLayout {
 4479                    id: block.id(),
 4480                    x_offset,
 4481                    row: None,
 4482                    element,
 4483                    available_space: size(width, element_size.height.into()),
 4484                    style,
 4485                    overlaps_gutter: true,
 4486                    is_buffer_header: block.is_buffer_header(),
 4487                });
 4488            }
 4489        }
 4490
 4491        if resized_blocks.is_empty() {
 4492            *scroll_width =
 4493                (*scroll_width).max(fixed_block_max_width - editor_margins.gutter.width);
 4494        }
 4495
 4496        RenderBlocksOutput {
 4497            non_spacer_blocks: blocks,
 4498            spacer_blocks,
 4499            row_block_types,
 4500            resized_blocks: (!resized_blocks.is_empty()).then_some(resized_blocks),
 4501        }
 4502    }
 4503
 4504    fn layout_blocks(
 4505        &self,
 4506        blocks: &mut Vec<BlockLayout>,
 4507        hitbox: &Hitbox,
 4508        gutter_hitbox: &Hitbox,
 4509        line_height: Pixels,
 4510        scroll_position: gpui::Point<ScrollOffset>,
 4511        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 4512        editor_margins: &EditorMargins,
 4513        window: &mut Window,
 4514        cx: &mut App,
 4515    ) {
 4516        for block in blocks {
 4517            let mut origin = if let Some(row) = block.row {
 4518                hitbox.origin
 4519                    + point(
 4520                        block.x_offset,
 4521                        Pixels::from(
 4522                            (row.as_f64() - scroll_position.y)
 4523                                * ScrollPixelOffset::from(line_height),
 4524                        ),
 4525                    )
 4526            } else {
 4527                // Position the block outside the visible area
 4528                hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
 4529            };
 4530
 4531            if block.style == BlockStyle::Spacer {
 4532                origin += point(
 4533                    gutter_hitbox.size.width + editor_margins.gutter.margin,
 4534                    Pixels::ZERO,
 4535                );
 4536            }
 4537
 4538            if !matches!(block.style, BlockStyle::Sticky) {
 4539                origin += point(Pixels::from(-scroll_pixel_position.x), Pixels::ZERO);
 4540            }
 4541
 4542            let focus_handle =
 4543                block
 4544                    .element
 4545                    .prepaint_as_root(origin, block.available_space, window, cx);
 4546
 4547            if let Some(focus_handle) = focus_handle {
 4548                self.editor.update(cx, |editor, _cx| {
 4549                    editor.set_focused_block(FocusedBlock {
 4550                        id: block.id,
 4551                        focus_handle: focus_handle.downgrade(),
 4552                    });
 4553                });
 4554            }
 4555        }
 4556    }
 4557
 4558    fn layout_sticky_buffer_header(
 4559        &self,
 4560        StickyHeaderExcerpt { excerpt }: StickyHeaderExcerpt<'_>,
 4561        scroll_position: gpui::Point<ScrollOffset>,
 4562        line_height: Pixels,
 4563        right_margin: Pixels,
 4564        snapshot: &EditorSnapshot,
 4565        hitbox: &Hitbox,
 4566        selected_buffer_ids: &Vec<BufferId>,
 4567        blocks: &[BlockLayout],
 4568        latest_selection_anchors: &HashMap<BufferId, Anchor>,
 4569        window: &mut Window,
 4570        cx: &mut App,
 4571    ) -> AnyElement {
 4572        let jump_data = header_jump_data(
 4573            snapshot,
 4574            DisplayRow(scroll_position.y as u32),
 4575            FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 4576            excerpt,
 4577            latest_selection_anchors,
 4578        );
 4579
 4580        let editor_bg_color = cx.theme().colors().editor_background;
 4581
 4582        let selected = selected_buffer_ids.contains(&excerpt.buffer_id());
 4583
 4584        let available_width = hitbox.bounds.size.width - right_margin;
 4585
 4586        let mut header = v_flex()
 4587            .w_full()
 4588            .relative()
 4589            .child(
 4590                div()
 4591                    .w(available_width)
 4592                    .h(FILE_HEADER_HEIGHT as f32 * line_height)
 4593                    .bg(linear_gradient(
 4594                        0.,
 4595                        linear_color_stop(editor_bg_color.opacity(0.), 0.),
 4596                        linear_color_stop(editor_bg_color, 0.6),
 4597                    ))
 4598                    .absolute()
 4599                    .top_0(),
 4600            )
 4601            .child(
 4602                self.render_buffer_header(excerpt, false, selected, true, jump_data, window, cx)
 4603                    .into_any_element(),
 4604            )
 4605            .into_any_element();
 4606
 4607        let mut origin = hitbox.origin;
 4608        // Move floating header up to avoid colliding with the next buffer header.
 4609        for block in blocks.iter() {
 4610            if !block.is_buffer_header {
 4611                continue;
 4612            }
 4613
 4614            let Some(display_row) = block.row.filter(|row| row.0 > scroll_position.y as u32) else {
 4615                continue;
 4616            };
 4617
 4618            let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
 4619            let offset = scroll_position.y - max_row as f64;
 4620
 4621            if offset > 0.0 {
 4622                origin.y -= Pixels::from(offset * ScrollPixelOffset::from(line_height));
 4623            }
 4624            break;
 4625        }
 4626
 4627        let size = size(
 4628            AvailableSpace::Definite(available_width),
 4629            AvailableSpace::MinContent,
 4630        );
 4631
 4632        header.prepaint_as_root(origin, size, window, cx);
 4633
 4634        header
 4635    }
 4636
 4637    fn layout_sticky_headers(
 4638        &self,
 4639        snapshot: &EditorSnapshot,
 4640        editor_width: Pixels,
 4641        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 4642        line_height: Pixels,
 4643        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 4644        content_origin: gpui::Point<Pixels>,
 4645        gutter_dimensions: &GutterDimensions,
 4646        gutter_hitbox: &Hitbox,
 4647        text_hitbox: &Hitbox,
 4648        relative_line_numbers: RelativeLineNumbers,
 4649        relative_to: Option<DisplayRow>,
 4650        window: &mut Window,
 4651        cx: &mut App,
 4652    ) -> Option<StickyHeaders> {
 4653        let show_line_numbers = snapshot
 4654            .show_line_numbers
 4655            .unwrap_or_else(|| EditorSettings::get_global(cx).gutter.line_numbers);
 4656
 4657        let rows = Self::sticky_headers(self.editor.read(cx), snapshot);
 4658
 4659        let mut lines = Vec::<StickyHeaderLine>::new();
 4660
 4661        for StickyHeader {
 4662            sticky_row,
 4663            start_point,
 4664            offset,
 4665        } in rows.into_iter().rev()
 4666        {
 4667            let line = layout_line(
 4668                sticky_row,
 4669                snapshot,
 4670                &self.style,
 4671                editor_width,
 4672                is_row_soft_wrapped,
 4673                window,
 4674                cx,
 4675            );
 4676
 4677            let line_number = show_line_numbers.then(|| {
 4678                let start_display_row = start_point.to_display_point(snapshot).row();
 4679                let relative_number = relative_to
 4680                    .filter(|_| relative_line_numbers != RelativeLineNumbers::Disabled)
 4681                    .map(|base| {
 4682                        snapshot.relative_line_delta(
 4683                            base,
 4684                            start_display_row,
 4685                            relative_line_numbers == RelativeLineNumbers::Wrapped,
 4686                        )
 4687                    });
 4688                let number = relative_number
 4689                    .filter(|&delta| delta != 0)
 4690                    .map(|delta| delta.unsigned_abs() as u32)
 4691                    .unwrap_or(start_point.row + 1);
 4692                let color = cx.theme().colors().editor_line_number;
 4693                self.shape_line_number(SharedString::from(number.to_string()), color, window)
 4694            });
 4695
 4696            lines.push(StickyHeaderLine::new(
 4697                sticky_row,
 4698                line_height * offset as f32,
 4699                line,
 4700                line_number,
 4701                line_height,
 4702                scroll_pixel_position,
 4703                content_origin,
 4704                gutter_hitbox,
 4705                text_hitbox,
 4706                window,
 4707                cx,
 4708            ));
 4709        }
 4710
 4711        lines.reverse();
 4712        if lines.is_empty() {
 4713            return None;
 4714        }
 4715
 4716        Some(StickyHeaders {
 4717            lines,
 4718            gutter_background: cx.theme().colors().editor_gutter_background,
 4719            content_background: self.style.background,
 4720            gutter_right_padding: gutter_dimensions.right_padding,
 4721        })
 4722    }
 4723
 4724    pub(crate) fn sticky_headers(editor: &Editor, snapshot: &EditorSnapshot) -> Vec<StickyHeader> {
 4725        let scroll_top = snapshot.scroll_position().y;
 4726
 4727        let mut end_rows = Vec::<DisplayRow>::new();
 4728        let mut rows = Vec::<StickyHeader>::new();
 4729
 4730        for item in editor.sticky_headers.iter().flatten() {
 4731            let start_point = item
 4732                .source_range_for_text
 4733                .start
 4734                .to_point(snapshot.buffer_snapshot());
 4735            let end_point = item.range.end.to_point(snapshot.buffer_snapshot());
 4736
 4737            let sticky_row = snapshot
 4738                .display_snapshot
 4739                .point_to_display_point(start_point, Bias::Left)
 4740                .row();
 4741            if rows
 4742                .last()
 4743                .is_some_and(|last| last.sticky_row == sticky_row)
 4744            {
 4745                continue;
 4746            }
 4747
 4748            let end_row = snapshot
 4749                .display_snapshot
 4750                .point_to_display_point(end_point, Bias::Left)
 4751                .row();
 4752            let max_sticky_row = end_row.previous_row();
 4753            if max_sticky_row <= sticky_row {
 4754                continue;
 4755            }
 4756
 4757            while end_rows
 4758                .last()
 4759                .is_some_and(|&last_end| last_end <= sticky_row)
 4760            {
 4761                end_rows.pop();
 4762            }
 4763            let depth = end_rows.len();
 4764            let adjusted_scroll_top = scroll_top + depth as f64;
 4765
 4766            if sticky_row.as_f64() >= adjusted_scroll_top || end_row.as_f64() <= adjusted_scroll_top
 4767            {
 4768                continue;
 4769            }
 4770
 4771            let max_scroll_offset = max_sticky_row.as_f64() - scroll_top;
 4772            let offset = (depth as f64).min(max_scroll_offset);
 4773
 4774            end_rows.push(end_row);
 4775            rows.push(StickyHeader {
 4776                sticky_row,
 4777                start_point,
 4778                offset,
 4779            });
 4780        }
 4781
 4782        rows
 4783    }
 4784
 4785    fn layout_cursor_popovers(
 4786        &self,
 4787        line_height: Pixels,
 4788        text_hitbox: &Hitbox,
 4789        content_origin: gpui::Point<Pixels>,
 4790        right_margin: Pixels,
 4791        start_row: DisplayRow,
 4792        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 4793        line_layouts: &[LineWithInvisibles],
 4794        cursor: DisplayPoint,
 4795        cursor_point: Point,
 4796        style: &EditorStyle,
 4797        window: &mut Window,
 4798        cx: &mut App,
 4799    ) -> Option<ContextMenuLayout> {
 4800        let mut min_menu_height = Pixels::ZERO;
 4801        let mut max_menu_height = Pixels::ZERO;
 4802        let mut height_above_menu = Pixels::ZERO;
 4803        let height_below_menu = Pixels::ZERO;
 4804        let mut edit_prediction_popover_visible = false;
 4805        let mut context_menu_visible = false;
 4806        let context_menu_placement;
 4807
 4808        {
 4809            let editor = self.editor.read(cx);
 4810            if editor.edit_prediction_visible_in_cursor_popover(editor.has_active_edit_prediction())
 4811            {
 4812                height_above_menu +=
 4813                    editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
 4814                edit_prediction_popover_visible = true;
 4815            }
 4816
 4817            if editor.context_menu_visible()
 4818                && let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin()
 4819            {
 4820                let (min_height_in_lines, max_height_in_lines) = editor
 4821                    .context_menu_options
 4822                    .as_ref()
 4823                    .map_or((3, 12), |options| {
 4824                        (options.min_entries_visible, options.max_entries_visible)
 4825                    });
 4826
 4827                min_menu_height += line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
 4828                max_menu_height += line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
 4829                context_menu_visible = true;
 4830            }
 4831            context_menu_placement = editor
 4832                .context_menu_options
 4833                .as_ref()
 4834                .and_then(|options| options.placement.clone());
 4835        }
 4836
 4837        let visible = edit_prediction_popover_visible || context_menu_visible;
 4838        if !visible {
 4839            return None;
 4840        }
 4841
 4842        let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
 4843        let target_position = content_origin
 4844            + gpui::Point {
 4845                x: cmp::max(
 4846                    px(0.),
 4847                    Pixels::from(
 4848                        ScrollPixelOffset::from(
 4849                            cursor_row_layout.x_for_index(cursor.column() as usize),
 4850                        ) - scroll_pixel_position.x,
 4851                    ),
 4852                ),
 4853                y: cmp::max(
 4854                    px(0.),
 4855                    Pixels::from(
 4856                        cursor.row().next_row().as_f64() * ScrollPixelOffset::from(line_height)
 4857                            - scroll_pixel_position.y,
 4858                    ),
 4859                ),
 4860            };
 4861
 4862        let viewport_bounds =
 4863            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 4864                right: -right_margin - MENU_GAP,
 4865                ..Default::default()
 4866            });
 4867
 4868        let min_height = height_above_menu + min_menu_height + height_below_menu;
 4869        let max_height = height_above_menu + max_menu_height + height_below_menu;
 4870        let (laid_out_popovers, y_flipped) = self.layout_popovers_above_or_below_line(
 4871            target_position,
 4872            line_height,
 4873            min_height,
 4874            max_height,
 4875            context_menu_placement,
 4876            text_hitbox,
 4877            viewport_bounds,
 4878            window,
 4879            cx,
 4880            |height, max_width_for_stable_x, y_flipped, window, cx| {
 4881                // First layout the menu to get its size - others can be at least this wide.
 4882                let context_menu = if context_menu_visible {
 4883                    let menu_height = if y_flipped {
 4884                        height - height_below_menu
 4885                    } else {
 4886                        height - height_above_menu
 4887                    };
 4888                    let mut element = self
 4889                        .render_context_menu(line_height, menu_height, window, cx)
 4890                        .expect("Visible context menu should always render.");
 4891                    let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 4892                    Some((CursorPopoverType::CodeContextMenu, element, size))
 4893                } else {
 4894                    None
 4895                };
 4896                let min_width = context_menu
 4897                    .as_ref()
 4898                    .map_or(px(0.), |(_, _, size)| size.width);
 4899                let max_width = max_width_for_stable_x.max(
 4900                    context_menu
 4901                        .as_ref()
 4902                        .map_or(px(0.), |(_, _, size)| size.width),
 4903                );
 4904
 4905                let edit_prediction = if edit_prediction_popover_visible {
 4906                    self.editor.update(cx, move |editor, cx| {
 4907                        let mut element = editor.render_edit_prediction_cursor_popover(
 4908                            min_width,
 4909                            max_width,
 4910                            cursor_point,
 4911                            style,
 4912                            window,
 4913                            cx,
 4914                        )?;
 4915                        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 4916                        Some((CursorPopoverType::EditPrediction, element, size))
 4917                    })
 4918                } else {
 4919                    None
 4920                };
 4921                vec![edit_prediction, context_menu]
 4922                    .into_iter()
 4923                    .flatten()
 4924                    .collect::<Vec<_>>()
 4925            },
 4926        )?;
 4927
 4928        let (menu_ix, (_, menu_bounds)) = laid_out_popovers
 4929            .iter()
 4930            .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))?;
 4931        let last_ix = laid_out_popovers.len() - 1;
 4932        let menu_is_last = menu_ix == last_ix;
 4933        let first_popover_bounds = laid_out_popovers[0].1;
 4934        let last_popover_bounds = laid_out_popovers[last_ix].1;
 4935
 4936        // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
 4937        // right, and otherwise it goes below or to the right.
 4938        let mut target_bounds = Bounds::from_corners(
 4939            first_popover_bounds.origin,
 4940            last_popover_bounds.bottom_right(),
 4941        );
 4942        target_bounds.size.width = menu_bounds.size.width;
 4943
 4944        // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
 4945        // based on this is preferred for layout stability.
 4946        let mut max_target_bounds = target_bounds;
 4947        max_target_bounds.size.height = max_height;
 4948        if y_flipped {
 4949            max_target_bounds.origin.y -= max_height - target_bounds.size.height;
 4950        }
 4951
 4952        // Add spacing around `target_bounds` and `max_target_bounds`.
 4953        let mut extend_amount = Edges::all(MENU_GAP);
 4954        if y_flipped {
 4955            extend_amount.bottom = line_height;
 4956        } else {
 4957            extend_amount.top = line_height;
 4958        }
 4959        let target_bounds = target_bounds.extend(extend_amount);
 4960        let max_target_bounds = max_target_bounds.extend(extend_amount);
 4961
 4962        let must_place_above_or_below =
 4963            if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
 4964                laid_out_popovers[menu_ix + 1..]
 4965                    .iter()
 4966                    .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
 4967            } else {
 4968                false
 4969            };
 4970
 4971        let aside_bounds = self.layout_context_menu_aside(
 4972            y_flipped,
 4973            *menu_bounds,
 4974            target_bounds,
 4975            max_target_bounds,
 4976            max_menu_height,
 4977            must_place_above_or_below,
 4978            text_hitbox,
 4979            viewport_bounds,
 4980            window,
 4981            cx,
 4982        );
 4983
 4984        if let Some(menu_bounds) = laid_out_popovers.iter().find_map(|(popover_type, bounds)| {
 4985            if matches!(popover_type, CursorPopoverType::CodeContextMenu) {
 4986                Some(*bounds)
 4987            } else {
 4988                None
 4989            }
 4990        }) {
 4991            let bounds = if let Some(aside_bounds) = aside_bounds {
 4992                menu_bounds.union(&aside_bounds)
 4993            } else {
 4994                menu_bounds
 4995            };
 4996            return Some(ContextMenuLayout { y_flipped, bounds });
 4997        }
 4998
 4999        None
 5000    }
 5001
 5002    fn layout_gutter_menu(
 5003        &self,
 5004        line_height: Pixels,
 5005        text_hitbox: &Hitbox,
 5006        content_origin: gpui::Point<Pixels>,
 5007        right_margin: Pixels,
 5008        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 5009        gutter_overshoot: Pixels,
 5010        window: &mut Window,
 5011        cx: &mut App,
 5012    ) {
 5013        let editor = self.editor.read(cx);
 5014        if !editor.context_menu_visible() {
 5015            return;
 5016        }
 5017        let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
 5018            editor.context_menu_origin()
 5019        else {
 5020            return;
 5021        };
 5022        // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
 5023        // indicator than just a plain first column of the text field.
 5024        let target_position = content_origin
 5025            + gpui::Point {
 5026                x: -gutter_overshoot,
 5027                y: Pixels::from(
 5028                    gutter_row.next_row().as_f64() * ScrollPixelOffset::from(line_height)
 5029                        - scroll_pixel_position.y,
 5030                ),
 5031            };
 5032
 5033        let (min_height_in_lines, max_height_in_lines) = editor
 5034            .context_menu_options
 5035            .as_ref()
 5036            .map_or((3, 12), |options| {
 5037                (options.min_entries_visible, options.max_entries_visible)
 5038            });
 5039
 5040        let min_height = line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
 5041        let max_height = line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
 5042        let viewport_bounds =
 5043            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 5044                right: -right_margin - MENU_GAP,
 5045                ..Default::default()
 5046            });
 5047        self.layout_popovers_above_or_below_line(
 5048            target_position,
 5049            line_height,
 5050            min_height,
 5051            max_height,
 5052            editor
 5053                .context_menu_options
 5054                .as_ref()
 5055                .and_then(|options| options.placement.clone()),
 5056            text_hitbox,
 5057            viewport_bounds,
 5058            window,
 5059            cx,
 5060            move |height, _max_width_for_stable_x, _, window, cx| {
 5061                let mut element = self
 5062                    .render_context_menu(line_height, height, window, cx)
 5063                    .expect("Visible context menu should always render.");
 5064                let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 5065                vec![(CursorPopoverType::CodeContextMenu, element, size)]
 5066            },
 5067        );
 5068    }
 5069
 5070    fn layout_popovers_above_or_below_line(
 5071        &self,
 5072        target_position: gpui::Point<Pixels>,
 5073        line_height: Pixels,
 5074        min_height: Pixels,
 5075        max_height: Pixels,
 5076        placement: Option<ContextMenuPlacement>,
 5077        text_hitbox: &Hitbox,
 5078        viewport_bounds: Bounds<Pixels>,
 5079        window: &mut Window,
 5080        cx: &mut App,
 5081        make_sized_popovers: impl FnOnce(
 5082            Pixels,
 5083            Pixels,
 5084            bool,
 5085            &mut Window,
 5086            &mut App,
 5087        ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
 5088    ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
 5089        let text_style = TextStyleRefinement {
 5090            line_height: Some(DefiniteLength::Fraction(
 5091                BufferLineHeight::Comfortable.value(),
 5092            )),
 5093            ..Default::default()
 5094        };
 5095        window.with_text_style(Some(text_style), |window| {
 5096            // If the max height won't fit below and there is more space above, put it above the line.
 5097            let bottom_y_when_flipped = target_position.y - line_height;
 5098            let available_above = bottom_y_when_flipped - text_hitbox.top();
 5099            let available_below = text_hitbox.bottom() - target_position.y;
 5100            let y_overflows_below = max_height > available_below;
 5101            let mut y_flipped = match placement {
 5102                Some(ContextMenuPlacement::Above) => true,
 5103                Some(ContextMenuPlacement::Below) => false,
 5104                None => y_overflows_below && available_above > available_below,
 5105            };
 5106            let mut height = cmp::min(
 5107                max_height,
 5108                if y_flipped {
 5109                    available_above
 5110                } else {
 5111                    available_below
 5112                },
 5113            );
 5114
 5115            // If the min height doesn't fit within text bounds, instead fit within the window.
 5116            if height < min_height {
 5117                let available_above = bottom_y_when_flipped;
 5118                let available_below = viewport_bounds.bottom() - target_position.y;
 5119                let (y_flipped_override, height_override) = match placement {
 5120                    Some(ContextMenuPlacement::Above) => {
 5121                        (true, cmp::min(available_above, min_height))
 5122                    }
 5123                    Some(ContextMenuPlacement::Below) => {
 5124                        (false, cmp::min(available_below, min_height))
 5125                    }
 5126                    None => {
 5127                        if available_below > min_height {
 5128                            (false, min_height)
 5129                        } else if available_above > min_height {
 5130                            (true, min_height)
 5131                        } else if available_above > available_below {
 5132                            (true, available_above)
 5133                        } else {
 5134                            (false, available_below)
 5135                        }
 5136                    }
 5137                };
 5138                y_flipped = y_flipped_override;
 5139                height = height_override;
 5140            }
 5141
 5142            let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
 5143
 5144            // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
 5145            // for very narrow windows.
 5146            let popovers =
 5147                make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
 5148            if popovers.is_empty() {
 5149                return None;
 5150            }
 5151
 5152            let max_width = popovers
 5153                .iter()
 5154                .map(|(_, _, size)| size.width)
 5155                .max()
 5156                .unwrap_or_default();
 5157
 5158            let mut current_position = gpui::Point {
 5159                // Snap the right edge of the list to the right edge of the window if its horizontal bounds
 5160                // overflow. Include space for the scrollbar.
 5161                x: target_position
 5162                    .x
 5163                    .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
 5164                y: if y_flipped {
 5165                    bottom_y_when_flipped
 5166                } else {
 5167                    target_position.y
 5168                },
 5169            };
 5170
 5171            let mut laid_out_popovers = popovers
 5172                .into_iter()
 5173                .map(|(popover_type, element, size)| {
 5174                    if y_flipped {
 5175                        current_position.y -= size.height;
 5176                    }
 5177                    let position = current_position;
 5178                    window.defer_draw(element, current_position, 1, None);
 5179                    if !y_flipped {
 5180                        current_position.y += size.height + MENU_GAP;
 5181                    } else {
 5182                        current_position.y -= MENU_GAP;
 5183                    }
 5184                    (popover_type, Bounds::new(position, size))
 5185                })
 5186                .collect::<Vec<_>>();
 5187
 5188            if y_flipped {
 5189                laid_out_popovers.reverse();
 5190            }
 5191
 5192            Some((laid_out_popovers, y_flipped))
 5193        })
 5194    }
 5195
 5196    fn layout_context_menu_aside(
 5197        &self,
 5198        y_flipped: bool,
 5199        menu_bounds: Bounds<Pixels>,
 5200        target_bounds: Bounds<Pixels>,
 5201        max_target_bounds: Bounds<Pixels>,
 5202        max_height: Pixels,
 5203        must_place_above_or_below: bool,
 5204        text_hitbox: &Hitbox,
 5205        viewport_bounds: Bounds<Pixels>,
 5206        window: &mut Window,
 5207        cx: &mut App,
 5208    ) -> Option<Bounds<Pixels>> {
 5209        let available_within_viewport = target_bounds.space_within(&viewport_bounds);
 5210        let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
 5211            && !must_place_above_or_below
 5212        {
 5213            let max_width = cmp::min(
 5214                available_within_viewport.right - px(1.),
 5215                MENU_ASIDE_MAX_WIDTH,
 5216            );
 5217            let mut aside = self.render_context_menu_aside(
 5218                size(max_width, max_height - POPOVER_Y_PADDING),
 5219                window,
 5220                cx,
 5221            )?;
 5222            let size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
 5223            let right_position = point(target_bounds.right(), menu_bounds.origin.y);
 5224            Some((aside, right_position, size))
 5225        } else {
 5226            let max_size = size(
 5227                // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
 5228                // won't be needed here.
 5229                cmp::min(
 5230                    cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
 5231                    viewport_bounds.right(),
 5232                ),
 5233                cmp::min(
 5234                    max_height,
 5235                    cmp::max(
 5236                        available_within_viewport.top,
 5237                        available_within_viewport.bottom,
 5238                    ),
 5239                ) - POPOVER_Y_PADDING,
 5240            );
 5241            let mut aside = self.render_context_menu_aside(max_size, window, cx)?;
 5242            let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
 5243
 5244            let top_position = point(
 5245                menu_bounds.origin.x,
 5246                target_bounds.top() - actual_size.height,
 5247            );
 5248            let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
 5249
 5250            let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
 5251                // Prefer to fit on the same side of the line as the menu, then on the other side of
 5252                // the line.
 5253                if !y_flipped && wanted.height < available.bottom {
 5254                    Some(bottom_position)
 5255                } else if !y_flipped && wanted.height < available.top {
 5256                    Some(top_position)
 5257                } else if y_flipped && wanted.height < available.top {
 5258                    Some(top_position)
 5259                } else if y_flipped && wanted.height < available.bottom {
 5260                    Some(bottom_position)
 5261                } else {
 5262                    None
 5263                }
 5264            };
 5265
 5266            // Prefer choosing a direction using max sizes rather than actual size for stability.
 5267            let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
 5268            let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
 5269            let aside_position = fit_within(available_within_text, wanted)
 5270                // Fallback: fit max size in window.
 5271                .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
 5272                // Fallback: fit actual size in window.
 5273                .or_else(|| fit_within(available_within_viewport, actual_size));
 5274
 5275            aside_position.map(|position| (aside, position, actual_size))
 5276        };
 5277
 5278        // Skip drawing if it doesn't fit anywhere.
 5279        if let Some((aside, position, size)) = positioned_aside {
 5280            let aside_bounds = Bounds::new(position, size);
 5281            window.defer_draw(aside, position, 2, None);
 5282            return Some(aside_bounds);
 5283        }
 5284
 5285        None
 5286    }
 5287
 5288    fn render_context_menu(
 5289        &self,
 5290        line_height: Pixels,
 5291        height: Pixels,
 5292        window: &mut Window,
 5293        cx: &mut App,
 5294    ) -> Option<AnyElement> {
 5295        let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
 5296        self.editor.update(cx, |editor, cx| {
 5297            editor.render_context_menu(max_height_in_lines, window, cx)
 5298        })
 5299    }
 5300
 5301    fn render_context_menu_aside(
 5302        &self,
 5303        max_size: Size<Pixels>,
 5304        window: &mut Window,
 5305        cx: &mut App,
 5306    ) -> Option<AnyElement> {
 5307        if max_size.width < px(100.) || max_size.height < px(12.) {
 5308            None
 5309        } else {
 5310            self.editor.update(cx, |editor, cx| {
 5311                editor.render_context_menu_aside(max_size, window, cx)
 5312            })
 5313        }
 5314    }
 5315
 5316    fn layout_mouse_context_menu(
 5317        &self,
 5318        editor_snapshot: &EditorSnapshot,
 5319        visible_range: Range<DisplayRow>,
 5320        content_origin: gpui::Point<Pixels>,
 5321        window: &mut Window,
 5322        cx: &mut App,
 5323    ) -> Option<AnyElement> {
 5324        let position = self.editor.update(cx, |editor, cx| {
 5325            let visible_start_point = editor.display_to_pixel_point(
 5326                DisplayPoint::new(visible_range.start, 0),
 5327                editor_snapshot,
 5328                window,
 5329                cx,
 5330            )?;
 5331            let visible_end_point = editor.display_to_pixel_point(
 5332                DisplayPoint::new(visible_range.end, 0),
 5333                editor_snapshot,
 5334                window,
 5335                cx,
 5336            )?;
 5337
 5338            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
 5339            let (source_display_point, position) = match mouse_context_menu.position {
 5340                MenuPosition::PinnedToScreen(point) => (None, point),
 5341                MenuPosition::PinnedToEditor { source, offset } => {
 5342                    let source_display_point = source.to_display_point(editor_snapshot);
 5343                    let source_point =
 5344                        editor.to_pixel_point(source, editor_snapshot, window, cx)?;
 5345                    let position = content_origin + source_point + offset;
 5346                    (Some(source_display_point), position)
 5347                }
 5348            };
 5349
 5350            let source_included = source_display_point.is_none_or(|source_display_point| {
 5351                visible_range
 5352                    .to_inclusive()
 5353                    .contains(&source_display_point.row())
 5354            });
 5355            let position_included =
 5356                visible_start_point.y <= position.y && position.y <= visible_end_point.y;
 5357            if !source_included && !position_included {
 5358                None
 5359            } else {
 5360                Some(position)
 5361            }
 5362        })?;
 5363
 5364        let text_style = TextStyleRefinement {
 5365            line_height: Some(DefiniteLength::Fraction(
 5366                BufferLineHeight::Comfortable.value(),
 5367            )),
 5368            ..Default::default()
 5369        };
 5370        window.with_text_style(Some(text_style), |window| {
 5371            let mut element = self.editor.read_with(cx, |editor, _| {
 5372                let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
 5373                let context_menu = mouse_context_menu.context_menu.clone();
 5374
 5375                Some(
 5376                    deferred(
 5377                        anchored()
 5378                            .position(position)
 5379                            .child(context_menu)
 5380                            .anchor(gpui::Anchor::TopLeft)
 5381                            .snap_to_window_with_margin(px(8.)),
 5382                    )
 5383                    .with_priority(1)
 5384                    .into_any(),
 5385                )
 5386            })?;
 5387
 5388            element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
 5389            Some(element)
 5390        })
 5391    }
 5392
 5393    fn layout_hover_popovers(
 5394        &self,
 5395        snapshot: &EditorSnapshot,
 5396        hitbox: &Hitbox,
 5397        visible_display_row_range: Range<DisplayRow>,
 5398        content_origin: gpui::Point<Pixels>,
 5399        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 5400        line_layouts: &[LineWithInvisibles],
 5401        line_height: Pixels,
 5402        em_width: Pixels,
 5403        context_menu_layout: Option<ContextMenuLayout>,
 5404        window: &mut Window,
 5405        cx: &mut App,
 5406    ) {
 5407        struct MeasuredHoverPopover {
 5408            element: AnyElement,
 5409            size: Size<Pixels>,
 5410            horizontal_offset: Pixels,
 5411        }
 5412
 5413        let max_size = size(
 5414            (120. * em_width) // Default size
 5415                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
 5416                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
 5417            (16. * line_height) // Default size
 5418                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
 5419                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
 5420        );
 5421
 5422        // Don't show hover popovers when context menu is open to avoid overlap
 5423        let has_context_menu = self.editor.read(cx).mouse_context_menu.is_some();
 5424        if has_context_menu {
 5425            return;
 5426        }
 5427
 5428        let hover_popovers = self.editor.update(cx, |editor, cx| {
 5429            editor.hover_state.render(
 5430                snapshot,
 5431                visible_display_row_range.clone(),
 5432                max_size,
 5433                &editor.text_layout_details(window, cx),
 5434                window,
 5435                cx,
 5436            )
 5437        });
 5438        let Some((popover_position, hover_popovers)) = hover_popovers else {
 5439            return;
 5440        };
 5441
 5442        // This is safe because we check on layout whether the required row is available
 5443        let hovered_row_layout = &line_layouts[popover_position
 5444            .row()
 5445            .minus(visible_display_row_range.start)
 5446            as usize];
 5447
 5448        // Compute Hovered Point
 5449        let x = hovered_row_layout.x_for_index(popover_position.column() as usize)
 5450            - Pixels::from(scroll_pixel_position.x);
 5451        let y = Pixels::from(
 5452            popover_position.row().as_f64() * ScrollPixelOffset::from(line_height)
 5453                - scroll_pixel_position.y,
 5454        );
 5455        let hovered_point = content_origin + point(x, y);
 5456
 5457        let mut overall_height = Pixels::ZERO;
 5458        let mut measured_hover_popovers = Vec::new();
 5459        for (position, mut hover_popover) in hover_popovers.into_iter().with_position() {
 5460            let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
 5461            let horizontal_offset =
 5462                (hitbox.top_right().x - POPOVER_RIGHT_OFFSET - (hovered_point.x + size.width))
 5463                    .min(Pixels::ZERO);
 5464            match position {
 5465                itertools::Position::Middle | itertools::Position::Last => {
 5466                    overall_height += HOVER_POPOVER_GAP
 5467                }
 5468                _ => {}
 5469            }
 5470            overall_height += size.height;
 5471            measured_hover_popovers.push(MeasuredHoverPopover {
 5472                element: hover_popover,
 5473                size,
 5474                horizontal_offset,
 5475            });
 5476        }
 5477
 5478        fn draw_occluder(
 5479            width: Pixels,
 5480            origin: gpui::Point<Pixels>,
 5481            window: &mut Window,
 5482            cx: &mut App,
 5483        ) {
 5484            let mut occlusion = div()
 5485                .size_full()
 5486                .occlude()
 5487                .on_mouse_move(|_, _, cx| cx.stop_propagation())
 5488                .into_any_element();
 5489            occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
 5490            window.defer_draw(occlusion, origin, 2, None);
 5491        }
 5492
 5493        fn place_popovers_above(
 5494            hovered_point: gpui::Point<Pixels>,
 5495            measured_hover_popovers: Vec<MeasuredHoverPopover>,
 5496            window: &mut Window,
 5497            cx: &mut App,
 5498        ) {
 5499            let mut current_y = hovered_point.y;
 5500            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 5501                let size = popover.size;
 5502                let popover_origin = point(
 5503                    hovered_point.x + popover.horizontal_offset,
 5504                    current_y - size.height,
 5505                );
 5506
 5507                window.defer_draw(popover.element, popover_origin, 2, None);
 5508                if position != itertools::Position::Last {
 5509                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
 5510                    draw_occluder(size.width, origin, window, cx);
 5511                }
 5512
 5513                current_y = popover_origin.y - HOVER_POPOVER_GAP;
 5514            }
 5515        }
 5516
 5517        fn place_popovers_below(
 5518            hovered_point: gpui::Point<Pixels>,
 5519            measured_hover_popovers: Vec<MeasuredHoverPopover>,
 5520            line_height: Pixels,
 5521            window: &mut Window,
 5522            cx: &mut App,
 5523        ) {
 5524            let mut current_y = hovered_point.y + line_height;
 5525            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 5526                let size = popover.size;
 5527                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
 5528
 5529                window.defer_draw(popover.element, popover_origin, 2, None);
 5530                if position != itertools::Position::Last {
 5531                    let origin = point(popover_origin.x, popover_origin.y + size.height);
 5532                    draw_occluder(size.width, origin, window, cx);
 5533                }
 5534
 5535                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 5536            }
 5537        }
 5538
 5539        let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
 5540            context_menu_layout
 5541                .as_ref()
 5542                .is_some_and(|menu| bounds.intersects(&menu.bounds))
 5543        };
 5544
 5545        let can_place_above = {
 5546            let mut bounds_above = Vec::new();
 5547            let mut current_y = hovered_point.y;
 5548            for popover in &measured_hover_popovers {
 5549                let size = popover.size;
 5550                let popover_origin = point(
 5551                    hovered_point.x + popover.horizontal_offset,
 5552                    current_y - size.height,
 5553                );
 5554                bounds_above.push(Bounds::new(popover_origin, size));
 5555                current_y = popover_origin.y - HOVER_POPOVER_GAP;
 5556            }
 5557            bounds_above
 5558                .iter()
 5559                .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
 5560        };
 5561
 5562        let can_place_below = || {
 5563            let mut bounds_below = Vec::new();
 5564            let mut current_y = hovered_point.y + line_height;
 5565            for popover in &measured_hover_popovers {
 5566                let size = popover.size;
 5567                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
 5568                bounds_below.push(Bounds::new(popover_origin, size));
 5569                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 5570            }
 5571            bounds_below
 5572                .iter()
 5573                .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
 5574        };
 5575
 5576        if can_place_above {
 5577            // try placing above hovered point
 5578            place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
 5579        } else if can_place_below() {
 5580            // try placing below hovered point
 5581            place_popovers_below(
 5582                hovered_point,
 5583                measured_hover_popovers,
 5584                line_height,
 5585                window,
 5586                cx,
 5587            );
 5588        } else {
 5589            // try to place popovers around the context menu
 5590            let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
 5591                let total_width = measured_hover_popovers
 5592                    .iter()
 5593                    .map(|p| p.size.width)
 5594                    .max()
 5595                    .unwrap_or(Pixels::ZERO);
 5596                let y_for_horizontal_positioning = if menu.y_flipped {
 5597                    menu.bounds.bottom() - overall_height
 5598                } else {
 5599                    menu.bounds.top()
 5600                };
 5601                let possible_origins = vec![
 5602                    // left of context menu
 5603                    point(
 5604                        menu.bounds.left() - total_width - HOVER_POPOVER_GAP,
 5605                        y_for_horizontal_positioning,
 5606                    ),
 5607                    // right of context menu
 5608                    point(
 5609                        menu.bounds.right() + HOVER_POPOVER_GAP,
 5610                        y_for_horizontal_positioning,
 5611                    ),
 5612                    // top of context menu
 5613                    point(
 5614                        menu.bounds.left(),
 5615                        menu.bounds.top() - overall_height - HOVER_POPOVER_GAP,
 5616                    ),
 5617                    // bottom of context menu
 5618                    point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
 5619                ];
 5620                possible_origins.into_iter().find(|&origin| {
 5621                    Bounds::new(origin, size(total_width, overall_height))
 5622                        .is_contained_within(hitbox)
 5623                })
 5624            });
 5625            if let Some(origin) = origin_surrounding_menu {
 5626                let mut current_y = origin.y;
 5627                for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 5628                    let size = popover.size;
 5629                    let popover_origin = point(origin.x, current_y);
 5630
 5631                    window.defer_draw(popover.element, popover_origin, 2, None);
 5632                    if position != itertools::Position::Last {
 5633                        let origin = point(popover_origin.x, popover_origin.y + size.height);
 5634                        draw_occluder(size.width, origin, window, cx);
 5635                    }
 5636
 5637                    current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 5638                }
 5639            } else {
 5640                // fallback to existing above/below cursor logic
 5641                // this might overlap menu or overflow in rare case
 5642                if can_place_above {
 5643                    place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
 5644                } else {
 5645                    place_popovers_below(
 5646                        hovered_point,
 5647                        measured_hover_popovers,
 5648                        line_height,
 5649                        window,
 5650                        cx,
 5651                    );
 5652                }
 5653            }
 5654        }
 5655    }
 5656
 5657    fn layout_word_diff_highlights(
 5658        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 5659        row_infos: &[RowInfo],
 5660        start_row: DisplayRow,
 5661        snapshot: &EditorSnapshot,
 5662        highlighted_ranges: &mut Vec<(Range<DisplayPoint>, Hsla)>,
 5663        cx: &mut App,
 5664    ) {
 5665        let colors = cx.theme().colors();
 5666
 5667        let word_highlights = display_hunks
 5668            .into_iter()
 5669            .filter_map(|(hunk, _)| match hunk {
 5670                DisplayDiffHunk::Unfolded {
 5671                    word_diffs, status, ..
 5672                } => Some((word_diffs, status)),
 5673                _ => None,
 5674            })
 5675            .filter(|(_, status)| status.is_modified())
 5676            .flat_map(|(word_diffs, _)| word_diffs)
 5677            .flat_map(|word_diff| {
 5678                let display_ranges = snapshot
 5679                    .display_snapshot
 5680                    .isomorphic_display_point_ranges_for_buffer_range(
 5681                        word_diff.start..word_diff.end,
 5682                    );
 5683
 5684                display_ranges.into_iter().filter_map(|range| {
 5685                    let start_row_offset = range.start.row().0.saturating_sub(start_row.0) as usize;
 5686
 5687                    let diff_status = row_infos
 5688                        .get(start_row_offset)
 5689                        .and_then(|row_info| row_info.diff_status)?;
 5690
 5691                    let background_color = match diff_status.kind {
 5692                        DiffHunkStatusKind::Added => colors.version_control_word_added,
 5693                        DiffHunkStatusKind::Deleted => colors.version_control_word_deleted,
 5694                        DiffHunkStatusKind::Modified => {
 5695                            debug_panic!("modified diff status for row info");
 5696                            return None;
 5697                        }
 5698                    };
 5699
 5700                    Some((range, background_color))
 5701                })
 5702            });
 5703
 5704        highlighted_ranges.extend(word_highlights);
 5705    }
 5706
 5707    fn layout_diff_hunk_controls(
 5708        &self,
 5709        row_range: Range<DisplayRow>,
 5710        row_infos: &[RowInfo],
 5711        text_hitbox: &Hitbox,
 5712        newest_cursor_row: Option<DisplayRow>,
 5713        line_height: Pixels,
 5714        right_margin: Pixels,
 5715        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 5716        sticky_header_height: Pixels,
 5717        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 5718        highlighted_rows: &BTreeMap<DisplayRow, LineHighlight>,
 5719        editor: Entity<Editor>,
 5720        window: &mut Window,
 5721        cx: &mut App,
 5722    ) -> (Vec<AnyElement>, Vec<(DisplayRow, Bounds<Pixels>)>) {
 5723        let render_diff_hunk_controls = editor.read(cx).render_diff_hunk_controls.clone();
 5724        let hovered_diff_hunk_row = editor.read(cx).hovered_diff_hunk_row;
 5725        let sticky_top = text_hitbox.bounds.top() + sticky_header_height;
 5726
 5727        let mut controls = vec![];
 5728        let mut control_bounds = vec![];
 5729
 5730        let active_rows = [hovered_diff_hunk_row, newest_cursor_row];
 5731
 5732        for (hunk, _) in display_hunks {
 5733            if let DisplayDiffHunk::Unfolded {
 5734                display_row_range,
 5735                multi_buffer_range,
 5736                status,
 5737                is_created_file,
 5738                ..
 5739            } = &hunk
 5740            {
 5741                if display_row_range.start >= row_range.end {
 5742                    // hunk is fully below the viewport
 5743                    continue;
 5744                }
 5745                if display_row_range.end <= row_range.start {
 5746                    // hunk is fully above the viewport
 5747                    continue;
 5748                }
 5749                let row_ix = display_row_range.start.0.saturating_sub(row_range.start.0);
 5750                if row_infos
 5751                    .get(row_ix as usize)
 5752                    .and_then(|row_info| row_info.diff_status)
 5753                    .is_none()
 5754                {
 5755                    continue;
 5756                }
 5757                if highlighted_rows
 5758                    .get(&display_row_range.start)
 5759                    .and_then(|highlight| highlight.type_id)
 5760                    .is_some_and(|type_id| {
 5761                        [
 5762                            TypeId::of::<ConflictsOuter>(),
 5763                            TypeId::of::<ConflictsOursMarker>(),
 5764                            TypeId::of::<ConflictsOurs>(),
 5765                            TypeId::of::<ConflictsTheirs>(),
 5766                            TypeId::of::<ConflictsTheirsMarker>(),
 5767                        ]
 5768                        .contains(&type_id)
 5769                    })
 5770                {
 5771                    continue;
 5772                }
 5773
 5774                if active_rows
 5775                    .iter()
 5776                    .any(|row| row.is_some_and(|row| display_row_range.contains(&row)))
 5777                {
 5778                    let hunk_start_y: Pixels = (display_row_range.start.as_f64()
 5779                        * ScrollPixelOffset::from(line_height)
 5780                        + ScrollPixelOffset::from(text_hitbox.bounds.top())
 5781                        - scroll_pixel_position.y)
 5782                        .into();
 5783
 5784                    let y: Pixels = if hunk_start_y >= sticky_top {
 5785                        hunk_start_y
 5786                    } else {
 5787                        let hunk_end_y: Pixels = hunk_start_y
 5788                            + (display_row_range.len() as f64
 5789                                * ScrollPixelOffset::from(line_height))
 5790                            .into();
 5791                        let max_y = hunk_end_y - line_height;
 5792                        sticky_top.min(max_y)
 5793                    };
 5794
 5795                    let mut element = render_diff_hunk_controls(
 5796                        display_row_range.start.0,
 5797                        status,
 5798                        multi_buffer_range.clone(),
 5799                        *is_created_file,
 5800                        line_height,
 5801                        &editor,
 5802                        window,
 5803                        cx,
 5804                    );
 5805                    let size =
 5806                        element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
 5807
 5808                    let x = text_hitbox.bounds.right() - right_margin - px(10.) - size.width;
 5809
 5810                    if x < text_hitbox.bounds.left() {
 5811                        continue;
 5812                    }
 5813
 5814                    let bounds = Bounds::new(gpui::Point::new(x, y), size);
 5815                    control_bounds.push((display_row_range.start, bounds));
 5816
 5817                    window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
 5818                        element.prepaint(window, cx)
 5819                    });
 5820                    controls.push(element);
 5821                }
 5822            }
 5823        }
 5824
 5825        (controls, control_bounds)
 5826    }
 5827
 5828    fn layout_signature_help(
 5829        &self,
 5830        hitbox: &Hitbox,
 5831        content_origin: gpui::Point<Pixels>,
 5832        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 5833        newest_selection_head: Option<DisplayPoint>,
 5834        start_row: DisplayRow,
 5835        line_layouts: &[LineWithInvisibles],
 5836        line_height: Pixels,
 5837        em_width: Pixels,
 5838        context_menu_layout: Option<ContextMenuLayout>,
 5839        window: &mut Window,
 5840        cx: &mut App,
 5841    ) {
 5842        if !self.editor.focus_handle(cx).is_focused(window) {
 5843            return;
 5844        }
 5845        let Some(newest_selection_head) = newest_selection_head else {
 5846            return;
 5847        };
 5848
 5849        let max_size = size(
 5850            (120. * em_width) // Default size
 5851                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
 5852                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
 5853            (16. * line_height) // Default size
 5854                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
 5855                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
 5856        );
 5857
 5858        let maybe_element = self.editor.update(cx, |editor, cx| {
 5859            if let Some(popover) = editor.signature_help_state.popover_mut() {
 5860                let element = popover.render(max_size, window, cx);
 5861                Some(element)
 5862            } else {
 5863                None
 5864            }
 5865        });
 5866        let Some(mut element) = maybe_element else {
 5867            return;
 5868        };
 5869
 5870        let selection_row = newest_selection_head.row();
 5871        let Some(cursor_row_layout) = (selection_row >= start_row)
 5872            .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
 5873            .flatten()
 5874        else {
 5875            return;
 5876        };
 5877
 5878        let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
 5879            - Pixels::from(scroll_pixel_position.x);
 5880        let target_y = Pixels::from(
 5881            selection_row.as_f64() * ScrollPixelOffset::from(line_height) - scroll_pixel_position.y,
 5882        );
 5883        let target_point = content_origin + point(target_x, target_y);
 5884
 5885        let actual_size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
 5886
 5887        let (popover_bounds_above, popover_bounds_below) = {
 5888            let horizontal_offset = (hitbox.top_right().x
 5889                - POPOVER_RIGHT_OFFSET
 5890                - (target_point.x + actual_size.width))
 5891                .min(Pixels::ZERO);
 5892            let initial_x = target_point.x + horizontal_offset;
 5893            (
 5894                Bounds::new(
 5895                    point(initial_x, target_point.y - actual_size.height),
 5896                    actual_size,
 5897                ),
 5898                Bounds::new(
 5899                    point(initial_x, target_point.y + line_height + HOVER_POPOVER_GAP),
 5900                    actual_size,
 5901                ),
 5902            )
 5903        };
 5904
 5905        let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
 5906            context_menu_layout
 5907                .as_ref()
 5908                .is_some_and(|menu| bounds.intersects(&menu.bounds))
 5909        };
 5910
 5911        let final_origin = if popover_bounds_above.is_contained_within(hitbox)
 5912            && !intersects_menu(popover_bounds_above)
 5913        {
 5914            // try placing above cursor
 5915            popover_bounds_above.origin
 5916        } else if popover_bounds_below.is_contained_within(hitbox)
 5917            && !intersects_menu(popover_bounds_below)
 5918        {
 5919            // try placing below cursor
 5920            popover_bounds_below.origin
 5921        } else {
 5922            // try surrounding context menu if exists
 5923            let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
 5924                let y_for_horizontal_positioning = if menu.y_flipped {
 5925                    menu.bounds.bottom() - actual_size.height
 5926                } else {
 5927                    menu.bounds.top()
 5928                };
 5929                let possible_origins = vec![
 5930                    // left of context menu
 5931                    point(
 5932                        menu.bounds.left() - actual_size.width - HOVER_POPOVER_GAP,
 5933                        y_for_horizontal_positioning,
 5934                    ),
 5935                    // right of context menu
 5936                    point(
 5937                        menu.bounds.right() + HOVER_POPOVER_GAP,
 5938                        y_for_horizontal_positioning,
 5939                    ),
 5940                    // top of context menu
 5941                    point(
 5942                        menu.bounds.left(),
 5943                        menu.bounds.top() - actual_size.height - HOVER_POPOVER_GAP,
 5944                    ),
 5945                    // bottom of context menu
 5946                    point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
 5947                ];
 5948                possible_origins
 5949                    .into_iter()
 5950                    .find(|&origin| Bounds::new(origin, actual_size).is_contained_within(hitbox))
 5951            });
 5952            origin_surrounding_menu.unwrap_or_else(|| {
 5953                // fallback to existing above/below cursor logic
 5954                // this might overlap menu or overflow in rare case
 5955                if popover_bounds_above.is_contained_within(hitbox) {
 5956                    popover_bounds_above.origin
 5957                } else {
 5958                    popover_bounds_below.origin
 5959                }
 5960            })
 5961        };
 5962
 5963        window.defer_draw(element, final_origin, 2, None);
 5964    }
 5965
 5966    fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
 5967        window.paint_layer(layout.hitbox.bounds, |window| {
 5968            let scroll_top = layout.position_map.snapshot.scroll_position().y;
 5969            let gutter_bg = cx.theme().colors().editor_gutter_background;
 5970            window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
 5971            window.paint_quad(fill(
 5972                layout.position_map.text_hitbox.bounds,
 5973                self.style.background,
 5974            ));
 5975
 5976            if matches!(
 5977                layout.mode,
 5978                EditorMode::Full { .. } | EditorMode::Minimap { .. }
 5979            ) {
 5980                let show_active_line_background = match layout.mode {
 5981                    EditorMode::Full {
 5982                        show_active_line_background,
 5983                        ..
 5984                    } => show_active_line_background,
 5985                    EditorMode::Minimap { .. } => true,
 5986                    _ => false,
 5987                };
 5988                let mut active_rows = layout.active_rows.iter().peekable();
 5989                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
 5990                    let mut end_row = start_row.0;
 5991                    while active_rows
 5992                        .peek()
 5993                        .is_some_and(|(active_row, has_selection)| {
 5994                            active_row.0 == end_row + 1
 5995                                && has_selection.selection == contains_non_empty_selection.selection
 5996                        })
 5997                    {
 5998                        active_rows.next().unwrap();
 5999                        end_row += 1;
 6000                    }
 6001
 6002                    if show_active_line_background && !contains_non_empty_selection.selection {
 6003                        let highlight_h_range =
 6004                            match layout.position_map.snapshot.current_line_highlight {
 6005                                CurrentLineHighlight::Gutter => Some(Range {
 6006                                    start: layout.hitbox.left(),
 6007                                    end: layout.gutter_hitbox.right(),
 6008                                }),
 6009                                CurrentLineHighlight::Line => Some(Range {
 6010                                    start: layout.position_map.text_hitbox.bounds.left(),
 6011                                    end: layout.position_map.text_hitbox.bounds.right(),
 6012                                }),
 6013                                CurrentLineHighlight::All => Some(Range {
 6014                                    start: layout.hitbox.left(),
 6015                                    end: layout.hitbox.right(),
 6016                                }),
 6017                                CurrentLineHighlight::None => None,
 6018                            };
 6019                        if let Some(range) = highlight_h_range {
 6020                            let active_line_bg = cx.theme().colors().editor_active_line_background;
 6021                            let bounds = Bounds {
 6022                                origin: point(
 6023                                    range.start,
 6024                                    layout.hitbox.origin.y
 6025                                        + Pixels::from(
 6026                                            (start_row.as_f64() - scroll_top)
 6027                                                * ScrollPixelOffset::from(
 6028                                                    layout.position_map.line_height,
 6029                                                ),
 6030                                        ),
 6031                                ),
 6032                                size: size(
 6033                                    range.end - range.start,
 6034                                    layout.position_map.line_height
 6035                                        * (end_row - start_row.0 + 1) as f32,
 6036                                ),
 6037                            };
 6038                            window.paint_quad(fill(bounds, active_line_bg));
 6039                        }
 6040                    }
 6041                }
 6042
 6043                let mut paint_highlight = |highlight_row_start: DisplayRow,
 6044                                           highlight_row_end: DisplayRow,
 6045                                           highlight: crate::LineHighlight,
 6046                                           edges| {
 6047                    let mut origin_x = layout.hitbox.left();
 6048                    let mut width = layout.hitbox.size.width;
 6049                    if !highlight.include_gutter {
 6050                        origin_x += layout.gutter_hitbox.size.width;
 6051                        width -= layout.gutter_hitbox.size.width;
 6052                    }
 6053
 6054                    let origin = point(
 6055                        origin_x,
 6056                        layout.hitbox.origin.y
 6057                            + Pixels::from(
 6058                                (highlight_row_start.as_f64() - scroll_top)
 6059                                    * ScrollPixelOffset::from(layout.position_map.line_height),
 6060                            ),
 6061                    );
 6062                    let size = size(
 6063                        width,
 6064                        layout.position_map.line_height
 6065                            * highlight_row_end.next_row().minus(highlight_row_start) as f32,
 6066                    );
 6067                    let mut quad = fill(Bounds { origin, size }, highlight.background);
 6068                    if let Some(border_color) = highlight.border {
 6069                        quad.border_color = border_color;
 6070                        quad.border_widths = edges
 6071                    }
 6072                    window.paint_quad(quad);
 6073                };
 6074
 6075                let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
 6076                    None;
 6077                for (&new_row, &new_background) in &layout.highlighted_rows {
 6078                    match &mut current_paint {
 6079                        &mut Some((current_background, ref mut current_range, mut edges)) => {
 6080                            let new_range_started = current_background != new_background
 6081                                || current_range.end.next_row() != new_row;
 6082                            if new_range_started {
 6083                                if current_range.end.next_row() == new_row {
 6084                                    edges.bottom = px(0.);
 6085                                };
 6086                                paint_highlight(
 6087                                    current_range.start,
 6088                                    current_range.end,
 6089                                    current_background,
 6090                                    edges,
 6091                                );
 6092                                let edges = Edges {
 6093                                    top: if current_range.end.next_row() != new_row {
 6094                                        px(1.)
 6095                                    } else {
 6096                                        px(0.)
 6097                                    },
 6098                                    bottom: px(1.),
 6099                                    ..Default::default()
 6100                                };
 6101                                current_paint = Some((new_background, new_row..new_row, edges));
 6102                                continue;
 6103                            } else {
 6104                                current_range.end = current_range.end.next_row();
 6105                            }
 6106                        }
 6107                        None => {
 6108                            let edges = Edges {
 6109                                top: px(1.),
 6110                                bottom: px(1.),
 6111                                ..Default::default()
 6112                            };
 6113                            current_paint = Some((new_background, new_row..new_row, edges))
 6114                        }
 6115                    };
 6116                }
 6117                if let Some((color, range, edges)) = current_paint {
 6118                    paint_highlight(range.start, range.end, color, edges);
 6119                }
 6120
 6121                for (guide_x, active) in layout.wrap_guides.iter() {
 6122                    let color = if *active {
 6123                        cx.theme().colors().editor_active_wrap_guide
 6124                    } else {
 6125                        cx.theme().colors().editor_wrap_guide
 6126                    };
 6127                    window.paint_quad(fill(
 6128                        Bounds {
 6129                            origin: point(*guide_x, layout.position_map.text_hitbox.origin.y),
 6130                            size: size(px(1.), layout.position_map.text_hitbox.size.height),
 6131                        },
 6132                        color,
 6133                    ));
 6134                }
 6135            }
 6136        })
 6137    }
 6138
 6139    fn paint_indent_guides(
 6140        &mut self,
 6141        layout: &mut EditorLayout,
 6142        window: &mut Window,
 6143        cx: &mut App,
 6144    ) {
 6145        let Some(indent_guides) = &layout.indent_guides else {
 6146            return;
 6147        };
 6148
 6149        let faded_color = |color: Hsla, alpha: f32| {
 6150            let mut faded = color;
 6151            faded.a = alpha;
 6152            faded
 6153        };
 6154
 6155        for indent_guide in indent_guides {
 6156            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
 6157            let settings = &indent_guide.settings;
 6158
 6159            // TODO fixed for now, expose them through themes later
 6160            const INDENT_AWARE_ALPHA: f32 = 0.2;
 6161            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
 6162            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
 6163            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
 6164
 6165            let line_color = match (settings.coloring, indent_guide.active) {
 6166                (IndentGuideColoring::Disabled, _) => None,
 6167                (IndentGuideColoring::Fixed, false) => {
 6168                    Some(cx.theme().colors().editor_indent_guide)
 6169                }
 6170                (IndentGuideColoring::Fixed, true) => {
 6171                    Some(cx.theme().colors().editor_indent_guide_active)
 6172                }
 6173                (IndentGuideColoring::IndentAware, false) => {
 6174                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
 6175                }
 6176                (IndentGuideColoring::IndentAware, true) => {
 6177                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
 6178                }
 6179            };
 6180
 6181            let background_color = match (settings.background_coloring, indent_guide.active) {
 6182                (IndentGuideBackgroundColoring::Disabled, _) => None,
 6183                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
 6184                    indent_accent_colors,
 6185                    INDENT_AWARE_BACKGROUND_ALPHA,
 6186                )),
 6187                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
 6188                    indent_accent_colors,
 6189                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
 6190                )),
 6191            };
 6192
 6193            let mut line_indicator_width = 0.;
 6194            if let Some(requested_line_width) = settings.visible_line_width(indent_guide.active) {
 6195                if let Some(color) = line_color {
 6196                    window.paint_quad(fill(
 6197                        Bounds {
 6198                            origin: indent_guide.origin,
 6199                            size: size(px(requested_line_width as f32), indent_guide.length),
 6200                        },
 6201                        color,
 6202                    ));
 6203                    line_indicator_width = requested_line_width as f32;
 6204                }
 6205            }
 6206
 6207            if let Some(color) = background_color {
 6208                let width = indent_guide.single_indent_width - px(line_indicator_width);
 6209                window.paint_quad(fill(
 6210                    Bounds {
 6211                        origin: point(
 6212                            indent_guide.origin.x + px(line_indicator_width),
 6213                            indent_guide.origin.y,
 6214                        ),
 6215                        size: size(width, indent_guide.length),
 6216                    },
 6217                    color,
 6218                ));
 6219            }
 6220        }
 6221    }
 6222
 6223    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6224        let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
 6225
 6226        let line_height = layout.position_map.line_height;
 6227        window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
 6228
 6229        for line_layout in layout.line_numbers.values() {
 6230            for LineNumberSegment {
 6231                shaped_line,
 6232                hitbox,
 6233            } in &line_layout.segments
 6234            {
 6235                let Some(hitbox) = hitbox else {
 6236                    continue;
 6237                };
 6238
 6239                let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
 6240                    let color = cx.theme().colors().editor_hover_line_number;
 6241
 6242                    let line = self.shape_line_number(shaped_line.text.clone(), color, window);
 6243                    line.paint(
 6244                        hitbox.origin,
 6245                        line_height,
 6246                        TextAlign::Left,
 6247                        None,
 6248                        window,
 6249                        cx,
 6250                    )
 6251                    .log_err()
 6252                } else {
 6253                    shaped_line
 6254                        .paint(
 6255                            hitbox.origin,
 6256                            line_height,
 6257                            TextAlign::Left,
 6258                            None,
 6259                            window,
 6260                            cx,
 6261                        )
 6262                        .log_err()
 6263                }) else {
 6264                    continue;
 6265                };
 6266
 6267                // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
 6268                // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
 6269                if is_singleton {
 6270                    window.set_cursor_style(CursorStyle::IBeam, hitbox);
 6271                } else {
 6272                    window.set_cursor_style(CursorStyle::PointingHand, hitbox);
 6273                }
 6274            }
 6275        }
 6276    }
 6277
 6278    fn paint_gutter_diff_hunks(
 6279        layout: &mut EditorLayout,
 6280        split_side: Option<SplitSide>,
 6281        window: &mut Window,
 6282        cx: &mut App,
 6283    ) {
 6284        if layout.display_hunks.is_empty() {
 6285            return;
 6286        }
 6287
 6288        let line_height = layout.position_map.line_height;
 6289        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6290            for (hunk, hitbox) in &layout.display_hunks {
 6291                let hunk_to_paint = match hunk {
 6292                    DisplayDiffHunk::Folded { .. } => {
 6293                        let hunk_bounds = Self::diff_hunk_bounds(
 6294                            &layout.position_map.snapshot,
 6295                            line_height,
 6296                            layout.gutter_hitbox.bounds,
 6297                            hunk,
 6298                        );
 6299                        Some((
 6300                            hunk_bounds,
 6301                            cx.theme().colors().version_control_modified,
 6302                            Corners::all(px(0.)),
 6303                            DiffHunkStatus::modified_none(),
 6304                        ))
 6305                    }
 6306                    DisplayDiffHunk::Unfolded {
 6307                        status,
 6308                        display_row_range,
 6309                        ..
 6310                    } => hitbox.as_ref().map(|hunk_hitbox| {
 6311                        let color = match split_side {
 6312                            Some(SplitSide::Left) => cx.theme().colors().version_control_deleted,
 6313                            Some(SplitSide::Right) => cx.theme().colors().version_control_added,
 6314                            None => match status.kind {
 6315                                DiffHunkStatusKind::Added => {
 6316                                    cx.theme().colors().version_control_added
 6317                                }
 6318                                DiffHunkStatusKind::Modified => {
 6319                                    cx.theme().colors().version_control_modified
 6320                                }
 6321                                DiffHunkStatusKind::Deleted => {
 6322                                    cx.theme().colors().version_control_deleted
 6323                                }
 6324                            },
 6325                        };
 6326                        match status.kind {
 6327                            DiffHunkStatusKind::Deleted if display_row_range.is_empty() => (
 6328                                Bounds::new(
 6329                                    point(
 6330                                        hunk_hitbox.origin.x - hunk_hitbox.size.width,
 6331                                        hunk_hitbox.origin.y,
 6332                                    ),
 6333                                    size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
 6334                                ),
 6335                                color,
 6336                                Corners::all(1. * line_height),
 6337                                *status,
 6338                            ),
 6339                            _ => (hunk_hitbox.bounds, color, Corners::all(px(0.)), *status),
 6340                        }
 6341                    }),
 6342                };
 6343
 6344                if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
 6345                    // Flatten the background color with the editor color to prevent
 6346                    // elements below transparent hunks from showing through
 6347                    let flattened_background_color = cx
 6348                        .theme()
 6349                        .colors()
 6350                        .editor_background
 6351                        .blend(background_color);
 6352
 6353                    if !Self::diff_hunk_hollow(status, cx) {
 6354                        window.paint_quad(quad(
 6355                            hunk_bounds,
 6356                            corner_radii,
 6357                            flattened_background_color,
 6358                            Edges::default(),
 6359                            transparent_black(),
 6360                            BorderStyle::default(),
 6361                        ));
 6362                    } else {
 6363                        let flattened_unstaged_background_color = cx
 6364                            .theme()
 6365                            .colors()
 6366                            .editor_background
 6367                            .blend(background_color.opacity(0.3));
 6368
 6369                        window.paint_quad(quad(
 6370                            hunk_bounds,
 6371                            corner_radii,
 6372                            flattened_unstaged_background_color,
 6373                            Edges::all(px(1.0)),
 6374                            flattened_background_color,
 6375                            BorderStyle::Solid,
 6376                        ));
 6377                    }
 6378                }
 6379            }
 6380        });
 6381    }
 6382
 6383    fn gutter_strip_width(line_height: Pixels) -> Pixels {
 6384        (0.275 * line_height).floor()
 6385    }
 6386
 6387    fn diff_hunk_bounds(
 6388        snapshot: &EditorSnapshot,
 6389        line_height: Pixels,
 6390        gutter_bounds: Bounds<Pixels>,
 6391        hunk: &DisplayDiffHunk,
 6392    ) -> Bounds<Pixels> {
 6393        let scroll_position = snapshot.scroll_position();
 6394        let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
 6395        let gutter_strip_width = Self::gutter_strip_width(line_height);
 6396
 6397        match hunk {
 6398            DisplayDiffHunk::Folded { display_row, .. } => {
 6399                let start_y = (display_row.as_f64() * ScrollPixelOffset::from(line_height)
 6400                    - scroll_top)
 6401                    .into();
 6402                let end_y = start_y + line_height;
 6403                let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 6404                let highlight_size = size(gutter_strip_width, end_y - start_y);
 6405                Bounds::new(highlight_origin, highlight_size)
 6406            }
 6407            DisplayDiffHunk::Unfolded {
 6408                display_row_range,
 6409                status,
 6410                ..
 6411            } => {
 6412                if status.is_deleted() && display_row_range.is_empty() {
 6413                    let row = display_row_range.start;
 6414
 6415                    let offset = ScrollPixelOffset::from(line_height / 2.);
 6416                    let start_y =
 6417                        (row.as_f64() * ScrollPixelOffset::from(line_height) - offset - scroll_top)
 6418                            .into();
 6419                    let end_y = start_y + line_height;
 6420
 6421                    let width = (0.35 * line_height).floor();
 6422                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 6423                    let highlight_size = size(width, end_y - start_y);
 6424                    Bounds::new(highlight_origin, highlight_size)
 6425                } else {
 6426                    let start_row = display_row_range.start;
 6427                    let end_row = display_row_range.end;
 6428                    // If we're in a multibuffer, row range span might include an
 6429                    // excerpt header, so if we were to draw the marker straight away,
 6430                    // the hunk might include the rows of that header.
 6431                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
 6432                    // Instead, we simply check whether the range we're dealing with includes
 6433                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
 6434                    let end_row_in_current_excerpt = snapshot
 6435                        .blocks_in_range(start_row..end_row)
 6436                        .find_map(|(start_row, block)| {
 6437                            if matches!(
 6438                                block,
 6439                                Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
 6440                            ) {
 6441                                Some(start_row)
 6442                            } else {
 6443                                None
 6444                            }
 6445                        })
 6446                        .unwrap_or(end_row);
 6447
 6448                    let start_y = (start_row.as_f64() * ScrollPixelOffset::from(line_height)
 6449                        - scroll_top)
 6450                        .into();
 6451                    let end_y = Pixels::from(
 6452                        end_row_in_current_excerpt.as_f64() * ScrollPixelOffset::from(line_height)
 6453                            - scroll_top,
 6454                    );
 6455
 6456                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 6457                    let highlight_size = size(gutter_strip_width, end_y - start_y);
 6458                    Bounds::new(highlight_origin, highlight_size)
 6459                }
 6460            }
 6461        }
 6462    }
 6463
 6464    fn paint_gutter_indicators(
 6465        &self,
 6466        layout: &mut EditorLayout,
 6467        window: &mut Window,
 6468        cx: &mut App,
 6469    ) {
 6470        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6471            window.with_element_namespace("crease_toggles", |window| {
 6472                for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
 6473                    crease_toggle.paint(window, cx);
 6474                }
 6475            });
 6476
 6477            window.with_element_namespace("expand_toggles", |window| {
 6478                for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
 6479                    expand_toggle.paint(window, cx);
 6480                }
 6481            });
 6482
 6483            for bookmark in layout.bookmarks.iter_mut() {
 6484                bookmark.paint(window, cx);
 6485            }
 6486
 6487            for breakpoint in layout.breakpoints.iter_mut() {
 6488                breakpoint.paint(window, cx);
 6489            }
 6490
 6491            for test_indicator in layout.test_indicators.iter_mut() {
 6492                test_indicator.paint(window, cx);
 6493            }
 6494
 6495            if let Some(diff_review_button) = layout.diff_review_button.as_mut() {
 6496                diff_review_button.paint(window, cx);
 6497            }
 6498        });
 6499    }
 6500
 6501    fn paint_gutter_highlights(
 6502        &self,
 6503        layout: &mut EditorLayout,
 6504        window: &mut Window,
 6505        cx: &mut App,
 6506    ) {
 6507        for (_, hunk_hitbox) in &layout.display_hunks {
 6508            if let Some(hunk_hitbox) = hunk_hitbox
 6509                && !self
 6510                    .editor
 6511                    .read(cx)
 6512                    .buffer()
 6513                    .read(cx)
 6514                    .all_diff_hunks_expanded()
 6515            {
 6516                window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
 6517            }
 6518        }
 6519
 6520        let show_git_gutter = layout
 6521            .position_map
 6522            .snapshot
 6523            .show_git_diff_gutter
 6524            .unwrap_or_else(|| {
 6525                matches!(
 6526                    ProjectSettings::get_global(cx).git.git_gutter,
 6527                    GitGutterSetting::TrackedFiles
 6528                )
 6529            });
 6530        if show_git_gutter {
 6531            Self::paint_gutter_diff_hunks(layout, self.split_side, window, cx)
 6532        }
 6533
 6534        let highlight_width = 0.275 * layout.position_map.line_height;
 6535        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
 6536        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6537            for (range, color) in &layout.highlighted_gutter_ranges {
 6538                let start_row = if range.start.row() < layout.visible_display_row_range.start {
 6539                    layout.visible_display_row_range.start - DisplayRow(1)
 6540                } else {
 6541                    range.start.row()
 6542                };
 6543                let end_row = if range.end.row() > layout.visible_display_row_range.end {
 6544                    layout.visible_display_row_range.end + DisplayRow(1)
 6545                } else {
 6546                    range.end.row()
 6547                };
 6548
 6549                let start_y = layout.gutter_hitbox.top()
 6550                    + Pixels::from(
 6551                        start_row.0 as f64
 6552                            * ScrollPixelOffset::from(layout.position_map.line_height)
 6553                            - layout.position_map.scroll_pixel_position.y,
 6554                    );
 6555                let end_y = layout.gutter_hitbox.top()
 6556                    + Pixels::from(
 6557                        (end_row.0 + 1) as f64
 6558                            * ScrollPixelOffset::from(layout.position_map.line_height)
 6559                            - layout.position_map.scroll_pixel_position.y,
 6560                    );
 6561                let bounds = Bounds::from_corners(
 6562                    point(layout.gutter_hitbox.left(), start_y),
 6563                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
 6564                );
 6565                window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
 6566            }
 6567        });
 6568    }
 6569
 6570    fn paint_blamed_display_rows(
 6571        &self,
 6572        layout: &mut EditorLayout,
 6573        window: &mut Window,
 6574        cx: &mut App,
 6575    ) {
 6576        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
 6577            return;
 6578        };
 6579
 6580        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6581            for mut blame_element in blamed_display_rows.into_iter() {
 6582                blame_element.paint(window, cx);
 6583            }
 6584        })
 6585    }
 6586
 6587    fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6588        window.with_content_mask(
 6589            Some(ContentMask {
 6590                bounds: layout.position_map.text_hitbox.bounds,
 6591            }),
 6592            |window| {
 6593                let editor = self.editor.read(cx);
 6594                if editor.mouse_cursor_hidden {
 6595                    window.set_window_cursor_style(CursorStyle::None);
 6596                } else if let SelectionDragState::ReadyToDrag {
 6597                    mouse_down_time, ..
 6598                } = &editor.selection_drag_state
 6599                {
 6600                    let drag_and_drop_delay = Duration::from_millis(
 6601                        EditorSettings::get_global(cx)
 6602                            .drag_and_drop_selection
 6603                            .delay
 6604                            .0,
 6605                    );
 6606                    if mouse_down_time.elapsed() >= drag_and_drop_delay {
 6607                        window.set_cursor_style(
 6608                            CursorStyle::DragCopy,
 6609                            &layout.position_map.text_hitbox,
 6610                        );
 6611                    }
 6612                } else if matches!(
 6613                    editor.selection_drag_state,
 6614                    SelectionDragState::Dragging { .. }
 6615                ) {
 6616                    window
 6617                        .set_cursor_style(CursorStyle::DragCopy, &layout.position_map.text_hitbox);
 6618                } else if editor
 6619                    .hovered_link_state
 6620                    .as_ref()
 6621                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
 6622                {
 6623                    window.set_cursor_style(
 6624                        CursorStyle::PointingHand,
 6625                        &layout.position_map.text_hitbox,
 6626                    );
 6627                } else {
 6628                    window.set_cursor_style(CursorStyle::IBeam, &layout.position_map.text_hitbox);
 6629                };
 6630
 6631                self.paint_lines_background(layout, window, cx);
 6632                let invisible_display_ranges = self.paint_highlights(layout, window, cx);
 6633                self.paint_document_colors(layout, window);
 6634                self.paint_lines(&invisible_display_ranges, layout, window, cx);
 6635                self.paint_redactions(layout, window);
 6636                self.paint_navigation_overlays(layout, window, cx);
 6637                self.paint_cursors(layout, window, cx);
 6638                self.paint_inline_diagnostics(layout, window, cx);
 6639                self.paint_inline_blame(layout, window, cx);
 6640                self.paint_inline_code_actions(layout, window, cx);
 6641                self.paint_diff_hunk_controls(layout, window, cx);
 6642                window.with_element_namespace("crease_trailers", |window| {
 6643                    for trailer in layout.crease_trailers.iter_mut().flatten() {
 6644                        trailer.element.paint(window, cx);
 6645                    }
 6646                });
 6647            },
 6648        )
 6649    }
 6650
 6651    fn paint_highlights(
 6652        &mut self,
 6653        layout: &mut EditorLayout,
 6654        window: &mut Window,
 6655        cx: &mut App,
 6656    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
 6657        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6658            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
 6659            let line_end_overshoot = 0.15 * layout.position_map.line_height;
 6660            for (range, color) in &layout.highlighted_ranges {
 6661                self.paint_highlighted_range(
 6662                    range.clone(),
 6663                    true,
 6664                    *color,
 6665                    Pixels::ZERO,
 6666                    line_end_overshoot,
 6667                    layout,
 6668                    window,
 6669                );
 6670            }
 6671
 6672            let corner_radius = if EditorSettings::get_global(cx).rounded_selection {
 6673                0.15 * layout.position_map.line_height
 6674            } else {
 6675                Pixels::ZERO
 6676            };
 6677
 6678            for (player_color, selections) in &layout.selections {
 6679                for selection in selections.iter() {
 6680                    self.paint_highlighted_range(
 6681                        selection.range.clone(),
 6682                        true,
 6683                        player_color.selection,
 6684                        corner_radius,
 6685                        corner_radius * 2.,
 6686                        layout,
 6687                        window,
 6688                    );
 6689
 6690                    if selection.is_local && !selection.range.is_empty() {
 6691                        invisible_display_ranges.push(selection.range.clone());
 6692                    }
 6693                }
 6694            }
 6695            invisible_display_ranges
 6696        })
 6697    }
 6698
 6699    fn paint_lines(
 6700        &mut self,
 6701        invisible_display_ranges: &[Range<DisplayPoint>],
 6702        layout: &mut EditorLayout,
 6703        window: &mut Window,
 6704        cx: &mut App,
 6705    ) {
 6706        let whitespace_setting = self
 6707            .editor
 6708            .read(cx)
 6709            .buffer
 6710            .read(cx)
 6711            .language_settings(cx)
 6712            .show_whitespaces;
 6713
 6714        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
 6715            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
 6716            line_with_invisibles.draw(
 6717                layout,
 6718                row,
 6719                layout.content_origin,
 6720                whitespace_setting,
 6721                invisible_display_ranges,
 6722                window,
 6723                cx,
 6724            )
 6725        }
 6726
 6727        for line_element in &mut layout.line_elements {
 6728            line_element.paint(window, cx);
 6729        }
 6730    }
 6731
 6732    fn paint_sticky_headers(
 6733        &mut self,
 6734        layout: &mut EditorLayout,
 6735        window: &mut Window,
 6736        cx: &mut App,
 6737    ) {
 6738        let Some(mut sticky_headers) = layout.sticky_headers.take() else {
 6739            return;
 6740        };
 6741
 6742        if sticky_headers.lines.is_empty() {
 6743            layout.sticky_headers = Some(sticky_headers);
 6744            return;
 6745        }
 6746
 6747        let whitespace_setting = self
 6748            .editor
 6749            .read(cx)
 6750            .buffer
 6751            .read(cx)
 6752            .language_settings(cx)
 6753            .show_whitespaces;
 6754        sticky_headers.paint(layout, whitespace_setting, window, cx);
 6755
 6756        let sticky_header_hitboxes: Vec<Hitbox> = sticky_headers
 6757            .lines
 6758            .iter()
 6759            .map(|line| line.hitbox.clone())
 6760            .collect();
 6761        let hovered_hitbox = sticky_header_hitboxes
 6762            .iter()
 6763            .find_map(|hitbox| hitbox.is_hovered(window).then_some(hitbox.id));
 6764
 6765        window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, _cx| {
 6766            if !phase.bubble() {
 6767                return;
 6768            }
 6769
 6770            let current_hover = sticky_header_hitboxes
 6771                .iter()
 6772                .find_map(|hitbox| hitbox.is_hovered(window).then_some(hitbox.id));
 6773            if hovered_hitbox != current_hover {
 6774                window.refresh();
 6775            }
 6776        });
 6777
 6778        let position_map = layout.position_map.clone();
 6779
 6780        for (line_index, line) in sticky_headers.lines.iter().enumerate() {
 6781            let editor = self.editor.clone();
 6782            let hitbox = line.hitbox.clone();
 6783            let row = line.row;
 6784            let line_layout = line.line.clone();
 6785            let position_map = position_map.clone();
 6786            window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
 6787                if !phase.bubble() {
 6788                    return;
 6789                }
 6790
 6791                if event.button == MouseButton::Left && hitbox.is_hovered(window) {
 6792                    let point_for_position =
 6793                        position_map.point_for_position_on_line(event.position, row, &line_layout);
 6794
 6795                    editor.update(cx, |editor, cx| {
 6796                        let snapshot = editor.snapshot(window, cx);
 6797                        let anchor = snapshot
 6798                            .display_snapshot
 6799                            .display_point_to_anchor(point_for_position.nearest_valid, Bias::Left);
 6800                        editor.change_selections(
 6801                            SelectionEffects::scroll(Autoscroll::top_relative(line_index)),
 6802                            window,
 6803                            cx,
 6804                            |selections| {
 6805                                selections.clear_disjoint();
 6806                                selections.set_pending_anchor_range(
 6807                                    anchor..anchor,
 6808                                    crate::SelectMode::Character,
 6809                                );
 6810                            },
 6811                        );
 6812                        cx.stop_propagation();
 6813                    });
 6814                }
 6815            });
 6816        }
 6817
 6818        let text_bounds = layout.position_map.text_hitbox.bounds;
 6819        let border_top = text_bounds.top()
 6820            + sticky_headers.lines.last().unwrap().offset
 6821            + layout.position_map.line_height;
 6822        let separator_height = px(1.);
 6823        let border_bounds = Bounds::from_corners(
 6824            point(layout.gutter_hitbox.bounds.left(), border_top),
 6825            point(text_bounds.right(), border_top + separator_height),
 6826        );
 6827        window.paint_quad(fill(border_bounds, cx.theme().colors().border_variant));
 6828
 6829        layout.sticky_headers = Some(sticky_headers);
 6830    }
 6831
 6832    fn paint_lines_background(
 6833        &mut self,
 6834        layout: &mut EditorLayout,
 6835        window: &mut Window,
 6836        cx: &mut App,
 6837    ) {
 6838        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
 6839            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
 6840            line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
 6841        }
 6842    }
 6843
 6844    fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
 6845        if layout.redacted_ranges.is_empty() {
 6846            return;
 6847        }
 6848
 6849        let line_end_overshoot = layout.line_end_overshoot();
 6850
 6851        // A softer than perfect black
 6852        let redaction_color = gpui::rgb(0x0e1111);
 6853
 6854        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6855            for range in layout.redacted_ranges.iter() {
 6856                self.paint_highlighted_range(
 6857                    range.clone(),
 6858                    true,
 6859                    redaction_color.into(),
 6860                    Pixels::ZERO,
 6861                    line_end_overshoot,
 6862                    layout,
 6863                    window,
 6864                );
 6865            }
 6866        });
 6867    }
 6868
 6869    fn paint_navigation_overlays(
 6870        &mut self,
 6871        layout: &mut EditorLayout,
 6872        window: &mut Window,
 6873        cx: &mut App,
 6874    ) {
 6875        window.with_element_namespace("navigation_overlays", |window| {
 6876            for command in &mut layout.navigation_overlay_paint_commands {
 6877                let NavigationOverlayPaintCommand::Label(label) = command;
 6878                label.element.paint(window, cx);
 6879            }
 6880        });
 6881    }
 6882
 6883    fn paint_document_colors(&self, layout: &mut EditorLayout, window: &mut Window) {
 6884        let Some((colors_render_mode, image_colors)) = &layout.document_colors else {
 6885            return;
 6886        };
 6887        if image_colors.is_empty()
 6888            || colors_render_mode == &DocumentColorsRenderMode::None
 6889            || colors_render_mode == &DocumentColorsRenderMode::Inlay
 6890        {
 6891            return;
 6892        }
 6893
 6894        let line_end_overshoot = layout.line_end_overshoot();
 6895
 6896        for (range, color) in image_colors {
 6897            match colors_render_mode {
 6898                DocumentColorsRenderMode::Inlay | DocumentColorsRenderMode::None => return,
 6899                DocumentColorsRenderMode::Background => {
 6900                    self.paint_highlighted_range(
 6901                        range.clone(),
 6902                        true,
 6903                        *color,
 6904                        Pixels::ZERO,
 6905                        line_end_overshoot,
 6906                        layout,
 6907                        window,
 6908                    );
 6909                }
 6910                DocumentColorsRenderMode::Border => {
 6911                    self.paint_highlighted_range(
 6912                        range.clone(),
 6913                        false,
 6914                        *color,
 6915                        Pixels::ZERO,
 6916                        line_end_overshoot,
 6917                        layout,
 6918                        window,
 6919                    );
 6920                }
 6921            }
 6922        }
 6923    }
 6924
 6925    fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6926        for cursor in &mut layout.visible_cursors {
 6927            cursor.paint(layout.content_origin, window, cx);
 6928        }
 6929    }
 6930
 6931    fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6932        let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
 6933            return;
 6934        };
 6935        let any_scrollbar_dragged = self.editor.read(cx).scroll_manager.any_scrollbar_dragged();
 6936
 6937        for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
 6938            let hitbox = &scrollbar_layout.hitbox;
 6939            if scrollbars_layout.visible {
 6940                let scrollbar_edges = match axis {
 6941                    ScrollbarAxis::Horizontal => Edges {
 6942                        top: Pixels::ZERO,
 6943                        right: Pixels::ZERO,
 6944                        bottom: Pixels::ZERO,
 6945                        left: Pixels::ZERO,
 6946                    },
 6947                    ScrollbarAxis::Vertical => Edges {
 6948                        top: Pixels::ZERO,
 6949                        right: Pixels::ZERO,
 6950                        bottom: Pixels::ZERO,
 6951                        left: ScrollbarLayout::BORDER_WIDTH,
 6952                    },
 6953                };
 6954
 6955                window.paint_layer(hitbox.bounds, |window| {
 6956                    window.paint_quad(quad(
 6957                        hitbox.bounds,
 6958                        Corners::default(),
 6959                        cx.theme().colors().scrollbar_track_background,
 6960                        scrollbar_edges,
 6961                        cx.theme().colors().scrollbar_track_border,
 6962                        BorderStyle::Solid,
 6963                    ));
 6964
 6965                    if axis == ScrollbarAxis::Vertical {
 6966                        let fast_markers =
 6967                            self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
 6968                        // Refresh slow scrollbar markers in the background. Below, we
 6969                        // paint whatever markers have already been computed.
 6970                        self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, window, cx);
 6971
 6972                        let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
 6973                        for marker in markers.iter().chain(&fast_markers) {
 6974                            let mut marker = marker.clone();
 6975                            marker.bounds.origin += hitbox.origin;
 6976                            window.paint_quad(marker);
 6977                        }
 6978                    }
 6979
 6980                    if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
 6981                        let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
 6982                            ScrollbarThumbState::Dragging => {
 6983                                cx.theme().colors().scrollbar_thumb_active_background
 6984                            }
 6985                            ScrollbarThumbState::Hovered => {
 6986                                cx.theme().colors().scrollbar_thumb_hover_background
 6987                            }
 6988                            ScrollbarThumbState::Idle => {
 6989                                cx.theme().colors().scrollbar_thumb_background
 6990                            }
 6991                        };
 6992                        window.paint_quad(quad(
 6993                            thumb_bounds,
 6994                            Corners::default(),
 6995                            scrollbar_thumb_color,
 6996                            scrollbar_edges,
 6997                            cx.theme().colors().scrollbar_thumb_border,
 6998                            BorderStyle::Solid,
 6999                        ));
 7000
 7001                        if any_scrollbar_dragged {
 7002                            window.set_window_cursor_style(CursorStyle::Arrow);
 7003                        } else {
 7004                            window.set_cursor_style(CursorStyle::Arrow, hitbox);
 7005                        }
 7006                    }
 7007                })
 7008            }
 7009        }
 7010
 7011        window.on_mouse_event({
 7012            let editor = self.editor.clone();
 7013            let scrollbars_layout = scrollbars_layout.clone();
 7014
 7015            let mut mouse_position = window.mouse_position();
 7016            move |event: &MouseMoveEvent, phase, window, cx| {
 7017                if phase == DispatchPhase::Capture {
 7018                    return;
 7019                }
 7020
 7021                editor.update(cx, |editor, cx| {
 7022                    if let Some((scrollbar_layout, axis)) = event
 7023                        .pressed_button
 7024                        .filter(|button| *button == MouseButton::Left)
 7025                        .and(editor.scroll_manager.dragging_scrollbar_axis())
 7026                        .and_then(|axis| {
 7027                            scrollbars_layout
 7028                                .iter_scrollbars()
 7029                                .find(|(_, a)| *a == axis)
 7030                        })
 7031                    {
 7032                        let ScrollbarLayout {
 7033                            hitbox,
 7034                            text_unit_size,
 7035                            ..
 7036                        } = scrollbar_layout;
 7037
 7038                        let old_position = mouse_position.along(axis);
 7039                        let new_position = event.position.along(axis);
 7040                        if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
 7041                            .contains(&old_position)
 7042                        {
 7043                            let position = editor.scroll_position(cx).apply_along(axis, |p| {
 7044                                (p + ScrollOffset::from(
 7045                                    (new_position - old_position) / *text_unit_size,
 7046                                ))
 7047                                .max(0.)
 7048                            });
 7049                            editor.set_scroll_position(position, window, cx);
 7050                        }
 7051
 7052                        editor.scroll_manager.show_scrollbars(window, cx);
 7053                        cx.stop_propagation();
 7054                    } else if let Some((layout, axis)) = scrollbars_layout
 7055                        .get_hovered_axis(window)
 7056                        .filter(|_| !event.dragging())
 7057                    {
 7058                        if layout.thumb_hovered(&event.position) {
 7059                            editor
 7060                                .scroll_manager
 7061                                .set_hovered_scroll_thumb_axis(axis, cx);
 7062                        } else {
 7063                            editor.scroll_manager.reset_scrollbar_state(cx);
 7064                        }
 7065
 7066                        editor.scroll_manager.show_scrollbars(window, cx);
 7067                    } else {
 7068                        editor.scroll_manager.reset_scrollbar_state(cx);
 7069                    }
 7070
 7071                    mouse_position = event.position;
 7072                })
 7073            }
 7074        });
 7075
 7076        if any_scrollbar_dragged {
 7077            window.on_mouse_event({
 7078                let editor = self.editor.clone();
 7079                move |_: &MouseUpEvent, phase, window, cx| {
 7080                    if phase == DispatchPhase::Capture {
 7081                        return;
 7082                    }
 7083
 7084                    editor.update(cx, |editor, cx| {
 7085                        if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
 7086                            editor
 7087                                .scroll_manager
 7088                                .set_hovered_scroll_thumb_axis(axis, cx);
 7089                        } else {
 7090                            editor.scroll_manager.reset_scrollbar_state(cx);
 7091                        }
 7092                        cx.stop_propagation();
 7093                    });
 7094                }
 7095            });
 7096        } else {
 7097            window.on_mouse_event({
 7098                let editor = self.editor.clone();
 7099
 7100                move |event: &MouseDownEvent, phase, window, cx| {
 7101                    if phase == DispatchPhase::Capture {
 7102                        return;
 7103                    }
 7104                    let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
 7105                    else {
 7106                        return;
 7107                    };
 7108
 7109                    let ScrollbarLayout {
 7110                        hitbox,
 7111                        visible_range,
 7112                        text_unit_size,
 7113                        thumb_bounds,
 7114                        ..
 7115                    } = scrollbar_layout;
 7116
 7117                    let Some(thumb_bounds) = thumb_bounds else {
 7118                        return;
 7119                    };
 7120
 7121                    editor.update(cx, |editor, cx| {
 7122                        editor
 7123                            .scroll_manager
 7124                            .set_dragged_scroll_thumb_axis(axis, cx);
 7125
 7126                        let event_position = event.position.along(axis);
 7127
 7128                        if event_position < thumb_bounds.origin.along(axis)
 7129                            || thumb_bounds.bottom_right().along(axis) < event_position
 7130                        {
 7131                            let center_position = ((event_position - hitbox.origin.along(axis))
 7132                                / *text_unit_size)
 7133                                .round() as u32;
 7134                            let start_position = center_position.saturating_sub(
 7135                                (visible_range.end - visible_range.start) as u32 / 2,
 7136                            );
 7137
 7138                            let position = editor
 7139                                .scroll_position(cx)
 7140                                .apply_along(axis, |_| start_position as ScrollOffset);
 7141
 7142                            editor.set_scroll_position(position, window, cx);
 7143                        } else {
 7144                            editor.scroll_manager.show_scrollbars(window, cx);
 7145                        }
 7146
 7147                        cx.stop_propagation();
 7148                    });
 7149                }
 7150            });
 7151        }
 7152    }
 7153
 7154    fn collect_fast_scrollbar_markers(
 7155        &self,
 7156        layout: &EditorLayout,
 7157        scrollbar_layout: &ScrollbarLayout,
 7158        cx: &mut App,
 7159    ) -> Vec<PaintQuad> {
 7160        const LIMIT: usize = 100;
 7161        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
 7162            return vec![];
 7163        }
 7164        let cursor_ranges = layout
 7165            .cursors
 7166            .iter()
 7167            .map(|(point, color)| ColoredRange {
 7168                start: point.row(),
 7169                end: point.row(),
 7170                color: *color,
 7171            })
 7172            .collect_vec();
 7173        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
 7174    }
 7175
 7176    fn refresh_slow_scrollbar_markers(
 7177        &self,
 7178        layout: &EditorLayout,
 7179        scrollbar_layout: &ScrollbarLayout,
 7180        window: &mut Window,
 7181        cx: &mut App,
 7182    ) {
 7183        self.editor.update(cx, |editor, cx| {
 7184            if editor.buffer_kind(cx) != ItemBufferKind::Singleton
 7185                || !editor
 7186                    .scrollbar_marker_state
 7187                    .should_refresh(scrollbar_layout.hitbox.size)
 7188            {
 7189                return;
 7190            }
 7191
 7192            let scrollbar_layout = scrollbar_layout.clone();
 7193            let background_highlights = editor.background_highlights.clone();
 7194            let snapshot = layout.position_map.snapshot.clone();
 7195            let theme = cx.theme().clone();
 7196            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
 7197
 7198            editor.scrollbar_marker_state.dirty = false;
 7199            editor.scrollbar_marker_state.pending_refresh =
 7200                Some(cx.spawn_in(window, async move |editor, cx| {
 7201                    let scrollbar_size = scrollbar_layout.hitbox.size;
 7202                    let scrollbar_markers = cx
 7203                        .background_spawn(async move {
 7204                            let max_point = snapshot.display_snapshot.buffer_snapshot().max_point();
 7205                            let mut marker_quads = Vec::new();
 7206                            if scrollbar_settings.git_diff {
 7207                                let marker_row_ranges =
 7208                                    snapshot.buffer_snapshot().diff_hunks().map(|hunk| {
 7209                                        let start_display_row =
 7210                                            MultiBufferPoint::new(hunk.row_range.start.0, 0)
 7211                                                .to_display_point(&snapshot.display_snapshot)
 7212                                                .row();
 7213                                        let mut end_display_row =
 7214                                            MultiBufferPoint::new(hunk.row_range.end.0, 0)
 7215                                                .to_display_point(&snapshot.display_snapshot)
 7216                                                .row();
 7217                                        if end_display_row != start_display_row {
 7218                                            end_display_row.0 -= 1;
 7219                                        }
 7220                                        let color = match &hunk.status().kind {
 7221                                            DiffHunkStatusKind::Added => {
 7222                                                theme.colors().version_control_added
 7223                                            }
 7224                                            DiffHunkStatusKind::Modified => {
 7225                                                theme.colors().version_control_modified
 7226                                            }
 7227                                            DiffHunkStatusKind::Deleted => {
 7228                                                theme.colors().version_control_deleted
 7229                                            }
 7230                                        };
 7231                                        ColoredRange {
 7232                                            start: start_display_row,
 7233                                            end: end_display_row,
 7234                                            color,
 7235                                        }
 7236                                    });
 7237
 7238                                marker_quads.extend(
 7239                                    scrollbar_layout
 7240                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
 7241                                );
 7242                            }
 7243
 7244                            for (background_highlight_id, (_, background_ranges)) in
 7245                                background_highlights.iter()
 7246                            {
 7247                                let is_search_highlights = *background_highlight_id
 7248                                    == HighlightKey::BufferSearchHighlights;
 7249                                let is_text_highlights =
 7250                                    *background_highlight_id == HighlightKey::SelectedTextHighlight;
 7251                                let is_symbol_occurrences = *background_highlight_id
 7252                                    == HighlightKey::DocumentHighlightRead
 7253                                    || *background_highlight_id
 7254                                        == HighlightKey::DocumentHighlightWrite;
 7255                                if (is_search_highlights && scrollbar_settings.search_results)
 7256                                    || (is_text_highlights && scrollbar_settings.selected_text)
 7257                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
 7258                                {
 7259                                    let mut color = theme.status().info;
 7260                                    if is_symbol_occurrences {
 7261                                        color.fade_out(0.5);
 7262                                    }
 7263                                    let marker_row_ranges = background_ranges.iter().map(|range| {
 7264                                        let display_start = range
 7265                                            .start
 7266                                            .to_display_point(&snapshot.display_snapshot);
 7267                                        let display_end =
 7268                                            range.end.to_display_point(&snapshot.display_snapshot);
 7269                                        ColoredRange {
 7270                                            start: display_start.row(),
 7271                                            end: display_end.row(),
 7272                                            color,
 7273                                        }
 7274                                    });
 7275                                    marker_quads.extend(
 7276                                        scrollbar_layout
 7277                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
 7278                                    );
 7279                                }
 7280                            }
 7281
 7282                            if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
 7283                                let diagnostics = snapshot
 7284                                    .buffer_snapshot()
 7285                                    .diagnostics_in_range::<Point>(Point::zero()..max_point)
 7286                                    // Don't show diagnostics the user doesn't care about
 7287                                    .filter(|diagnostic| {
 7288                                        match (
 7289                                            scrollbar_settings.diagnostics,
 7290                                            diagnostic.diagnostic.severity,
 7291                                        ) {
 7292                                            (ScrollbarDiagnostics::All, _) => true,
 7293                                            (
 7294                                                ScrollbarDiagnostics::Error,
 7295                                                lsp::DiagnosticSeverity::ERROR,
 7296                                            ) => true,
 7297                                            (
 7298                                                ScrollbarDiagnostics::Warning,
 7299                                                lsp::DiagnosticSeverity::ERROR
 7300                                                | lsp::DiagnosticSeverity::WARNING,
 7301                                            ) => true,
 7302                                            (
 7303                                                ScrollbarDiagnostics::Information,
 7304                                                lsp::DiagnosticSeverity::ERROR
 7305                                                | lsp::DiagnosticSeverity::WARNING
 7306                                                | lsp::DiagnosticSeverity::INFORMATION,
 7307                                            ) => true,
 7308                                            (_, _) => false,
 7309                                        }
 7310                                    })
 7311                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
 7312                                    .sorted_by_key(|diagnostic| {
 7313                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
 7314                                    });
 7315
 7316                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
 7317                                    let start_display = diagnostic
 7318                                        .range
 7319                                        .start
 7320                                        .to_display_point(&snapshot.display_snapshot);
 7321                                    let end_display = diagnostic
 7322                                        .range
 7323                                        .end
 7324                                        .to_display_point(&snapshot.display_snapshot);
 7325                                    let color = match diagnostic.diagnostic.severity {
 7326                                        lsp::DiagnosticSeverity::ERROR => theme.status().error,
 7327                                        lsp::DiagnosticSeverity::WARNING => theme.status().warning,
 7328                                        lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
 7329                                        _ => theme.status().hint,
 7330                                    };
 7331                                    ColoredRange {
 7332                                        start: start_display.row(),
 7333                                        end: end_display.row(),
 7334                                        color,
 7335                                    }
 7336                                });
 7337                                marker_quads.extend(
 7338                                    scrollbar_layout
 7339                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
 7340                                );
 7341                            }
 7342
 7343                            Arc::from(marker_quads)
 7344                        })
 7345                        .await;
 7346
 7347                    editor.update(cx, |editor, cx| {
 7348                        editor.scrollbar_marker_state.markers = scrollbar_markers;
 7349                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
 7350                        editor.scrollbar_marker_state.pending_refresh = None;
 7351                        cx.notify();
 7352                    })?;
 7353
 7354                    Ok(())
 7355                }));
 7356        });
 7357    }
 7358
 7359    fn paint_highlighted_range(
 7360        &self,
 7361        range: Range<DisplayPoint>,
 7362        fill: bool,
 7363        color: Hsla,
 7364        corner_radius: Pixels,
 7365        line_end_overshoot: Pixels,
 7366        layout: &EditorLayout,
 7367        window: &mut Window,
 7368    ) {
 7369        let start_row = layout.visible_display_row_range.start;
 7370        let end_row = layout.visible_display_row_range.end;
 7371        if range.start != range.end {
 7372            let row_range = if range.end.column() == 0 {
 7373                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
 7374            } else {
 7375                cmp::max(range.start.row(), start_row)
 7376                    ..cmp::min(range.end.row().next_row(), end_row)
 7377            };
 7378
 7379            let highlighted_range = HighlightedRange {
 7380                color,
 7381                line_height: layout.position_map.line_height,
 7382                corner_radius,
 7383                start_y: layout.content_origin.y
 7384                    + Pixels::from(
 7385                        (row_range.start.as_f64() - layout.position_map.scroll_position.y)
 7386                            * ScrollOffset::from(layout.position_map.line_height),
 7387                    ),
 7388                lines: row_range
 7389                    .iter_rows()
 7390                    .map(|row| {
 7391                        let line_layout =
 7392                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
 7393                        let alignment_offset =
 7394                            line_layout.alignment_offset(layout.text_align, layout.content_width);
 7395                        HighlightedRangeLine {
 7396                            start_x: if row == range.start.row() {
 7397                                layout.content_origin.x
 7398                                    + Pixels::from(
 7399                                        ScrollPixelOffset::from(
 7400                                            line_layout.x_for_index(range.start.column() as usize)
 7401                                                + alignment_offset,
 7402                                        ) - layout.position_map.scroll_pixel_position.x,
 7403                                    )
 7404                            } else {
 7405                                layout.content_origin.x + alignment_offset
 7406                                    - Pixels::from(layout.position_map.scroll_pixel_position.x)
 7407                            },
 7408                            end_x: if row == range.end.row() {
 7409                                layout.content_origin.x
 7410                                    + Pixels::from(
 7411                                        ScrollPixelOffset::from(
 7412                                            line_layout.x_for_index(range.end.column() as usize)
 7413                                                + alignment_offset,
 7414                                        ) - layout.position_map.scroll_pixel_position.x,
 7415                                    )
 7416                            } else {
 7417                                Pixels::from(
 7418                                    ScrollPixelOffset::from(
 7419                                        layout.content_origin.x
 7420                                            + line_layout.width
 7421                                            + alignment_offset
 7422                                            + line_end_overshoot,
 7423                                    ) - layout.position_map.scroll_pixel_position.x,
 7424                                )
 7425                            },
 7426                        }
 7427                    })
 7428                    .collect(),
 7429            };
 7430
 7431            highlighted_range.paint(fill, layout.position_map.text_hitbox.bounds, window);
 7432        }
 7433    }
 7434
 7435    fn paint_inline_diagnostics(
 7436        &mut self,
 7437        layout: &mut EditorLayout,
 7438        window: &mut Window,
 7439        cx: &mut App,
 7440    ) {
 7441        for mut inline_diagnostic in layout.inline_diagnostics.drain() {
 7442            inline_diagnostic.1.paint(window, cx);
 7443        }
 7444    }
 7445
 7446    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 7447        if let Some(mut blame_layout) = layout.inline_blame_layout.take() {
 7448            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 7449                blame_layout.element.paint(window, cx);
 7450            })
 7451        }
 7452    }
 7453
 7454    fn paint_inline_code_actions(
 7455        &mut self,
 7456        layout: &mut EditorLayout,
 7457        window: &mut Window,
 7458        cx: &mut App,
 7459    ) {
 7460        if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
 7461            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 7462                inline_code_actions.paint(window, cx);
 7463            })
 7464        }
 7465    }
 7466
 7467    fn paint_diff_hunk_controls(
 7468        &mut self,
 7469        layout: &mut EditorLayout,
 7470        window: &mut Window,
 7471        cx: &mut App,
 7472    ) {
 7473        for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
 7474            diff_hunk_control.paint(window, cx);
 7475        }
 7476    }
 7477
 7478    fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 7479        if let Some(mut layout) = layout.minimap.take() {
 7480            let minimap_hitbox = layout.thumb_layout.hitbox.clone();
 7481            let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
 7482
 7483            window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
 7484                window.with_element_namespace("minimap", |window| {
 7485                    layout.minimap.paint(window, cx);
 7486                    if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
 7487                        let minimap_thumb_color = match layout.thumb_layout.thumb_state {
 7488                            ScrollbarThumbState::Idle => {
 7489                                cx.theme().colors().minimap_thumb_background
 7490                            }
 7491                            ScrollbarThumbState::Hovered => {
 7492                                cx.theme().colors().minimap_thumb_hover_background
 7493                            }
 7494                            ScrollbarThumbState::Dragging => {
 7495                                cx.theme().colors().minimap_thumb_active_background
 7496                            }
 7497                        };
 7498                        let minimap_thumb_border = match layout.thumb_border_style {
 7499                            MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
 7500                            MinimapThumbBorder::LeftOnly => Edges {
 7501                                left: ScrollbarLayout::BORDER_WIDTH,
 7502                                ..Default::default()
 7503                            },
 7504                            MinimapThumbBorder::LeftOpen => Edges {
 7505                                right: ScrollbarLayout::BORDER_WIDTH,
 7506                                top: ScrollbarLayout::BORDER_WIDTH,
 7507                                bottom: ScrollbarLayout::BORDER_WIDTH,
 7508                                ..Default::default()
 7509                            },
 7510                            MinimapThumbBorder::RightOpen => Edges {
 7511                                left: ScrollbarLayout::BORDER_WIDTH,
 7512                                top: ScrollbarLayout::BORDER_WIDTH,
 7513                                bottom: ScrollbarLayout::BORDER_WIDTH,
 7514                                ..Default::default()
 7515                            },
 7516                            MinimapThumbBorder::None => Default::default(),
 7517                        };
 7518
 7519                        window.paint_layer(minimap_hitbox.bounds, |window| {
 7520                            window.paint_quad(quad(
 7521                                thumb_bounds,
 7522                                Corners::default(),
 7523                                minimap_thumb_color,
 7524                                minimap_thumb_border,
 7525                                cx.theme().colors().minimap_thumb_border,
 7526                                BorderStyle::Solid,
 7527                            ));
 7528                        });
 7529                    }
 7530                });
 7531            });
 7532
 7533            if dragging_minimap {
 7534                window.set_window_cursor_style(CursorStyle::Arrow);
 7535            } else {
 7536                window.set_cursor_style(CursorStyle::Arrow, &minimap_hitbox);
 7537            }
 7538
 7539            let minimap_axis = ScrollbarAxis::Vertical;
 7540            let pixels_per_line = Pixels::from(
 7541                ScrollPixelOffset::from(minimap_hitbox.size.height) / layout.max_scroll_top,
 7542            )
 7543            .min(layout.minimap_line_height);
 7544
 7545            let mut mouse_position = window.mouse_position();
 7546
 7547            window.on_mouse_event({
 7548                let editor = self.editor.clone();
 7549
 7550                let minimap_hitbox = minimap_hitbox.clone();
 7551
 7552                move |event: &MouseMoveEvent, phase, window, cx| {
 7553                    if phase == DispatchPhase::Capture {
 7554                        return;
 7555                    }
 7556
 7557                    editor.update(cx, |editor, cx| {
 7558                        if event.pressed_button == Some(MouseButton::Left)
 7559                            && editor.scroll_manager.is_dragging_minimap()
 7560                        {
 7561                            let old_position = mouse_position.along(minimap_axis);
 7562                            let new_position = event.position.along(minimap_axis);
 7563                            if (minimap_hitbox.origin.along(minimap_axis)
 7564                                ..minimap_hitbox.bottom_right().along(minimap_axis))
 7565                                .contains(&old_position)
 7566                            {
 7567                                let position =
 7568                                    editor.scroll_position(cx).apply_along(minimap_axis, |p| {
 7569                                        (p + ScrollPixelOffset::from(
 7570                                            (new_position - old_position) / pixels_per_line,
 7571                                        ))
 7572                                        .max(0.)
 7573                                    });
 7574
 7575                                editor.set_scroll_position(position, window, cx);
 7576                            }
 7577                            cx.stop_propagation();
 7578                        } else if minimap_hitbox.is_hovered(window) {
 7579                            editor.scroll_manager.set_is_hovering_minimap_thumb(
 7580                                !event.dragging()
 7581                                    && layout
 7582                                        .thumb_layout
 7583                                        .thumb_bounds
 7584                                        .is_some_and(|bounds| bounds.contains(&event.position)),
 7585                                cx,
 7586                            );
 7587
 7588                            // Stop hover events from propagating to the
 7589                            // underlying editor if the minimap hitbox is hovered
 7590                            if !event.dragging() {
 7591                                cx.stop_propagation();
 7592                            }
 7593                        } else {
 7594                            editor.scroll_manager.hide_minimap_thumb(cx);
 7595                        }
 7596                        mouse_position = event.position;
 7597                    });
 7598                }
 7599            });
 7600
 7601            if dragging_minimap {
 7602                window.on_mouse_event({
 7603                    let editor = self.editor.clone();
 7604                    move |event: &MouseUpEvent, phase, window, cx| {
 7605                        if phase == DispatchPhase::Capture {
 7606                            return;
 7607                        }
 7608
 7609                        editor.update(cx, |editor, cx| {
 7610                            if minimap_hitbox.is_hovered(window) {
 7611                                editor.scroll_manager.set_is_hovering_minimap_thumb(
 7612                                    layout
 7613                                        .thumb_layout
 7614                                        .thumb_bounds
 7615                                        .is_some_and(|bounds| bounds.contains(&event.position)),
 7616                                    cx,
 7617                                );
 7618                            } else {
 7619                                editor.scroll_manager.hide_minimap_thumb(cx);
 7620                            }
 7621                            cx.stop_propagation();
 7622                        });
 7623                    }
 7624                });
 7625            } else {
 7626                window.on_mouse_event({
 7627                    let editor = self.editor.clone();
 7628
 7629                    move |event: &MouseDownEvent, phase, window, cx| {
 7630                        if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
 7631                            return;
 7632                        }
 7633
 7634                        let event_position = event.position;
 7635
 7636                        let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
 7637                            return;
 7638                        };
 7639
 7640                        editor.update(cx, |editor, cx| {
 7641                            if !thumb_bounds.contains(&event_position) {
 7642                                let click_position =
 7643                                    event_position.relative_to(&minimap_hitbox.origin).y;
 7644
 7645                                let top_position = (click_position
 7646                                    - thumb_bounds.size.along(minimap_axis) / 2.0)
 7647                                    .max(Pixels::ZERO);
 7648
 7649                                let scroll_offset = (layout.minimap_scroll_top
 7650                                    + ScrollPixelOffset::from(
 7651                                        top_position / layout.minimap_line_height,
 7652                                    ))
 7653                                .min(layout.max_scroll_top);
 7654
 7655                                let scroll_position = editor
 7656                                    .scroll_position(cx)
 7657                                    .apply_along(minimap_axis, |_| scroll_offset);
 7658                                editor.set_scroll_position(scroll_position, window, cx);
 7659                            }
 7660
 7661                            editor.scroll_manager.set_is_dragging_minimap(cx);
 7662                            cx.stop_propagation();
 7663                        });
 7664                    }
 7665                });
 7666            }
 7667        }
 7668    }
 7669
 7670    fn paint_spacer_blocks(
 7671        &mut self,
 7672        layout: &mut EditorLayout,
 7673        window: &mut Window,
 7674        cx: &mut App,
 7675    ) {
 7676        for mut block in layout.spacer_blocks.drain(..) {
 7677            let mut bounds = layout.hitbox.bounds;
 7678            bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
 7679            window.with_content_mask(Some(ContentMask { bounds }), |window| {
 7680                block.element.paint(window, cx);
 7681            })
 7682        }
 7683    }
 7684
 7685    fn paint_non_spacer_blocks(
 7686        &mut self,
 7687        layout: &mut EditorLayout,
 7688        window: &mut Window,
 7689        cx: &mut App,
 7690    ) {
 7691        for mut block in layout.blocks.drain(..) {
 7692            if block.overlaps_gutter {
 7693                block.element.paint(window, cx);
 7694            } else {
 7695                let mut bounds = layout.hitbox.bounds;
 7696                bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
 7697                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 7698                    block.element.paint(window, cx);
 7699                })
 7700            }
 7701        }
 7702    }
 7703
 7704    fn paint_edit_prediction_popover(
 7705        &mut self,
 7706        layout: &mut EditorLayout,
 7707        window: &mut Window,
 7708        cx: &mut App,
 7709    ) {
 7710        if let Some(edit_prediction_popover) = layout.edit_prediction_popover.as_mut() {
 7711            edit_prediction_popover.paint(window, cx);
 7712        }
 7713    }
 7714
 7715    fn paint_mouse_context_menu(
 7716        &mut self,
 7717        layout: &mut EditorLayout,
 7718        window: &mut Window,
 7719        cx: &mut App,
 7720    ) {
 7721        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
 7722            mouse_context_menu.paint(window, cx);
 7723        }
 7724    }
 7725
 7726    fn paint_scroll_wheel_listener(
 7727        &mut self,
 7728        layout: &EditorLayout,
 7729        window: &mut Window,
 7730        cx: &mut App,
 7731    ) {
 7732        window.on_mouse_event({
 7733            let position_map = layout.position_map.clone();
 7734            let editor = self.editor.clone();
 7735            let hitbox = layout.hitbox.clone();
 7736            let mut delta = ScrollDelta::default();
 7737
 7738            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
 7739            // accidentally turn off their scrolling.
 7740            let base_scroll_sensitivity =
 7741                EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
 7742
 7743            // Use a minimum fast_scroll_sensitivity for same reason above
 7744            let fast_scroll_sensitivity = EditorSettings::get_global(cx)
 7745                .fast_scroll_sensitivity
 7746                .max(0.01);
 7747
 7748            move |event: &ScrollWheelEvent, phase, window, cx| {
 7749                if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
 7750                    delta = delta.coalesce(event.delta);
 7751
 7752                    if event.modifiers.secondary()
 7753                        && editor.read(cx).enable_mouse_wheel_zoom
 7754                        && EditorSettings::get_global(cx).mouse_wheel_zoom
 7755                    {
 7756                        let delta_y = match event.delta {
 7757                            ScrollDelta::Pixels(pixels) => pixels.y.into(),
 7758                            ScrollDelta::Lines(lines) => lines.y,
 7759                        };
 7760
 7761                        if delta_y > 0.0 {
 7762                            theme_settings::increase_buffer_font_size(cx);
 7763                        } else if delta_y < 0.0 {
 7764                            theme_settings::decrease_buffer_font_size(cx);
 7765                        }
 7766
 7767                        cx.stop_propagation();
 7768                    } else {
 7769                        let scroll_sensitivity = {
 7770                            if event.modifiers.alt {
 7771                                fast_scroll_sensitivity
 7772                            } else {
 7773                                base_scroll_sensitivity
 7774                            }
 7775                        };
 7776
 7777                        editor.update(cx, |editor, cx| {
 7778                            let line_height = position_map.line_height;
 7779                            let glyph_width = position_map.em_layout_width;
 7780                            let (delta, axis) = match delta {
 7781                                gpui::ScrollDelta::Pixels(mut pixels) => {
 7782                                    //Trackpad
 7783                                    let axis =
 7784                                        position_map.snapshot.ongoing_scroll.filter(&mut pixels);
 7785                                    (pixels, axis)
 7786                                }
 7787
 7788                                gpui::ScrollDelta::Lines(lines) => {
 7789                                    //Not trackpad
 7790                                    let pixels =
 7791                                        point(lines.x * glyph_width, lines.y * line_height);
 7792                                    (pixels, None)
 7793                                }
 7794                            };
 7795
 7796                            let current_scroll_position = position_map.snapshot.scroll_position();
 7797                            let x = (current_scroll_position.x
 7798                                * ScrollPixelOffset::from(glyph_width)
 7799                                - ScrollPixelOffset::from(delta.x * scroll_sensitivity))
 7800                                / ScrollPixelOffset::from(glyph_width);
 7801                            let y = (current_scroll_position.y
 7802                                * ScrollPixelOffset::from(line_height)
 7803                                - ScrollPixelOffset::from(delta.y * scroll_sensitivity))
 7804                                / ScrollPixelOffset::from(line_height);
 7805                            let mut scroll_position =
 7806                                point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
 7807                            let forbid_vertical_scroll =
 7808                                editor.scroll_manager.forbid_vertical_scroll();
 7809                            if forbid_vertical_scroll {
 7810                                scroll_position.y = current_scroll_position.y;
 7811                            }
 7812
 7813                            if scroll_position != current_scroll_position {
 7814                                editor.scroll(scroll_position, axis, window, cx);
 7815                                cx.stop_propagation();
 7816                            } else if y < 0. {
 7817                                // Due to clamping, we may fail to detect cases of overscroll to the top;
 7818                                // We want the scroll manager to get an update in such cases and detect the change of direction
 7819                                // on the next frame.
 7820                                cx.notify();
 7821                            }
 7822                        });
 7823                    }
 7824                }
 7825            }
 7826        });
 7827    }
 7828
 7829    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
 7830        if layout.mode.is_minimap() {
 7831            return;
 7832        }
 7833
 7834        self.paint_scroll_wheel_listener(layout, window, cx);
 7835
 7836        window.on_mouse_event({
 7837            let position_map = layout.position_map.clone();
 7838            let editor = self.editor.clone();
 7839            let line_numbers = layout.line_numbers.clone();
 7840
 7841            move |event: &MouseDownEvent, phase, window, cx| {
 7842                if phase == DispatchPhase::Bubble {
 7843                    match event.button {
 7844                        MouseButton::Left => editor.update(cx, |editor, cx| {
 7845                            let pending_mouse_down = editor
 7846                                .pending_mouse_down
 7847                                .get_or_insert_with(Default::default)
 7848                                .clone();
 7849
 7850                            *pending_mouse_down.borrow_mut() = Some(event.clone());
 7851
 7852                            Self::mouse_left_down(
 7853                                editor,
 7854                                event,
 7855                                &position_map,
 7856                                line_numbers.as_ref(),
 7857                                window,
 7858                                cx,
 7859                            );
 7860                        }),
 7861                        MouseButton::Right => editor.update(cx, |editor, cx| {
 7862                            Self::mouse_right_down(editor, event, &position_map, window, cx);
 7863                        }),
 7864                        MouseButton::Middle => editor.update(cx, |editor, cx| {
 7865                            Self::mouse_middle_down(editor, event, &position_map, window, cx);
 7866                        }),
 7867                        _ => {}
 7868                    };
 7869                }
 7870            }
 7871        });
 7872
 7873        window.on_mouse_event({
 7874            let editor = self.editor.clone();
 7875            let position_map = layout.position_map.clone();
 7876
 7877            move |event: &MouseUpEvent, phase, window, cx| {
 7878                if phase == DispatchPhase::Bubble {
 7879                    editor.update(cx, |editor, cx| {
 7880                        Self::mouse_up(editor, event, &position_map, window, cx)
 7881                    });
 7882                }
 7883            }
 7884        });
 7885
 7886        window.on_mouse_event({
 7887            let editor = self.editor.clone();
 7888            let position_map = layout.position_map.clone();
 7889            let mut captured_mouse_down = None;
 7890
 7891            move |event: &MouseUpEvent, phase, window, cx| match phase {
 7892                // Clear the pending mouse down during the capture phase,
 7893                // so that it happens even if another event handler stops
 7894                // propagation.
 7895                DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
 7896                    let pending_mouse_down = editor
 7897                        .pending_mouse_down
 7898                        .get_or_insert_with(Default::default)
 7899                        .clone();
 7900
 7901                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
 7902                    if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
 7903                        captured_mouse_down = pending_mouse_down.take();
 7904                        window.refresh();
 7905                    }
 7906                }),
 7907                // Fire click handlers during the bubble phase.
 7908                DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
 7909                    if let Some(mouse_down) = captured_mouse_down.take() {
 7910                        let event = ClickEvent::Mouse(MouseClickEvent {
 7911                            down: mouse_down,
 7912                            up: event.clone(),
 7913                        });
 7914                        Self::click(editor, &event, &position_map, window, cx);
 7915                    }
 7916                }),
 7917            }
 7918        });
 7919
 7920        window.on_mouse_event({
 7921            let position_map = layout.position_map.clone();
 7922            let editor = self.editor.clone();
 7923
 7924            move |event: &MousePressureEvent, phase, window, cx| {
 7925                if phase == DispatchPhase::Bubble {
 7926                    editor.update(cx, |editor, cx| {
 7927                        Self::pressure_click(editor, &event, &position_map, window, cx);
 7928                    })
 7929                }
 7930            }
 7931        });
 7932
 7933        window.on_mouse_event({
 7934            let position_map = layout.position_map.clone();
 7935            let editor = self.editor.clone();
 7936            let split_side = self.split_side;
 7937
 7938            move |event: &MouseMoveEvent, phase, window, cx| {
 7939                if phase == DispatchPhase::Bubble {
 7940                    editor.update(cx, |editor, cx| {
 7941                        if editor.hover_state.focused(window, cx) {
 7942                            return;
 7943                        }
 7944                        if event.pressed_button == Some(MouseButton::Left)
 7945                            || event.pressed_button == Some(MouseButton::Middle)
 7946                        {
 7947                            Self::mouse_dragged(editor, event, &position_map, window, cx)
 7948                        }
 7949
 7950                        Self::mouse_moved(editor, event, &position_map, split_side, window, cx)
 7951                    });
 7952                }
 7953            }
 7954        });
 7955    }
 7956
 7957    fn shape_line_number(
 7958        &self,
 7959        text: SharedString,
 7960        color: Hsla,
 7961        window: &mut Window,
 7962    ) -> ShapedLine {
 7963        let run = TextRun {
 7964            len: text.len(),
 7965            font: self.style.text.font(),
 7966            color,
 7967            ..Default::default()
 7968        };
 7969        window.text_system().shape_line(
 7970            text,
 7971            self.style.text.font_size.to_pixels(window.rem_size()),
 7972            &[run],
 7973            None,
 7974        )
 7975    }
 7976
 7977    fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
 7978        let unstaged = status.has_secondary_hunk();
 7979        let unstaged_hollow = matches!(
 7980            ProjectSettings::get_global(cx).git.hunk_style,
 7981            GitHunkStyleSetting::UnstagedHollow
 7982        );
 7983
 7984        unstaged == unstaged_hollow
 7985    }
 7986
 7987    #[cfg(debug_assertions)]
 7988    fn layout_debug_ranges(
 7989        selections: &mut Vec<(PlayerColor, Vec<SelectionLayout>)>,
 7990        anchor_range: Range<Anchor>,
 7991        display_snapshot: &DisplaySnapshot,
 7992        cx: &App,
 7993    ) {
 7994        let theme = cx.theme();
 7995        text::debug::GlobalDebugRanges::with_locked(|debug_ranges| {
 7996            if debug_ranges.ranges.is_empty() {
 7997                return;
 7998            }
 7999            let buffer_snapshot = &display_snapshot.buffer_snapshot();
 8000            for (excerpt_buffer_snapshot, buffer_range, _) in
 8001                buffer_snapshot.range_to_buffer_ranges(anchor_range.start..anchor_range.end)
 8002            {
 8003                let buffer_range = excerpt_buffer_snapshot.anchor_after(buffer_range.start)
 8004                    ..excerpt_buffer_snapshot.anchor_before(buffer_range.end);
 8005                selections.extend(debug_ranges.ranges.iter().flat_map(|debug_range| {
 8006                    debug_range.ranges.iter().filter_map(|range| {
 8007                        let player_color = theme
 8008                            .players()
 8009                            .color_for_participant(debug_range.occurrence_index as u32 + 1);
 8010                        if range.start.buffer_id != excerpt_buffer_snapshot.remote_id() {
 8011                            return None;
 8012                        }
 8013                        let clipped_start = range
 8014                            .start
 8015                            .max(&buffer_range.start, &excerpt_buffer_snapshot);
 8016                        let clipped_end =
 8017                            range.end.min(&buffer_range.end, &excerpt_buffer_snapshot);
 8018                        let range = buffer_snapshot
 8019                            .buffer_anchor_range_to_anchor_range(*clipped_start..*clipped_end)?;
 8020                        let start = range.start.to_display_point(display_snapshot);
 8021                        let end = range.end.to_display_point(display_snapshot);
 8022                        let selection_layout = SelectionLayout {
 8023                            head: start,
 8024                            range: start..end,
 8025                            cursor_shape: CursorShape::Bar,
 8026                            is_newest: false,
 8027                            is_local: false,
 8028                            active_rows: start.row()..end.row(),
 8029                            user_name: Some(SharedString::new(debug_range.value.clone())),
 8030                        };
 8031                        Some((player_color, vec![selection_layout]))
 8032                    })
 8033                }));
 8034            }
 8035        });
 8036    }
 8037}
 8038
 8039struct Gutter<'a> {
 8040    line_height: Pixels,
 8041    range: Range<DisplayRow>,
 8042    scroll_position: gpui::Point<ScrollOffset>,
 8043    dimensions: &'a GutterDimensions,
 8044    hitbox: &'a Hitbox,
 8045    snapshot: &'a EditorSnapshot,
 8046    row_infos: &'a [RowInfo],
 8047}
 8048
 8049impl Gutter<'_> {
 8050    fn layout_item_skipping_folds(
 8051        &self,
 8052        display_row: DisplayRow,
 8053        render_item: impl Fn(&mut Context<'_, Editor>, &mut Window) -> AnyElement,
 8054        window: &mut Window,
 8055        cx: &mut Context<'_, Editor>,
 8056    ) -> Option<AnyElement> {
 8057        let row = MultiBufferRow(
 8058            DisplayPoint::new(display_row, 0)
 8059                .to_point(self.snapshot)
 8060                .row,
 8061        );
 8062        if self.snapshot.is_line_folded(row) {
 8063            return None;
 8064        }
 8065
 8066        self.layout_item(display_row, render_item, window, cx)
 8067    }
 8068
 8069    fn layout_item(
 8070        &self,
 8071        display_row: DisplayRow,
 8072        render_item: impl Fn(&mut Context<'_, Editor>, &mut Window) -> AnyElement,
 8073        window: &mut Window,
 8074        cx: &mut Context<'_, Editor>,
 8075    ) -> Option<AnyElement> {
 8076        if !self.range.contains(&display_row) {
 8077            return None;
 8078        }
 8079
 8080        if self
 8081            .row_infos
 8082            .get((display_row.0.saturating_sub(self.range.start.0)) as usize)
 8083            .is_some_and(|row_info| {
 8084                row_info.expand_info.is_some()
 8085                    || row_info
 8086                        .diff_status
 8087                        .is_some_and(|status| status.is_deleted())
 8088            })
 8089        {
 8090            return None;
 8091        }
 8092
 8093        let button = self.prepaint_button(render_item(cx, window), display_row, window, cx);
 8094        Some(button)
 8095    }
 8096
 8097    fn prepaint_button(
 8098        &self,
 8099        mut button: AnyElement,
 8100        row: DisplayRow,
 8101        window: &mut Window,
 8102        cx: &mut App,
 8103    ) -> AnyElement {
 8104        let available_space = size(
 8105            AvailableSpace::MinContent,
 8106            AvailableSpace::Definite(self.line_height),
 8107        );
 8108        let indicator_size = button.layout_as_root(available_space, window, cx);
 8109        let git_gutter_width = EditorElement::gutter_strip_width(self.line_height)
 8110            + self.dimensions.git_blame_entries_width.unwrap_or_default();
 8111
 8112        let x = git_gutter_width + px(2.);
 8113
 8114        let mut y = Pixels::from(
 8115            (row.as_f64() - self.scroll_position.y) * ScrollPixelOffset::from(self.line_height),
 8116        );
 8117        y += (self.line_height - indicator_size.height) / 2.;
 8118
 8119        button.prepaint_as_root(
 8120            self.hitbox.origin + point(x, y),
 8121            available_space,
 8122            window,
 8123            cx,
 8124        );
 8125        button
 8126    }
 8127}
 8128
 8129pub fn render_breadcrumb_text(
 8130    mut segments: Vec<HighlightedText>,
 8131    breadcrumb_font: Option<Font>,
 8132    prefix: Option<gpui::AnyElement>,
 8133    active_item: &dyn ItemHandle,
 8134    multibuffer_header: bool,
 8135    window: &mut Window,
 8136    cx: &App,
 8137) -> gpui::AnyElement {
 8138    const MAX_SEGMENTS: usize = 12;
 8139
 8140    let element = h_flex().flex_grow().text_ui(cx);
 8141
 8142    let prefix_end_ix = cmp::min(segments.len(), MAX_SEGMENTS / 2);
 8143    let suffix_start_ix = cmp::max(
 8144        prefix_end_ix,
 8145        segments.len().saturating_sub(MAX_SEGMENTS / 2),
 8146    );
 8147
 8148    if suffix_start_ix > prefix_end_ix {
 8149        segments.splice(
 8150            prefix_end_ix..suffix_start_ix,
 8151            Some(HighlightedText {
 8152                text: "β‹―".into(),
 8153                highlights: vec![],
 8154            }),
 8155        );
 8156    }
 8157
 8158    let highlighted_segments = segments.into_iter().enumerate().map(|(index, segment)| {
 8159        let mut text_style = window.text_style();
 8160        if let Some(font) = &breadcrumb_font {
 8161            text_style.font_family = font.family.clone();
 8162            text_style.font_features = font.features.clone();
 8163            text_style.font_style = font.style;
 8164            text_style.font_weight = font.weight;
 8165        }
 8166        text_style.color = Color::Muted.color(cx);
 8167
 8168        if index == 0
 8169            && !workspace::TabBarSettings::get_global(cx).show
 8170            && active_item.is_dirty(cx)
 8171            && let Some(styled_element) = apply_dirty_filename_style(&segment, &text_style, cx)
 8172        {
 8173            return styled_element;
 8174        }
 8175
 8176        StyledText::new(segment.text.replace('\n', " "))
 8177            .with_default_highlights(&text_style, segment.highlights)
 8178            .into_any()
 8179    });
 8180
 8181    let breadcrumbs = Itertools::intersperse_with(highlighted_segments, || {
 8182        Label::new("β€Ί").color(Color::Placeholder).into_any_element()
 8183    });
 8184
 8185    let breadcrumbs_stack = h_flex()
 8186        .gap_1()
 8187        .when(multibuffer_header, |this| {
 8188            this.pl_2()
 8189                .border_l_1()
 8190                .border_color(cx.theme().colors().border.opacity(0.6))
 8191        })
 8192        .children(breadcrumbs);
 8193
 8194    let breadcrumbs = if let Some(prefix) = prefix {
 8195        h_flex().gap_1p5().child(prefix).child(breadcrumbs_stack)
 8196    } else {
 8197        breadcrumbs_stack
 8198    };
 8199
 8200    let editor = active_item
 8201        .downcast::<Editor>()
 8202        .map(|editor| editor.downgrade());
 8203
 8204    let has_project_path = active_item.project_path(cx).is_some();
 8205
 8206    match editor {
 8207        Some(editor) => element
 8208            .id("breadcrumb_container")
 8209            .when(!multibuffer_header, |this| this.overflow_x_scroll())
 8210            .child(
 8211                ButtonLike::new("toggle outline view")
 8212                    .child(breadcrumbs)
 8213                    .when(multibuffer_header, |this| {
 8214                        this.style(ButtonStyle::Transparent)
 8215                    })
 8216                    .when(!multibuffer_header, |this| {
 8217                        let focus_handle = editor.upgrade().unwrap().focus_handle(&cx);
 8218
 8219                        this.tooltip(Tooltip::element(move |_window, cx| {
 8220                            v_flex()
 8221                                .gap_1()
 8222                                .child(
 8223                                    h_flex()
 8224                                        .gap_1()
 8225                                        .justify_between()
 8226                                        .child(Label::new("Show Symbol Outline"))
 8227                                        .child(ui::KeyBinding::for_action_in(
 8228                                            &zed_actions::outline::ToggleOutline,
 8229                                            &focus_handle,
 8230                                            cx,
 8231                                        )),
 8232                                )
 8233                                .when(has_project_path, |this| {
 8234                                    this.child(
 8235                                        h_flex()
 8236                                            .gap_1()
 8237                                            .justify_between()
 8238                                            .pt_1()
 8239                                            .border_t_1()
 8240                                            .border_color(cx.theme().colors().border_variant)
 8241                                            .child(Label::new("Right-Click to Copy Path")),
 8242                                    )
 8243                                })
 8244                                .into_any_element()
 8245                        }))
 8246                        .on_click({
 8247                            let editor = editor.clone();
 8248                            move |_, window, cx| {
 8249                                if let Some((editor, callback)) = editor
 8250                                    .upgrade()
 8251                                    .zip(zed_actions::outline::TOGGLE_OUTLINE.get())
 8252                                {
 8253                                    callback(editor.to_any_view(), window, cx);
 8254                                }
 8255                            }
 8256                        })
 8257                        .when(has_project_path, |this| {
 8258                            this.on_right_click({
 8259                                let editor = editor.clone();
 8260                                move |_, _, cx| {
 8261                                    if let Some(abs_path) = editor.upgrade().and_then(|editor| {
 8262                                        editor.update(cx, |editor, cx| {
 8263                                            editor.target_file_abs_path(cx)
 8264                                        })
 8265                                    }) {
 8266                                        if let Some(path_str) = abs_path.to_str() {
 8267                                            cx.write_to_clipboard(ClipboardItem::new_string(
 8268                                                path_str.to_string(),
 8269                                            ));
 8270                                        }
 8271                                    }
 8272                                }
 8273                            })
 8274                        })
 8275                    }),
 8276            )
 8277            .into_any_element(),
 8278        None => element
 8279            .h(rems_from_px(22.)) // Match the height and padding of the `ButtonLike` in the other arm.
 8280            .pl_1()
 8281            .child(breadcrumbs)
 8282            .into_any_element(),
 8283    }
 8284}
 8285
 8286fn apply_dirty_filename_style(
 8287    segment: &HighlightedText,
 8288    text_style: &gpui::TextStyle,
 8289    cx: &App,
 8290) -> Option<gpui::AnyElement> {
 8291    let text = segment.text.replace('\n', " ");
 8292
 8293    let filename_position = std::path::Path::new(segment.text.as_ref())
 8294        .file_name()
 8295        .and_then(|f| {
 8296            let filename_str = f.to_string_lossy();
 8297            segment.text.rfind(filename_str.as_ref())
 8298        })?;
 8299
 8300    let bold_weight = FontWeight::BOLD;
 8301    let default_color = Color::Default.color(cx);
 8302
 8303    if filename_position == 0 {
 8304        let mut filename_style = text_style.clone();
 8305        filename_style.font_weight = bold_weight;
 8306        filename_style.color = default_color;
 8307
 8308        return Some(
 8309            StyledText::new(text)
 8310                .with_default_highlights(&filename_style, [])
 8311                .into_any(),
 8312        );
 8313    }
 8314
 8315    let highlight_style = gpui::HighlightStyle {
 8316        font_weight: Some(bold_weight),
 8317        color: Some(default_color),
 8318        ..Default::default()
 8319    };
 8320
 8321    let highlight = vec![(filename_position..text.len(), highlight_style)];
 8322    Some(
 8323        StyledText::new(text)
 8324            .with_default_highlights(text_style, highlight)
 8325            .into_any(),
 8326    )
 8327}
 8328
 8329fn file_status_label_color(file_status: Option<FileStatus>) -> Color {
 8330    file_status.map_or(Color::Default, |status| {
 8331        if status.is_conflicted() {
 8332            Color::Conflict
 8333        } else if status.is_modified() {
 8334            Color::Modified
 8335        } else if status.is_deleted() {
 8336            Color::Disabled
 8337        } else if status.is_created() {
 8338            Color::Created
 8339        } else {
 8340            Color::Default
 8341        }
 8342    })
 8343}
 8344
 8345pub(crate) fn header_jump_data(
 8346    editor_snapshot: &EditorSnapshot,
 8347    block_row_start: DisplayRow,
 8348    height: u32,
 8349    first_excerpt: &ExcerptBoundaryInfo,
 8350    latest_selection_anchors: &HashMap<BufferId, Anchor>,
 8351) -> JumpData {
 8352    let multibuffer_snapshot = editor_snapshot.buffer_snapshot();
 8353    let buffer = first_excerpt.buffer(multibuffer_snapshot);
 8354    let (jump_anchor, jump_buffer) = if let Some(anchor) =
 8355        latest_selection_anchors.get(&first_excerpt.buffer_id())
 8356        && let Some((jump_anchor, selection_buffer)) =
 8357            multibuffer_snapshot.anchor_to_buffer_anchor(*anchor)
 8358    {
 8359        (jump_anchor, selection_buffer)
 8360    } else {
 8361        (first_excerpt.range.primary.start, buffer)
 8362    };
 8363    let excerpt_start = first_excerpt.range.context.start;
 8364    let jump_position = language::ToPoint::to_point(&jump_anchor, jump_buffer);
 8365    let rows_from_excerpt_start = if jump_anchor == excerpt_start {
 8366        0
 8367    } else {
 8368        let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
 8369        jump_position.row.saturating_sub(excerpt_start_point.row)
 8370    };
 8371
 8372    let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
 8373        .saturating_sub(
 8374            editor_snapshot
 8375                .scroll_anchor
 8376                .scroll_position(&editor_snapshot.display_snapshot)
 8377                .y as u32,
 8378        );
 8379
 8380    JumpData::MultiBufferPoint {
 8381        anchor: jump_anchor,
 8382        position: jump_position,
 8383        line_offset_from_top,
 8384    }
 8385}
 8386
 8387pub(crate) fn render_buffer_header(
 8388    editor: &Entity<Editor>,
 8389    for_excerpt: &ExcerptBoundaryInfo,
 8390    is_folded: bool,
 8391    is_selected: bool,
 8392    is_sticky: bool,
 8393    jump_data: JumpData,
 8394    window: &mut Window,
 8395    cx: &mut App,
 8396) -> impl IntoElement {
 8397    let editor_read = editor.read(cx);
 8398    let multi_buffer = editor_read.buffer.read(cx);
 8399    let is_read_only = editor_read.read_only(cx);
 8400    let editor_handle: &dyn ItemHandle = editor;
 8401    let multibuffer_snapshot = multi_buffer.snapshot(cx);
 8402    let buffer = for_excerpt.buffer(&multibuffer_snapshot);
 8403
 8404    let breadcrumbs = if is_selected {
 8405        editor_read.breadcrumbs_inner(cx)
 8406    } else {
 8407        None
 8408    };
 8409
 8410    let buffer_id = for_excerpt.buffer_id();
 8411    let file_status = multi_buffer
 8412        .all_diff_hunks_expanded()
 8413        .then(|| editor_read.status_for_buffer_id(buffer_id, cx))
 8414        .flatten();
 8415    let indicator = multi_buffer.buffer(buffer_id).and_then(|buffer| {
 8416        let buffer = buffer.read(cx);
 8417        let indicator_color = match (buffer.has_conflict(), buffer.is_dirty()) {
 8418            (true, _) => Some(Color::Warning),
 8419            (_, true) => Some(Color::Accent),
 8420            (false, false) => None,
 8421        };
 8422        indicator_color.map(|indicator_color| Indicator::dot().color(indicator_color))
 8423    });
 8424
 8425    let include_root = editor_read
 8426        .project
 8427        .as_ref()
 8428        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 8429        .unwrap_or_default();
 8430    let file = buffer.file();
 8431    let can_open_excerpts = file.is_none_or(|file| file.can_open());
 8432    let path_style = file.map(|file| file.path_style(cx));
 8433    let relative_path = buffer.resolve_file_path(include_root, cx);
 8434    let (parent_path, filename) = if let Some(path) = &relative_path {
 8435        if let Some(path_style) = path_style {
 8436            let (dir, file_name) = path_style.split(path);
 8437            (dir.map(|dir| dir.to_owned()), Some(file_name.to_owned()))
 8438        } else {
 8439            (None, Some(path.clone()))
 8440        }
 8441    } else {
 8442        (None, None)
 8443    };
 8444    let focus_handle = editor_read.focus_handle(cx);
 8445    let colors = cx.theme().colors();
 8446
 8447    let header = div()
 8448        .id(("buffer-header", buffer_id.to_proto()))
 8449        .p(BUFFER_HEADER_PADDING)
 8450        .w_full()
 8451        .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
 8452        .child(
 8453            h_flex()
 8454                .group("buffer-header-group")
 8455                .size_full()
 8456                .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
 8457                .pl_1()
 8458                .pr_2()
 8459                .rounded_sm()
 8460                .gap_1p5()
 8461                .when(is_sticky, |el| el.shadow_md())
 8462                .border_1()
 8463                .map(|border| {
 8464                    let border_color =
 8465                        if is_selected && is_folded && focus_handle.contains_focused(window, cx) {
 8466                            colors.border_focused
 8467                        } else {
 8468                            colors.border
 8469                        };
 8470                    border.border_color(border_color)
 8471                })
 8472                .bg(colors.editor_subheader_background)
 8473                .hover(|style| style.bg(colors.element_hover))
 8474                .map(|header| {
 8475                    let editor = editor.clone();
 8476                    let buffer_id = for_excerpt.buffer_id();
 8477                    let toggle_chevron_icon =
 8478                        FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
 8479                    let button_size = rems_from_px(28.);
 8480
 8481                    header.child(
 8482                        div()
 8483                            .hover(|style| style.bg(colors.element_selected))
 8484                            .rounded_xs()
 8485                            .child(
 8486                                ButtonLike::new("toggle-buffer-fold")
 8487                                    .style(ButtonStyle::Transparent)
 8488                                    .height(button_size.into())
 8489                                    .width(button_size)
 8490                                    .children(toggle_chevron_icon)
 8491                                    .tooltip({
 8492                                        let focus_handle = focus_handle.clone();
 8493                                        let is_folded_for_tooltip = is_folded;
 8494                                        move |_window, cx| {
 8495                                            Tooltip::with_meta_in(
 8496                                                if is_folded_for_tooltip {
 8497                                                    "Unfold Excerpt"
 8498                                                } else {
 8499                                                    "Fold Excerpt"
 8500                                                },
 8501                                                Some(&ToggleFold),
 8502                                                format!(
 8503                                                    "{} to toggle all",
 8504                                                    text_for_keystroke(
 8505                                                        &Modifiers::alt(),
 8506                                                        "click",
 8507                                                        cx
 8508                                                    )
 8509                                                ),
 8510                                                &focus_handle,
 8511                                                cx,
 8512                                            )
 8513                                        }
 8514                                    })
 8515                                    .on_click(move |event, window, cx| {
 8516                                        if event.modifiers().alt {
 8517                                            editor.update(cx, |editor, cx| {
 8518                                                editor.toggle_fold_all(&ToggleFoldAll, window, cx);
 8519                                            });
 8520                                        } else {
 8521                                            if is_folded {
 8522                                                editor.update(cx, |editor, cx| {
 8523                                                    editor.unfold_buffer(buffer_id, cx);
 8524                                                });
 8525                                            } else {
 8526                                                editor.update(cx, |editor, cx| {
 8527                                                    editor.fold_buffer(buffer_id, cx);
 8528                                                });
 8529                                            }
 8530                                        }
 8531                                    }),
 8532                            ),
 8533                    )
 8534                })
 8535                .children(
 8536                    editor_read
 8537                        .addons
 8538                        .values()
 8539                        .filter_map(|addon| {
 8540                            addon.render_buffer_header_controls(for_excerpt, buffer, window, cx)
 8541                        })
 8542                        .take(1),
 8543                )
 8544                .when(!is_read_only, |this| {
 8545                    this.child(
 8546                        h_flex()
 8547                            .size_3()
 8548                            .justify_center()
 8549                            .flex_shrink_0()
 8550                            .children(indicator),
 8551                    )
 8552                })
 8553                .child(
 8554                    h_flex()
 8555                        .cursor_pointer()
 8556                        .id("path_header_block")
 8557                        .min_w_0()
 8558                        .size_full()
 8559                        .gap_1()
 8560                        .justify_between()
 8561                        .overflow_hidden()
 8562                        .child(h_flex().min_w_0().flex_1().gap_0p5().overflow_hidden().map(
 8563                            |path_header| {
 8564                                let filename = filename
 8565                                    .map(SharedString::from)
 8566                                    .unwrap_or_else(|| "untitled".into());
 8567
 8568                                let full_path = match parent_path.as_deref() {
 8569                                    Some(parent) if !parent.is_empty() => {
 8570                                        format!("{}{}", parent, filename.as_str())
 8571                                    }
 8572                                    _ => filename.as_str().to_string(),
 8573                                };
 8574
 8575                                path_header
 8576                                    .child(
 8577                                        ButtonLike::new("filename-button")
 8578                                            .when(ItemSettings::get_global(cx).file_icons, |this| {
 8579                                                let path = path::Path::new(filename.as_str());
 8580                                                let icon = FileIcons::get_icon(path, cx)
 8581                                                    .unwrap_or_default();
 8582
 8583                                                this.child(
 8584                                                    Icon::from_path(icon).color(Color::Muted),
 8585                                                )
 8586                                            })
 8587                                            .child(
 8588                                                Label::new(filename)
 8589                                                    .single_line()
 8590                                                    .color(file_status_label_color(file_status))
 8591                                                    .buffer_font(cx)
 8592                                                    .when(
 8593                                                        file_status.is_some_and(|s| s.is_deleted()),
 8594                                                        |label| label.strikethrough(),
 8595                                                    ),
 8596                                            )
 8597                                            .tooltip(move |_, cx| {
 8598                                                Tooltip::with_meta(
 8599                                                    "Open File",
 8600                                                    None,
 8601                                                    full_path.clone(),
 8602                                                    cx,
 8603                                                )
 8604                                            })
 8605                                            .on_click(window.listener_for(editor, {
 8606                                                let jump_data = jump_data.clone();
 8607                                                move |editor, e: &ClickEvent, window, cx| {
 8608                                                    editor.open_excerpts_common(
 8609                                                        Some(jump_data.clone()),
 8610                                                        e.modifiers().secondary(),
 8611                                                        window,
 8612                                                        cx,
 8613                                                    );
 8614                                                }
 8615                                            })),
 8616                                    )
 8617                                    .when_some(parent_path, |then, path| {
 8618                                        then.child(
 8619                                            Label::new(path)
 8620                                                .buffer_font(cx)
 8621                                                .truncate_start()
 8622                                                .color(
 8623                                                    if file_status
 8624                                                        .is_some_and(FileStatus::is_deleted)
 8625                                                    {
 8626                                                        Color::Custom(colors.text_disabled)
 8627                                                    } else {
 8628                                                        Color::Custom(colors.text_muted)
 8629                                                    },
 8630                                                ),
 8631                                        )
 8632                                    })
 8633                                    .when(!buffer.capability.editable(), |el| {
 8634                                        el.child(Icon::new(IconName::FileLock).color(Color::Muted))
 8635                                    })
 8636                                    .when_some(breadcrumbs, |then, breadcrumbs| {
 8637                                        let font = theme_settings::ThemeSettings::get_global(cx)
 8638                                            .buffer_font
 8639                                            .clone();
 8640                                        then.child(render_breadcrumb_text(
 8641                                            breadcrumbs,
 8642                                            Some(font),
 8643                                            None,
 8644                                            editor_handle,
 8645                                            true,
 8646                                            window,
 8647                                            cx,
 8648                                        ))
 8649                                    })
 8650                            },
 8651                        ))
 8652                        .when(can_open_excerpts && relative_path.is_some(), |this| {
 8653                            this.child(
 8654                                div()
 8655                                    .when(!is_selected, |this| {
 8656                                        this.visible_on_hover("buffer-header-group")
 8657                                    })
 8658                                    .child(
 8659                                        Button::new("open-file-button", "Open File")
 8660                                            .style(ButtonStyle::OutlinedGhost)
 8661                                            .when(is_selected, |this| {
 8662                                                this.key_binding(KeyBinding::for_action_in(
 8663                                                    &OpenExcerpts,
 8664                                                    &focus_handle,
 8665                                                    cx,
 8666                                                ))
 8667                                            })
 8668                                            .on_click(window.listener_for(editor, {
 8669                                                let jump_data = jump_data.clone();
 8670                                                move |editor, e: &ClickEvent, window, cx| {
 8671                                                    editor.open_excerpts_common(
 8672                                                        Some(jump_data.clone()),
 8673                                                        e.modifiers().secondary(),
 8674                                                        window,
 8675                                                        cx,
 8676                                                    );
 8677                                                }
 8678                                            })),
 8679                                    ),
 8680                            )
 8681                        })
 8682                        .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 8683                        .on_click(window.listener_for(editor, {
 8684                            let buffer_id = for_excerpt.buffer_id();
 8685                            move |editor, e: &ClickEvent, window, cx| {
 8686                                if e.modifiers().alt {
 8687                                    editor.open_excerpts_common(
 8688                                        Some(jump_data.clone()),
 8689                                        e.modifiers().secondary(),
 8690                                        window,
 8691                                        cx,
 8692                                    );
 8693                                    return;
 8694                                }
 8695
 8696                                if is_folded {
 8697                                    editor.unfold_buffer(buffer_id, cx);
 8698                                } else {
 8699                                    editor.fold_buffer(buffer_id, cx);
 8700                                }
 8701                            }
 8702                        })),
 8703                ),
 8704        );
 8705
 8706    let file = buffer.file().cloned();
 8707    let editor = editor.clone();
 8708
 8709    right_click_menu("buffer-header-context-menu")
 8710        .trigger(move |_, _, _| header)
 8711        .menu(move |window, cx| {
 8712            let menu_context = focus_handle.clone();
 8713            let editor = editor.clone();
 8714            let file = file.clone();
 8715            ContextMenu::build(window, cx, move |mut menu, window, cx| {
 8716                if let Some(file) = file
 8717                    && let Some(project) = editor.read(cx).project()
 8718                    && let Some(worktree) =
 8719                        project.read(cx).worktree_for_id(file.worktree_id(cx), cx)
 8720                {
 8721                    let path_style = file.path_style(cx);
 8722                    let worktree = worktree.read(cx);
 8723                    let relative_path = file.path();
 8724                    let entry_for_path = worktree.entry_for_path(relative_path);
 8725                    let abs_path = entry_for_path.map(|e| {
 8726                        e.canonical_path
 8727                            .as_deref()
 8728                            .map_or_else(|| worktree.absolutize(relative_path), Path::to_path_buf)
 8729                    });
 8730                    let has_relative_path = worktree.root_entry().is_some_and(Entry::is_dir);
 8731
 8732                    let parent_abs_path = abs_path
 8733                        .as_ref()
 8734                        .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
 8735                    let relative_path = has_relative_path
 8736                        .then_some(relative_path)
 8737                        .map(ToOwned::to_owned);
 8738
 8739                    let visible_in_project_panel = relative_path.is_some() && worktree.is_visible();
 8740                    let reveal_in_project_panel = entry_for_path
 8741                        .filter(|_| visible_in_project_panel)
 8742                        .map(|entry| entry.id);
 8743                    menu = menu
 8744                        .when_some(abs_path, |menu, abs_path| {
 8745                            menu.entry(
 8746                                "Copy Path",
 8747                                Some(Box::new(zed_actions::workspace::CopyPath)),
 8748                                window.handler_for(&editor, move |_, _, cx| {
 8749                                    cx.write_to_clipboard(ClipboardItem::new_string(
 8750                                        abs_path.to_string_lossy().into_owned(),
 8751                                    ));
 8752                                }),
 8753                            )
 8754                        })
 8755                        .when_some(relative_path, |menu, relative_path| {
 8756                            menu.entry(
 8757                                "Copy Relative Path",
 8758                                Some(Box::new(zed_actions::workspace::CopyRelativePath)),
 8759                                window.handler_for(&editor, move |_, _, cx| {
 8760                                    cx.write_to_clipboard(ClipboardItem::new_string(
 8761                                        relative_path.display(path_style).to_string(),
 8762                                    ));
 8763                                }),
 8764                            )
 8765                        })
 8766                        .when(
 8767                            reveal_in_project_panel.is_some() || parent_abs_path.is_some(),
 8768                            |menu| menu.separator(),
 8769                        )
 8770                        .when_some(reveal_in_project_panel, |menu, entry_id| {
 8771                            menu.entry(
 8772                                "Reveal In Project Panel",
 8773                                Some(Box::new(RevealInProjectPanel::default())),
 8774                                window.handler_for(&editor, move |editor, _, cx| {
 8775                                    if let Some(project) = &mut editor.project {
 8776                                        project.update(cx, |_, cx| {
 8777                                            cx.emit(project::Event::RevealInProjectPanel(entry_id))
 8778                                        });
 8779                                    }
 8780                                }),
 8781                            )
 8782                        })
 8783                        .when_some(parent_abs_path, |menu, parent_abs_path| {
 8784                            menu.entry(
 8785                                "Open in Terminal",
 8786                                Some(Box::new(OpenInTerminal)),
 8787                                window.handler_for(&editor, move |_, window, cx| {
 8788                                    window.dispatch_action(
 8789                                        OpenTerminal {
 8790                                            working_directory: parent_abs_path.clone(),
 8791                                            local: false,
 8792                                        }
 8793                                        .boxed_clone(),
 8794                                        cx,
 8795                                    );
 8796                                }),
 8797                            )
 8798                        });
 8799                }
 8800
 8801                menu.context(menu_context)
 8802            })
 8803        })
 8804}
 8805
 8806fn render_inline_blame_entry(
 8807    blame_entry: BlameEntry,
 8808    style: &EditorStyle,
 8809    cx: &mut App,
 8810) -> Option<AnyElement> {
 8811    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 8812    renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
 8813}
 8814
 8815fn render_blame_entry_popover(
 8816    blame_entry: BlameEntry,
 8817    scroll_handle: ScrollHandle,
 8818    commit_message: Option<ParsedCommitMessage>,
 8819    markdown: Entity<Markdown>,
 8820    workspace: WeakEntity<Workspace>,
 8821    blame: &Entity<GitBlame>,
 8822    buffer: BufferId,
 8823    window: &mut Window,
 8824    cx: &mut App,
 8825) -> Option<AnyElement> {
 8826    if markdown.read(cx).is_parsing() {
 8827        return None;
 8828    }
 8829
 8830    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 8831    let blame = blame.read(cx);
 8832    let repository = blame.repository(cx, buffer)?;
 8833    renderer.render_blame_entry_popover(
 8834        blame_entry,
 8835        scroll_handle,
 8836        commit_message,
 8837        markdown,
 8838        repository,
 8839        workspace,
 8840        window,
 8841        cx,
 8842    )
 8843}
 8844
 8845fn render_blame_entry(
 8846    ix: usize,
 8847    blame: &Entity<GitBlame>,
 8848    blame_entry: BlameEntry,
 8849    style: &EditorStyle,
 8850    last_used_color: &mut Option<(Hsla, Oid)>,
 8851    editor: Entity<Editor>,
 8852    workspace: Entity<Workspace>,
 8853    buffer: BufferId,
 8854    renderer: &dyn BlameRenderer,
 8855    window: &mut Window,
 8856    cx: &mut App,
 8857) -> Option<AnyElement> {
 8858    let index: u32 = blame_entry.sha.into();
 8859    let mut sha_color = cx.theme().players().color_for_participant(index).cursor;
 8860
 8861    // If the last color we used is the same as the one we get for this line, but
 8862    // the commit SHAs are different, then we try again to get a different color.
 8863    if let Some((color, sha)) = *last_used_color
 8864        && sha != blame_entry.sha
 8865        && color == sha_color
 8866    {
 8867        sha_color = cx.theme().players().color_for_participant(index + 1).cursor;
 8868    }
 8869    last_used_color.replace((sha_color, blame_entry.sha));
 8870
 8871    let blame = blame.read(cx);
 8872    let details = blame.details_for_entry(buffer, &blame_entry);
 8873    let repository = blame.repository(cx, buffer)?;
 8874    renderer.render_blame_entry(
 8875        &style.text,
 8876        blame_entry,
 8877        details,
 8878        repository,
 8879        workspace.downgrade(),
 8880        editor,
 8881        ix,
 8882        sha_color,
 8883        window,
 8884        cx,
 8885    )
 8886}
 8887
 8888#[derive(Debug)]
 8889pub(crate) struct LineWithInvisibles {
 8890    fragments: SmallVec<[LineFragment; 1]>,
 8891    invisibles: Vec<Invisible>,
 8892    len: usize,
 8893    pub(crate) width: Pixels,
 8894    font_size: Pixels,
 8895}
 8896
 8897enum LineFragment {
 8898    Text(ShapedLine),
 8899    Element {
 8900        id: ChunkRendererId,
 8901        element: Option<AnyElement>,
 8902        size: Size<Pixels>,
 8903        len: usize,
 8904    },
 8905}
 8906
 8907impl fmt::Debug for LineFragment {
 8908    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 8909        match self {
 8910            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
 8911            LineFragment::Element { size, len, .. } => f
 8912                .debug_struct("Element")
 8913                .field("size", size)
 8914                .field("len", len)
 8915                .finish(),
 8916        }
 8917    }
 8918}
 8919
 8920impl LineWithInvisibles {
 8921    fn from_chunks<'a>(
 8922        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
 8923        editor_style: &EditorStyle,
 8924        max_line_len: usize,
 8925        max_line_count: usize,
 8926        editor_mode: &EditorMode,
 8927        text_width: Pixels,
 8928        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 8929        bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
 8930        window: &mut Window,
 8931        cx: &mut App,
 8932    ) -> Vec<Self> {
 8933        let text_style = &editor_style.text;
 8934        let mut layouts = Vec::with_capacity(max_line_count);
 8935        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
 8936        let mut line = String::new();
 8937        let mut invisibles = Vec::new();
 8938        let mut width = Pixels::ZERO;
 8939        let mut len = 0;
 8940        let mut styles = Vec::new();
 8941        let mut non_whitespace_added = false;
 8942        let mut row = 0;
 8943        let mut line_exceeded_max_len = false;
 8944        let font_size = text_style.font_size.to_pixels(window.rem_size());
 8945        let min_contrast = EditorSettings::get_global(cx).minimum_contrast_for_highlights;
 8946
 8947        let ellipsis = SharedString::from("β‹―");
 8948
 8949        for highlighted_chunk in chunks.chain([HighlightedChunk {
 8950            text: "\n",
 8951            style: None,
 8952            is_tab: false,
 8953            is_inlay: false,
 8954            replacement: None,
 8955        }]) {
 8956            if let Some(replacement) = highlighted_chunk.replacement {
 8957                if !line.is_empty() {
 8958                    let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
 8959                    let text_runs: &[TextRun] = if segments.is_empty() {
 8960                        &styles
 8961                    } else {
 8962                        &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
 8963                    };
 8964                    let shaped_line = window.text_system().shape_line(
 8965                        line.clone().into(),
 8966                        font_size,
 8967                        text_runs,
 8968                        None,
 8969                    );
 8970                    width += shaped_line.width;
 8971                    len += shaped_line.len;
 8972                    fragments.push(LineFragment::Text(shaped_line));
 8973                    line.clear();
 8974                    styles.clear();
 8975                }
 8976
 8977                match replacement {
 8978                    ChunkReplacement::Renderer(renderer) => {
 8979                        let available_width = if renderer.constrain_width {
 8980                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
 8981                                ellipsis.clone()
 8982                            } else {
 8983                                SharedString::from(Arc::from(highlighted_chunk.text))
 8984                            };
 8985                            let shaped_line = window.text_system().shape_line(
 8986                                chunk,
 8987                                font_size,
 8988                                &[text_style.to_run(highlighted_chunk.text.len())],
 8989                                None,
 8990                            );
 8991                            AvailableSpace::Definite(shaped_line.width)
 8992                        } else {
 8993                            AvailableSpace::MinContent
 8994                        };
 8995
 8996                        let mut element = (renderer.render)(&mut ChunkRendererContext {
 8997                            context: cx,
 8998                            window,
 8999                            max_width: text_width,
 9000                        });
 9001                        let line_height = text_style.line_height_in_pixels(window.rem_size());
 9002                        let size = element.layout_as_root(
 9003                            size(available_width, AvailableSpace::Definite(line_height)),
 9004                            window,
 9005                            cx,
 9006                        );
 9007
 9008                        width += size.width;
 9009                        len += highlighted_chunk.text.len();
 9010                        fragments.push(LineFragment::Element {
 9011                            id: renderer.id,
 9012                            element: Some(element),
 9013                            size,
 9014                            len: highlighted_chunk.text.len(),
 9015                        });
 9016                    }
 9017                    ChunkReplacement::Str(x) => {
 9018                        let text_style = if let Some(style) = highlighted_chunk.style {
 9019                            Cow::Owned(text_style.clone().highlight(style))
 9020                        } else {
 9021                            Cow::Borrowed(text_style)
 9022                        };
 9023
 9024                        let run = TextRun {
 9025                            len: x.len(),
 9026                            font: text_style.font(),
 9027                            color: text_style.color,
 9028                            background_color: text_style.background_color,
 9029                            underline: text_style.underline,
 9030                            strikethrough: text_style.strikethrough,
 9031                        };
 9032                        let line_layout = window
 9033                            .text_system()
 9034                            .shape_line(x, font_size, &[run], None)
 9035                            .with_len(highlighted_chunk.text.len());
 9036
 9037                        width += line_layout.width;
 9038                        len += highlighted_chunk.text.len();
 9039                        fragments.push(LineFragment::Text(line_layout))
 9040                    }
 9041                }
 9042            } else {
 9043                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
 9044                    if ix > 0 {
 9045                        let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
 9046                        let text_runs = if segments.is_empty() {
 9047                            &styles
 9048                        } else {
 9049                            &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
 9050                        };
 9051                        let shaped_line = window.text_system().shape_line(
 9052                            line.clone().into(),
 9053                            font_size,
 9054                            text_runs,
 9055                            None,
 9056                        );
 9057                        width += shaped_line.width;
 9058                        len += shaped_line.len;
 9059                        fragments.push(LineFragment::Text(shaped_line));
 9060                        layouts.push(Self {
 9061                            width: mem::take(&mut width),
 9062                            len: mem::take(&mut len),
 9063                            fragments: mem::take(&mut fragments),
 9064                            invisibles: std::mem::take(&mut invisibles),
 9065                            font_size,
 9066                        });
 9067
 9068                        line.clear();
 9069                        styles.clear();
 9070                        row += 1;
 9071                        line_exceeded_max_len = false;
 9072                        non_whitespace_added = false;
 9073                        if row == max_line_count {
 9074                            return layouts;
 9075                        }
 9076                    }
 9077
 9078                    if !line_chunk.is_empty() && !line_exceeded_max_len {
 9079                        let text_style = if let Some(style) = highlighted_chunk.style {
 9080                            Cow::Owned(text_style.clone().highlight(style))
 9081                        } else {
 9082                            Cow::Borrowed(text_style)
 9083                        };
 9084
 9085                        if line.len() + line_chunk.len() > max_line_len {
 9086                            let mut chunk_len = max_line_len - line.len();
 9087                            while !line_chunk.is_char_boundary(chunk_len) {
 9088                                chunk_len -= 1;
 9089                            }
 9090                            line_chunk = &line_chunk[..chunk_len];
 9091                            line_exceeded_max_len = true;
 9092                        }
 9093
 9094                        styles.push(TextRun {
 9095                            len: line_chunk.len(),
 9096                            font: text_style.font(),
 9097                            color: text_style.color,
 9098                            background_color: text_style.background_color,
 9099                            underline: text_style.underline,
 9100                            strikethrough: text_style.strikethrough,
 9101                        });
 9102
 9103                        if editor_mode.is_full() && !highlighted_chunk.is_inlay {
 9104                            // Line wrap pads its contents with fake whitespaces,
 9105                            // avoid printing them
 9106                            let is_soft_wrapped = is_row_soft_wrapped(row);
 9107                            if highlighted_chunk.is_tab {
 9108                                if non_whitespace_added || !is_soft_wrapped {
 9109                                    invisibles.push(Invisible::Tab {
 9110                                        line_start_offset: line.len(),
 9111                                        line_end_offset: line.len() + line_chunk.len(),
 9112                                    });
 9113                                }
 9114                            } else {
 9115                                invisibles.extend(line_chunk.char_indices().filter_map(
 9116                                    |(index, c)| {
 9117                                        let is_whitespace = c.is_whitespace();
 9118                                        non_whitespace_added |= !is_whitespace;
 9119                                        if is_whitespace
 9120                                            && (non_whitespace_added || !is_soft_wrapped)
 9121                                        {
 9122                                            Some(Invisible::Whitespace {
 9123                                                line_offset: line.len() + index,
 9124                                            })
 9125                                        } else {
 9126                                            None
 9127                                        }
 9128                                    },
 9129                                ))
 9130                            }
 9131                        }
 9132
 9133                        line.push_str(line_chunk);
 9134                    }
 9135                }
 9136            }
 9137        }
 9138
 9139        layouts
 9140    }
 9141
 9142    /// Takes text runs and non-overlapping left-to-right background ranges with color.
 9143    /// Returns new text runs with adjusted contrast as per background ranges.
 9144    fn split_runs_by_bg_segments(
 9145        text_runs: &[TextRun],
 9146        bg_segments: &[(Range<DisplayPoint>, Hsla)],
 9147        min_contrast: f32,
 9148        start_col_offset: usize,
 9149    ) -> Vec<TextRun> {
 9150        let mut output_runs: Vec<TextRun> = Vec::with_capacity(text_runs.len());
 9151        let mut line_col = start_col_offset;
 9152        let mut segment_ix = 0usize;
 9153
 9154        for text_run in text_runs.iter() {
 9155            let run_start_col = line_col;
 9156            let run_end_col = run_start_col + text_run.len;
 9157            while segment_ix < bg_segments.len()
 9158                && (bg_segments[segment_ix].0.end.column() as usize) <= run_start_col
 9159            {
 9160                segment_ix += 1;
 9161            }
 9162            let mut cursor_col = run_start_col;
 9163            let mut local_segment_ix = segment_ix;
 9164            while local_segment_ix < bg_segments.len() {
 9165                let (range, segment_color) = &bg_segments[local_segment_ix];
 9166                let segment_start_col = range.start.column() as usize;
 9167                let segment_end_col = range.end.column() as usize;
 9168                if segment_start_col >= run_end_col {
 9169                    break;
 9170                }
 9171                if segment_start_col > cursor_col {
 9172                    let span_len = segment_start_col - cursor_col;
 9173                    output_runs.push(TextRun {
 9174                        len: span_len,
 9175                        font: text_run.font.clone(),
 9176                        color: text_run.color,
 9177                        background_color: text_run.background_color,
 9178                        underline: text_run.underline,
 9179                        strikethrough: text_run.strikethrough,
 9180                    });
 9181                    cursor_col = segment_start_col;
 9182                }
 9183                let segment_slice_end_col = segment_end_col.min(run_end_col);
 9184                if segment_slice_end_col > cursor_col {
 9185                    let new_text_color =
 9186                        ensure_minimum_contrast(text_run.color, *segment_color, min_contrast);
 9187                    output_runs.push(TextRun {
 9188                        len: segment_slice_end_col - cursor_col,
 9189                        font: text_run.font.clone(),
 9190                        color: new_text_color,
 9191                        background_color: text_run.background_color,
 9192                        underline: text_run.underline,
 9193                        strikethrough: text_run.strikethrough,
 9194                    });
 9195                    cursor_col = segment_slice_end_col;
 9196                }
 9197                if segment_end_col >= run_end_col {
 9198                    break;
 9199                }
 9200                local_segment_ix += 1;
 9201            }
 9202            if cursor_col < run_end_col {
 9203                output_runs.push(TextRun {
 9204                    len: run_end_col - cursor_col,
 9205                    font: text_run.font.clone(),
 9206                    color: text_run.color,
 9207                    background_color: text_run.background_color,
 9208                    underline: text_run.underline,
 9209                    strikethrough: text_run.strikethrough,
 9210                });
 9211            }
 9212            line_col = run_end_col;
 9213            segment_ix = local_segment_ix;
 9214        }
 9215        output_runs
 9216    }
 9217
 9218    fn prepaint(
 9219        &mut self,
 9220        line_height: Pixels,
 9221        scroll_position: gpui::Point<ScrollOffset>,
 9222        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 9223        row: DisplayRow,
 9224        content_origin: gpui::Point<Pixels>,
 9225        line_elements: &mut SmallVec<[AnyElement; 1]>,
 9226        window: &mut Window,
 9227        cx: &mut App,
 9228    ) {
 9229        let line_y = f32::from(line_height) * Pixels::from(row.as_f64() - scroll_position.y);
 9230        self.prepaint_with_custom_offset(
 9231            line_height,
 9232            scroll_pixel_position,
 9233            content_origin,
 9234            line_y,
 9235            line_elements,
 9236            window,
 9237            cx,
 9238        );
 9239    }
 9240
 9241    fn prepaint_with_custom_offset(
 9242        &mut self,
 9243        line_height: Pixels,
 9244        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 9245        content_origin: gpui::Point<Pixels>,
 9246        line_y: Pixels,
 9247        line_elements: &mut SmallVec<[AnyElement; 1]>,
 9248        window: &mut Window,
 9249        cx: &mut App,
 9250    ) {
 9251        let mut fragment_origin =
 9252            content_origin + gpui::point(Pixels::from(-scroll_pixel_position.x), line_y);
 9253        for fragment in &mut self.fragments {
 9254            match fragment {
 9255                LineFragment::Text(line) => {
 9256                    fragment_origin.x += line.width;
 9257                }
 9258                LineFragment::Element { element, size, .. } => {
 9259                    let mut element = element
 9260                        .take()
 9261                        .expect("you can't prepaint LineWithInvisibles twice");
 9262
 9263                    // Center the element vertically within the line.
 9264                    let mut element_origin = fragment_origin;
 9265                    element_origin.y += (line_height - size.height) / 2.;
 9266                    element.prepaint_at(element_origin, window, cx);
 9267                    line_elements.push(element);
 9268
 9269                    fragment_origin.x += size.width;
 9270                }
 9271            }
 9272        }
 9273    }
 9274
 9275    fn draw(
 9276        &self,
 9277        layout: &EditorLayout,
 9278        row: DisplayRow,
 9279        content_origin: gpui::Point<Pixels>,
 9280        whitespace_setting: ShowWhitespaceSetting,
 9281        selection_ranges: &[Range<DisplayPoint>],
 9282        window: &mut Window,
 9283        cx: &mut App,
 9284    ) {
 9285        self.draw_with_custom_offset(
 9286            layout,
 9287            row,
 9288            content_origin,
 9289            layout.position_map.line_height
 9290                * (row.as_f64() - layout.position_map.scroll_position.y) as f32,
 9291            whitespace_setting,
 9292            selection_ranges,
 9293            window,
 9294            cx,
 9295        );
 9296    }
 9297
 9298    fn draw_with_custom_offset(
 9299        &self,
 9300        layout: &EditorLayout,
 9301        row: DisplayRow,
 9302        content_origin: gpui::Point<Pixels>,
 9303        line_y: Pixels,
 9304        whitespace_setting: ShowWhitespaceSetting,
 9305        selection_ranges: &[Range<DisplayPoint>],
 9306        window: &mut Window,
 9307        cx: &mut App,
 9308    ) {
 9309        let line_height = layout.position_map.line_height;
 9310        let mut fragment_origin = content_origin
 9311            + gpui::point(
 9312                Pixels::from(-layout.position_map.scroll_pixel_position.x),
 9313                line_y,
 9314            );
 9315
 9316        for fragment in &self.fragments {
 9317            match fragment {
 9318                LineFragment::Text(line) => {
 9319                    line.paint(
 9320                        fragment_origin,
 9321                        line_height,
 9322                        layout.text_align,
 9323                        Some(layout.content_width),
 9324                        window,
 9325                        cx,
 9326                    )
 9327                    .log_err();
 9328                    fragment_origin.x += line.width;
 9329                }
 9330                LineFragment::Element { size, .. } => {
 9331                    fragment_origin.x += size.width;
 9332                }
 9333            }
 9334        }
 9335
 9336        self.draw_invisibles(
 9337            selection_ranges,
 9338            layout,
 9339            content_origin,
 9340            line_y,
 9341            row,
 9342            line_height,
 9343            whitespace_setting,
 9344            window,
 9345            cx,
 9346        );
 9347    }
 9348
 9349    fn draw_background(
 9350        &self,
 9351        layout: &EditorLayout,
 9352        row: DisplayRow,
 9353        content_origin: gpui::Point<Pixels>,
 9354        window: &mut Window,
 9355        cx: &mut App,
 9356    ) {
 9357        let line_height = layout.position_map.line_height;
 9358        let line_y = line_height * (row.as_f64() - layout.position_map.scroll_position.y) as f32;
 9359
 9360        let mut fragment_origin = content_origin
 9361            + gpui::point(
 9362                Pixels::from(-layout.position_map.scroll_pixel_position.x),
 9363                line_y,
 9364            );
 9365
 9366        for fragment in &self.fragments {
 9367            match fragment {
 9368                LineFragment::Text(line) => {
 9369                    line.paint_background(
 9370                        fragment_origin,
 9371                        line_height,
 9372                        layout.text_align,
 9373                        Some(layout.content_width),
 9374                        window,
 9375                        cx,
 9376                    )
 9377                    .log_err();
 9378                    fragment_origin.x += line.width;
 9379                }
 9380                LineFragment::Element { size, .. } => {
 9381                    fragment_origin.x += size.width;
 9382                }
 9383            }
 9384        }
 9385    }
 9386
 9387    fn draw_invisibles(
 9388        &self,
 9389        selection_ranges: &[Range<DisplayPoint>],
 9390        layout: &EditorLayout,
 9391        content_origin: gpui::Point<Pixels>,
 9392        line_y: Pixels,
 9393        row: DisplayRow,
 9394        line_height: Pixels,
 9395        whitespace_setting: ShowWhitespaceSetting,
 9396        window: &mut Window,
 9397        cx: &mut App,
 9398    ) {
 9399        let extract_whitespace_info = |invisible: &Invisible| {
 9400            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
 9401                Invisible::Tab {
 9402                    line_start_offset,
 9403                    line_end_offset,
 9404                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
 9405                Invisible::Whitespace { line_offset } => {
 9406                    (*line_offset, line_offset + 1, &layout.space_invisible)
 9407                }
 9408            };
 9409
 9410            let x_offset: ScrollPixelOffset = self.x_for_index(token_offset).into();
 9411            let invisible_offset: ScrollPixelOffset =
 9412                ((layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0)
 9413                    .into();
 9414            let origin = content_origin
 9415                + gpui::point(
 9416                    Pixels::from(
 9417                        x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
 9418                    ),
 9419                    line_y,
 9420                );
 9421
 9422            (
 9423                [token_offset, token_end_offset],
 9424                Box::new(move |window: &mut Window, cx: &mut App| {
 9425                    invisible_symbol
 9426                        .paint(origin, line_height, TextAlign::Left, None, window, cx)
 9427                        .log_err();
 9428                }),
 9429            )
 9430        };
 9431
 9432        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
 9433        match whitespace_setting {
 9434            ShowWhitespaceSetting::None => (),
 9435            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
 9436            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
 9437                let invisible_point = DisplayPoint::new(row, start as u32);
 9438                if !selection_ranges
 9439                    .iter()
 9440                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
 9441                {
 9442                    return;
 9443                }
 9444
 9445                paint(window, cx);
 9446            }),
 9447
 9448            ShowWhitespaceSetting::Trailing => {
 9449                let mut previous_start = self.len;
 9450                for ([start, end], paint) in invisible_iter.rev() {
 9451                    if previous_start != end {
 9452                        break;
 9453                    }
 9454                    previous_start = start;
 9455                    paint(window, cx);
 9456                }
 9457            }
 9458
 9459            // For a whitespace to be on a boundary, any of the following conditions need to be met:
 9460            // - It is a tab
 9461            // - It is adjacent to an edge (start or end)
 9462            // - It is adjacent to a whitespace (left or right)
 9463            ShowWhitespaceSetting::Boundary => {
 9464                // 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
 9465                // the above cases.
 9466                // Note: We zip in the original `invisibles` to check for tab equality
 9467                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
 9468                for (([start, end], paint), invisible) in
 9469                    invisible_iter.zip_eq(self.invisibles.iter())
 9470                {
 9471                    let should_render = match (&last_seen, invisible) {
 9472                        (_, Invisible::Tab { .. }) => true,
 9473                        (Some((_, last_end, _)), _) => *last_end == start,
 9474                        _ => false,
 9475                    };
 9476
 9477                    if should_render || start == 0 || end == self.len {
 9478                        paint(window, cx);
 9479
 9480                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
 9481                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
 9482                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
 9483                            // Note that we need to make sure that the last one is actually adjacent
 9484                            if !should_render_last && last_end == start {
 9485                                paint_last(window, cx);
 9486                            }
 9487                        }
 9488                    }
 9489
 9490                    // Manually render anything within a selection
 9491                    let invisible_point = DisplayPoint::new(row, start as u32);
 9492                    if selection_ranges.iter().any(|region| {
 9493                        region.start <= invisible_point && invisible_point < region.end
 9494                    }) {
 9495                        paint(window, cx);
 9496                    }
 9497
 9498                    last_seen = Some((should_render, end, paint));
 9499                }
 9500            }
 9501        }
 9502    }
 9503
 9504    pub fn x_for_index(&self, index: usize) -> Pixels {
 9505        let mut fragment_start_x = Pixels::ZERO;
 9506        let mut fragment_start_index = 0;
 9507
 9508        for fragment in &self.fragments {
 9509            match fragment {
 9510                LineFragment::Text(shaped_line) => {
 9511                    let fragment_end_index = fragment_start_index + shaped_line.len;
 9512                    if index < fragment_end_index {
 9513                        return fragment_start_x
 9514                            + shaped_line.x_for_index(index - fragment_start_index);
 9515                    }
 9516                    fragment_start_x += shaped_line.width;
 9517                    fragment_start_index = fragment_end_index;
 9518                }
 9519                LineFragment::Element { len, size, .. } => {
 9520                    let fragment_end_index = fragment_start_index + len;
 9521                    if index < fragment_end_index {
 9522                        return fragment_start_x;
 9523                    }
 9524                    fragment_start_x += size.width;
 9525                    fragment_start_index = fragment_end_index;
 9526                }
 9527            }
 9528        }
 9529
 9530        fragment_start_x
 9531    }
 9532
 9533    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
 9534        let mut fragment_start_x = Pixels::ZERO;
 9535        let mut fragment_start_index = 0;
 9536
 9537        for fragment in &self.fragments {
 9538            match fragment {
 9539                LineFragment::Text(shaped_line) => {
 9540                    let fragment_end_x = fragment_start_x + shaped_line.width;
 9541                    if x < fragment_end_x {
 9542                        return Some(
 9543                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
 9544                        );
 9545                    }
 9546                    fragment_start_x = fragment_end_x;
 9547                    fragment_start_index += shaped_line.len;
 9548                }
 9549                LineFragment::Element { len, size, .. } => {
 9550                    let fragment_end_x = fragment_start_x + size.width;
 9551                    if x < fragment_end_x {
 9552                        return Some(fragment_start_index);
 9553                    }
 9554                    fragment_start_index += len;
 9555                    fragment_start_x = fragment_end_x;
 9556                }
 9557            }
 9558        }
 9559
 9560        None
 9561    }
 9562
 9563    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
 9564        let mut fragment_start_index = 0;
 9565
 9566        for fragment in &self.fragments {
 9567            match fragment {
 9568                LineFragment::Text(shaped_line) => {
 9569                    let fragment_end_index = fragment_start_index + shaped_line.len;
 9570                    if index < fragment_end_index {
 9571                        return shaped_line.font_id_for_index(index - fragment_start_index);
 9572                    }
 9573                    fragment_start_index = fragment_end_index;
 9574                }
 9575                LineFragment::Element { len, .. } => {
 9576                    let fragment_end_index = fragment_start_index + len;
 9577                    if index < fragment_end_index {
 9578                        return None;
 9579                    }
 9580                    fragment_start_index = fragment_end_index;
 9581                }
 9582            }
 9583        }
 9584
 9585        None
 9586    }
 9587
 9588    pub fn alignment_offset(&self, text_align: TextAlign, content_width: Pixels) -> Pixels {
 9589        let line_width = self.width;
 9590        match text_align {
 9591            TextAlign::Left => px(0.0),
 9592            TextAlign::Center => (content_width - line_width) / 2.0,
 9593            TextAlign::Right => content_width - line_width,
 9594        }
 9595    }
 9596}
 9597
 9598#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 9599enum Invisible {
 9600    /// A tab character
 9601    ///
 9602    /// A tab character is internally represented by spaces (configured by the user's tab width)
 9603    /// aligned to the nearest column, so it's necessary to store the start and end offset for
 9604    /// adjacency checks.
 9605    Tab {
 9606        line_start_offset: usize,
 9607        line_end_offset: usize,
 9608    },
 9609    Whitespace {
 9610        line_offset: usize,
 9611    },
 9612}
 9613
 9614impl EditorElement {
 9615    /// Returns the rem size to use when rendering the [`EditorElement`].
 9616    ///
 9617    /// This allows UI elements to scale based on the `buffer_font_size`.
 9618    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
 9619        match self.editor.read(cx).mode {
 9620            EditorMode::Full {
 9621                scale_ui_elements_with_buffer_font_size: true,
 9622                ..
 9623            }
 9624            | EditorMode::Minimap { .. } => {
 9625                let buffer_font_size = self.style.text.font_size;
 9626                match buffer_font_size {
 9627                    AbsoluteLength::Pixels(pixels) => {
 9628                        let rem_size_scale = {
 9629                            // Our default UI font size is 14px on a 16px base scale.
 9630                            // This means the default UI font size is 0.875rems.
 9631                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
 9632
 9633                            // We then determine the delta between a single rem and the default font
 9634                            // size scale.
 9635                            let default_font_size_delta = 1. - default_font_size_scale;
 9636
 9637                            // Finally, we add this delta to 1rem to get the scale factor that
 9638                            // should be used to scale up the UI.
 9639                            1. + default_font_size_delta
 9640                        };
 9641
 9642                        Some(pixels * rem_size_scale)
 9643                    }
 9644                    AbsoluteLength::Rems(rems) => {
 9645                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
 9646                    }
 9647                }
 9648            }
 9649            // We currently use single-line and auto-height editors in UI contexts,
 9650            // so we don't want to scale everything with the buffer font size, as it
 9651            // ends up looking off.
 9652            _ => None,
 9653        }
 9654    }
 9655
 9656    fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
 9657        if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
 9658            parent.upgrade()
 9659        } else {
 9660            Some(self.editor.clone())
 9661        }
 9662    }
 9663}
 9664
 9665#[derive(Default)]
 9666pub struct EditorRequestLayoutState {
 9667    // We use prepaint depth to limit the number of times prepaint is
 9668    // called recursively. We need this so that we can update stale
 9669    // data for e.g. block heights in block map.
 9670    prepaint_depth: Rc<Cell<usize>>,
 9671}
 9672
 9673impl EditorRequestLayoutState {
 9674    // In ideal conditions we only need one more subsequent prepaint call for resize to take effect.
 9675    // i.e. MAX_PREPAINT_DEPTH = 2, but placing near blocks can expose more lines from below, and
 9676    // we end up querying blocks for those lines too in subsequent renders.
 9677    // Setting MAX_PREPAINT_DEPTH = 3, passes all tests. Just to be on the safe side we set it to 5, so
 9678    // that subsequent shrinking does not lead to incorrect block placing.
 9679    const MAX_PREPAINT_DEPTH: usize = 5;
 9680
 9681    fn increment_prepaint_depth(&self) -> EditorPrepaintGuard {
 9682        let depth = self.prepaint_depth.get();
 9683        self.prepaint_depth.set(depth + 1);
 9684        EditorPrepaintGuard {
 9685            prepaint_depth: self.prepaint_depth.clone(),
 9686        }
 9687    }
 9688
 9689    fn has_remaining_prepaint_depth(&self) -> bool {
 9690        self.prepaint_depth.get() < Self::MAX_PREPAINT_DEPTH
 9691    }
 9692}
 9693
 9694struct EditorPrepaintGuard {
 9695    prepaint_depth: Rc<Cell<usize>>,
 9696}
 9697
 9698impl Drop for EditorPrepaintGuard {
 9699    fn drop(&mut self) {
 9700        let depth = self.prepaint_depth.get();
 9701        self.prepaint_depth.set(depth.saturating_sub(1));
 9702    }
 9703}
 9704
 9705impl Element for EditorElement {
 9706    type RequestLayoutState = EditorRequestLayoutState;
 9707    type PrepaintState = EditorLayout;
 9708
 9709    fn id(&self) -> Option<ElementId> {
 9710        None
 9711    }
 9712
 9713    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
 9714        None
 9715    }
 9716
 9717    fn request_layout(
 9718        &mut self,
 9719        _: Option<&GlobalElementId>,
 9720        _inspector_id: Option<&gpui::InspectorElementId>,
 9721        window: &mut Window,
 9722        cx: &mut App,
 9723    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
 9724        let rem_size = self.rem_size(cx);
 9725        window.with_rem_size(rem_size, |window| {
 9726            self.editor.update(cx, |editor, cx| {
 9727                editor.set_style(self.style.clone(), window, cx);
 9728
 9729                let layout_id = match editor.mode {
 9730                    EditorMode::SingleLine => {
 9731                        let rem_size = window.rem_size();
 9732                        let height = self.style.text.line_height_in_pixels(rem_size);
 9733                        let mut style = Style::default();
 9734                        style.size.height = height.into();
 9735                        style.size.width = relative(1.).into();
 9736                        window.request_layout(style, None, cx)
 9737                    }
 9738                    EditorMode::AutoHeight {
 9739                        min_lines,
 9740                        max_lines,
 9741                    } => {
 9742                        let editor_handle = cx.entity();
 9743                        window.request_measured_layout(
 9744                            Style::default(),
 9745                            move |known_dimensions, available_space, window, cx| {
 9746                                editor_handle
 9747                                    .update(cx, |editor, cx| {
 9748                                        compute_auto_height_layout(
 9749                                            editor,
 9750                                            min_lines,
 9751                                            max_lines,
 9752                                            known_dimensions,
 9753                                            available_space.width,
 9754                                            window,
 9755                                            cx,
 9756                                        )
 9757                                    })
 9758                                    .unwrap_or_default()
 9759                            },
 9760                        )
 9761                    }
 9762                    EditorMode::Minimap { .. } => {
 9763                        let mut style = Style::default();
 9764                        style.size.width = relative(1.).into();
 9765                        style.size.height = relative(1.).into();
 9766                        window.request_layout(style, None, cx)
 9767                    }
 9768                    EditorMode::Full {
 9769                        sizing_behavior, ..
 9770                    } => {
 9771                        let mut style = Style::default();
 9772                        style.size.width = relative(1.).into();
 9773                        if sizing_behavior == SizingBehavior::SizeByContent {
 9774                            let snapshot = editor.snapshot(window, cx);
 9775                            let line_height =
 9776                                self.style.text.line_height_in_pixels(window.rem_size());
 9777                            let scroll_height =
 9778                                (snapshot.max_point().row().next_row().0 as f32) * line_height;
 9779                            style.size.height = scroll_height.into();
 9780                        } else {
 9781                            style.size.height = relative(1.).into();
 9782                        }
 9783                        window.request_layout(style, None, cx)
 9784                    }
 9785                };
 9786
 9787                (layout_id, EditorRequestLayoutState::default())
 9788            })
 9789        })
 9790    }
 9791
 9792    fn prepaint(
 9793        &mut self,
 9794        _: Option<&GlobalElementId>,
 9795        _inspector_id: Option<&gpui::InspectorElementId>,
 9796        bounds: Bounds<Pixels>,
 9797        request_layout: &mut Self::RequestLayoutState,
 9798        window: &mut Window,
 9799        cx: &mut App,
 9800    ) -> Self::PrepaintState {
 9801        let _prepaint_depth_guard = request_layout.increment_prepaint_depth();
 9802        let text_style = TextStyleRefinement {
 9803            font_size: Some(self.style.text.font_size),
 9804            line_height: Some(self.style.text.line_height),
 9805            ..Default::default()
 9806        };
 9807
 9808        let is_minimap = self.editor.read(cx).mode.is_minimap();
 9809        let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
 9810
 9811        if !is_minimap {
 9812            let focus_handle = self.editor.focus_handle(cx);
 9813            window.set_view_id(self.editor.entity_id());
 9814            window.set_focus_handle(&focus_handle, cx);
 9815        }
 9816
 9817        let rem_size = self.rem_size(cx);
 9818        window.with_rem_size(rem_size, |window| {
 9819            window.with_text_style(Some(text_style), |window| {
 9820                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 9821                    let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
 9822                        (editor.snapshot(window, cx), editor.read_only(cx))
 9823                    });
 9824                    let style = &self.style;
 9825
 9826                    let rem_size = window.rem_size();
 9827                    let font_id = window.text_system().resolve_font(&style.text.font());
 9828                    let font_size = style.text.font_size.to_pixels(rem_size);
 9829                    let line_height = style.text.line_height_in_pixels(rem_size);
 9830                    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
 9831                    let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
 9832                    let em_layout_width = window.text_system().em_layout_width(font_id, font_size);
 9833                    let glyph_grid_cell = size(em_advance, line_height);
 9834
 9835                    let gutter_dimensions =
 9836                        snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
 9837                    let text_width = bounds.size.width - gutter_dimensions.width;
 9838
 9839                    let settings = EditorSettings::get_global(cx);
 9840                    let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
 9841                    let vertical_scrollbar_width = (scrollbars_shown
 9842                        && settings.scrollbar.axes.vertical
 9843                        && self.editor.read(cx).show_scrollbars.vertical)
 9844                        .then_some(style.scrollbar_width)
 9845                        .unwrap_or_default();
 9846                    let minimap_width = self
 9847                        .get_minimap_width(
 9848                            &settings.minimap,
 9849                            scrollbars_shown,
 9850                            text_width,
 9851                            em_width,
 9852                            font_size,
 9853                            rem_size,
 9854                            cx,
 9855                        )
 9856                        .unwrap_or_default();
 9857
 9858                    let right_margin = minimap_width + vertical_scrollbar_width;
 9859
 9860                    let extended_right = 2 * em_width + right_margin;
 9861                    let editor_width = text_width - gutter_dimensions.margin - extended_right;
 9862                    let editor_margins = EditorMargins {
 9863                        gutter: gutter_dimensions,
 9864                        right: right_margin,
 9865                        extended_right,
 9866                    };
 9867
 9868                    snapshot = self.editor.update(cx, |editor, cx| {
 9869                        editor.last_bounds = Some(bounds);
 9870                        editor.gutter_dimensions = gutter_dimensions;
 9871                        editor.set_visible_line_count(
 9872                            (bounds.size.height / line_height) as f64,
 9873                            window,
 9874                            cx,
 9875                        );
 9876                        editor.set_visible_column_count(f64::from(editor_width / em_advance));
 9877
 9878                        if matches!(
 9879                            editor.mode,
 9880                            EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
 9881                        ) {
 9882                            snapshot
 9883                        } else {
 9884                            let wrap_width = calculate_wrap_width(
 9885                                editor.soft_wrap_mode(cx),
 9886                                editor_width,
 9887                                em_layout_width,
 9888                            );
 9889
 9890                            if editor.set_wrap_width(wrap_width, cx) {
 9891                                editor.snapshot(window, cx)
 9892                            } else {
 9893                                snapshot
 9894                            }
 9895                        }
 9896                    });
 9897
 9898                    let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
 9899                    let gutter_hitbox = window.insert_hitbox(
 9900                        gutter_bounds(bounds, gutter_dimensions),
 9901                        HitboxBehavior::Normal,
 9902                    );
 9903                    let text_hitbox = window.insert_hitbox(
 9904                        Bounds {
 9905                            origin: gutter_hitbox.top_right(),
 9906                            size: size(text_width, bounds.size.height),
 9907                        },
 9908                        HitboxBehavior::Normal,
 9909                    );
 9910
 9911                    // Offset the content_bounds from the text_bounds by the gutter margin (which
 9912                    // is roughly half a character wide) to make hit testing work more like how we want.
 9913                    let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
 9914                    let content_origin = text_hitbox.origin + content_offset;
 9915
 9916                    let height_in_lines = f64::from(bounds.size.height / line_height);
 9917                    let max_row = snapshot.max_point().row().as_f64();
 9918
 9919                    // Calculate how much of the editor is clipped by parent containers (e.g., List).
 9920                    // This allows us to only render lines that are actually visible, which is
 9921                    // critical for performance when large AutoHeight editors are inside Lists.
 9922                    let visible_bounds = window.content_mask().bounds;
 9923                    let clipped_top = (visible_bounds.origin.y - bounds.origin.y).max(px(0.));
 9924                    let clipped_top_in_lines = f64::from(clipped_top / line_height);
 9925                    let visible_height_in_lines =
 9926                        f64::from(visible_bounds.size.height / line_height);
 9927
 9928                    // The max scroll position for the top of the window
 9929                    let scroll_beyond_last_line = self.editor.read(cx).scroll_beyond_last_line(cx);
 9930                    let max_scroll_top = match scroll_beyond_last_line {
 9931                        ScrollBeyondLastLine::OnePage => max_row,
 9932                        ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
 9933                        ScrollBeyondLastLine::VerticalScrollMargin => {
 9934                            let settings = EditorSettings::get_global(cx);
 9935                            (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
 9936                                .max(0.)
 9937                        }
 9938                    };
 9939
 9940                    let (
 9941                        autoscroll_request,
 9942                        autoscroll_containing_element,
 9943                        needs_horizontal_autoscroll,
 9944                    ) = self.editor.update(cx, |editor, cx| {
 9945                        let autoscroll_request = editor.scroll_manager.take_autoscroll_request();
 9946
 9947                        let autoscroll_containing_element =
 9948                            autoscroll_request.is_some() || editor.has_pending_selection();
 9949
 9950                        let (needs_horizontal_autoscroll, was_scrolled) = editor
 9951                            .autoscroll_vertically(
 9952                                bounds,
 9953                                line_height,
 9954                                max_scroll_top,
 9955                                autoscroll_request,
 9956                                window,
 9957                                cx,
 9958                            );
 9959                        if was_scrolled.0 {
 9960                            snapshot = editor.snapshot(window, cx);
 9961                        }
 9962                        (
 9963                            autoscroll_request,
 9964                            autoscroll_containing_element,
 9965                            needs_horizontal_autoscroll,
 9966                        )
 9967                    });
 9968
 9969                    let mut scroll_position = snapshot.scroll_position();
 9970                    // The scroll position is a fractional point, the whole number of which represents
 9971                    // the top of the window in terms of display rows.
 9972                    // We add clipped_top_in_lines to skip rows that are clipped by parent containers,
 9973                    // but we don't modify scroll_position itself since the parent handles positioning.
 9974                    let max_row = snapshot.max_point().row();
 9975                    let start_row = cmp::min(
 9976                        DisplayRow((scroll_position.y + clipped_top_in_lines).floor() as u32),
 9977                        max_row,
 9978                    );
 9979                    let end_row = cmp::min(
 9980                        (scroll_position.y + clipped_top_in_lines + visible_height_in_lines).ceil()
 9981                            as u32,
 9982                        max_row.next_row().0,
 9983                    );
 9984                    let end_row = DisplayRow(end_row);
 9985
 9986                    let row_infos = snapshot // note we only get the visual range
 9987                        .row_infos(start_row)
 9988                        .take((start_row..end_row).len())
 9989                        .collect::<Vec<RowInfo>>();
 9990                    let is_row_soft_wrapped = |row: usize| {
 9991                        row_infos
 9992                            .get(row)
 9993                            .is_none_or(|info| info.buffer_row.is_none())
 9994                    };
 9995
 9996                    let start_anchor = if start_row == Default::default() {
 9997                        Anchor::Min
 9998                    } else {
 9999                        snapshot.buffer_snapshot().anchor_before(
10000                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
10001                        )
10002                    };
10003                    let end_anchor = if end_row > max_row {
10004                        Anchor::Max
10005                    } else {
10006                        snapshot.buffer_snapshot().anchor_before(
10007                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
10008                        )
10009                    };
10010
10011                    let mut highlighted_rows = self
10012                        .editor
10013                        .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
10014
10015                    let is_light = cx.theme().appearance().is_light();
10016
10017                    let mut highlighted_ranges = self
10018                        .editor_with_selections(cx)
10019                        .map(|editor| {
10020                            if editor == self.editor {
10021                                editor.read(cx).background_highlights_in_range(
10022                                    start_anchor..end_anchor,
10023                                    &snapshot.display_snapshot,
10024                                    cx.theme(),
10025                                )
10026                            } else {
10027                                editor.update(cx, |editor, cx| {
10028                                    let snapshot = editor.snapshot(window, cx);
10029                                    let start_anchor = if start_row == Default::default() {
10030                                        Anchor::Min
10031                                    } else {
10032                                        snapshot.buffer_snapshot().anchor_before(
10033                                            DisplayPoint::new(start_row, 0)
10034                                                .to_offset(&snapshot, Bias::Left),
10035                                        )
10036                                    };
10037                                    let end_anchor = if end_row > max_row {
10038                                        Anchor::Max
10039                                    } else {
10040                                        snapshot.buffer_snapshot().anchor_before(
10041                                            DisplayPoint::new(end_row, 0)
10042                                                .to_offset(&snapshot, Bias::Right),
10043                                        )
10044                                    };
10045
10046                                    editor.background_highlights_in_range(
10047                                        start_anchor..end_anchor,
10048                                        &snapshot.display_snapshot,
10049                                        cx.theme(),
10050                                    )
10051                                })
10052                            }
10053                        })
10054                        .unwrap_or_default();
10055
10056                    for (ix, row_info) in row_infos.iter().enumerate() {
10057                        let Some(diff_status) = row_info.diff_status else {
10058                            continue;
10059                        };
10060
10061                        let background_color = match diff_status.kind {
10062                            DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
10063                            DiffHunkStatusKind::Deleted => {
10064                                cx.theme().colors().version_control_deleted
10065                            }
10066                            DiffHunkStatusKind::Modified => {
10067                                debug_panic!("modified diff status for row info");
10068                                continue;
10069                            }
10070                        };
10071
10072                        let hunk_opacity = if is_light { 0.16 } else { 0.12 };
10073
10074                        let hollow_highlight = LineHighlight {
10075                            background: (background_color.opacity(if is_light {
10076                                0.08
10077                            } else {
10078                                0.06
10079                            }))
10080                            .into(),
10081                            border: Some(if is_light {
10082                                background_color.opacity(0.48)
10083                            } else {
10084                                background_color.opacity(0.36)
10085                            }),
10086                            include_gutter: true,
10087                            type_id: None,
10088                        };
10089
10090                        let filled_highlight = LineHighlight {
10091                            background: solid_background(background_color.opacity(hunk_opacity)),
10092                            border: None,
10093                            include_gutter: true,
10094                            type_id: None,
10095                        };
10096
10097                        let background = if Self::diff_hunk_hollow(diff_status, cx) {
10098                            hollow_highlight
10099                        } else {
10100                            filled_highlight
10101                        };
10102
10103                        let base_display_point =
10104                            DisplayPoint::new(start_row + DisplayRow(ix as u32), 0);
10105
10106                        highlighted_rows
10107                            .entry(base_display_point.row())
10108                            .or_insert(background);
10109                    }
10110
10111                    // Add diff review drag selection highlight to text area
10112                    if let Some(drag_state) = &self.editor.read(cx).diff_review_drag_state {
10113                        let range = drag_state.row_range(&snapshot.display_snapshot);
10114                        let start_row = range.start().0;
10115                        let end_row = range.end().0;
10116                        let drag_highlight_color =
10117                            cx.theme().colors().editor_active_line_background;
10118                        let drag_highlight = LineHighlight {
10119                            background: solid_background(drag_highlight_color),
10120                            border: Some(cx.theme().colors().border_focused),
10121                            include_gutter: true,
10122                            type_id: None,
10123                        };
10124                        for row_num in start_row..=end_row {
10125                            highlighted_rows
10126                                .entry(DisplayRow(row_num))
10127                                .or_insert(drag_highlight);
10128                        }
10129                    }
10130
10131                    let highlighted_gutter_ranges =
10132                        self.editor.read(cx).gutter_highlights_in_range(
10133                            start_anchor..end_anchor,
10134                            &snapshot.display_snapshot,
10135                            cx,
10136                        );
10137
10138                    let document_colors = self
10139                        .editor
10140                        .read(cx)
10141                        .colors
10142                        .as_ref()
10143                        .map(|colors| colors.editor_display_highlights(&snapshot));
10144                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
10145                        start_anchor..end_anchor,
10146                        &snapshot.display_snapshot,
10147                        cx,
10148                    );
10149
10150                    let (local_selections, selected_buffer_ids, latest_selection_anchors): (
10151                        Vec<Selection<Point>>,
10152                        Vec<BufferId>,
10153                        HashMap<BufferId, Anchor>,
10154                    ) = self
10155                        .editor_with_selections(cx)
10156                        .map(|editor| {
10157                            editor.update(cx, |editor, cx| {
10158                                let all_selections =
10159                                    editor.selections.all::<Point>(&snapshot.display_snapshot);
10160                                let all_anchor_selections =
10161                                    editor.selections.all_anchors(&snapshot.display_snapshot);
10162                                let selected_buffer_ids =
10163                                    if editor.buffer_kind(cx) == ItemBufferKind::Singleton {
10164                                        Vec::new()
10165                                    } else {
10166                                        let mut selected_buffer_ids =
10167                                            Vec::with_capacity(all_selections.len());
10168
10169                                        for selection in all_selections {
10170                                            for buffer_id in snapshot
10171                                                .buffer_snapshot()
10172                                                .buffer_ids_for_range(selection.range())
10173                                            {
10174                                                if selected_buffer_ids.last() != Some(&buffer_id) {
10175                                                    selected_buffer_ids.push(buffer_id);
10176                                                }
10177                                            }
10178                                        }
10179
10180                                        selected_buffer_ids
10181                                    };
10182
10183                                let mut selections = editor.selections.disjoint_in_range(
10184                                    start_anchor..end_anchor,
10185                                    &snapshot.display_snapshot,
10186                                );
10187                                selections
10188                                    .extend(editor.selections.pending(&snapshot.display_snapshot));
10189
10190                                let mut anchors_by_buffer: HashMap<BufferId, (usize, Anchor)> =
10191                                    HashMap::default();
10192                                for selection in all_anchor_selections.iter() {
10193                                    let head = selection.head();
10194                                    if let Some((text_anchor, _)) =
10195                                        snapshot.buffer_snapshot().anchor_to_buffer_anchor(head)
10196                                    {
10197                                        anchors_by_buffer
10198                                            .entry(text_anchor.buffer_id)
10199                                            .and_modify(|(latest_id, latest_anchor)| {
10200                                                if selection.id > *latest_id {
10201                                                    *latest_id = selection.id;
10202                                                    *latest_anchor = head;
10203                                                }
10204                                            })
10205                                            .or_insert((selection.id, head));
10206                                    }
10207                                }
10208                                let latest_selection_anchors = anchors_by_buffer
10209                                    .into_iter()
10210                                    .map(|(buffer_id, (_, anchor))| (buffer_id, anchor))
10211                                    .collect();
10212
10213                                (selections, selected_buffer_ids, latest_selection_anchors)
10214                            })
10215                        })
10216                        .unwrap_or_else(|| (Vec::new(), Vec::new(), HashMap::default()));
10217
10218                    let (selections, mut active_rows, newest_selection_head) = self
10219                        .layout_selections(
10220                            start_anchor,
10221                            end_anchor,
10222                            &local_selections,
10223                            &snapshot,
10224                            start_row,
10225                            end_row,
10226                            window,
10227                            cx,
10228                        );
10229
10230                    // relative rows are based on newest selection, even outside the visible area
10231                    let current_selection_head = self.editor.update(cx, |editor, cx| {
10232                        (editor.selections.count() != 0).then(|| {
10233                            let newest = editor
10234                                .selections
10235                                .newest::<Point>(&editor.display_snapshot(cx));
10236
10237                            SelectionLayout::new(
10238                                newest,
10239                                editor.selections.line_mode(),
10240                                editor.cursor_offset_on_selection,
10241                                editor.cursor_shape,
10242                                &snapshot,
10243                                true,
10244                                true,
10245                                None,
10246                            )
10247                            .head
10248                            .row()
10249                        })
10250                    });
10251
10252                    let run_indicator_rows = self.editor.update(cx, |editor, cx| {
10253                        editor.active_run_indicators(start_row..end_row, window, cx)
10254                    });
10255
10256                    let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
10257                        editor.active_breakpoints(start_row..end_row, window, cx)
10258                    });
10259
10260                    for (display_row, (_, bp, state)) in &breakpoint_rows {
10261                        if bp.is_enabled() && state.is_none_or(|s| s.verified) {
10262                            active_rows.entry(*display_row).or_default().breakpoint = true;
10263                        }
10264                    }
10265
10266                    let gutter = Gutter {
10267                        line_height,
10268                        range: start_row..end_row,
10269                        scroll_position,
10270                        dimensions: &gutter_dimensions,
10271                        hitbox: &gutter_hitbox,
10272                        snapshot: &snapshot,
10273                        row_infos: &row_infos,
10274                    };
10275
10276                    let line_numbers = self.layout_line_numbers(
10277                        &gutter,
10278                        &active_rows,
10279                        current_selection_head,
10280                        window,
10281                        cx,
10282                    );
10283
10284                    let mut expand_toggles =
10285                        window.with_element_namespace("expand_toggles", |window| {
10286                            self.layout_expand_toggles(
10287                                &gutter_hitbox,
10288                                gutter_dimensions,
10289                                em_width,
10290                                line_height,
10291                                scroll_position,
10292                                &row_infos,
10293                                window,
10294                                cx,
10295                            )
10296                        });
10297
10298                    let mut crease_toggles =
10299                        window.with_element_namespace("crease_toggles", |window| {
10300                            self.layout_crease_toggles(
10301                                start_row..end_row,
10302                                &row_infos,
10303                                &active_rows,
10304                                &snapshot,
10305                                window,
10306                                cx,
10307                            )
10308                        });
10309                    let crease_trailers =
10310                        window.with_element_namespace("crease_trailers", |window| {
10311                            self.layout_crease_trailers(
10312                                row_infos.iter().cloned(),
10313                                &snapshot,
10314                                window,
10315                                cx,
10316                            )
10317                        });
10318
10319                    let display_hunks = self.layout_gutter_diff_hunks(
10320                        line_height,
10321                        &gutter_hitbox,
10322                        start_row..end_row,
10323                        &snapshot,
10324                        window,
10325                        cx,
10326                    );
10327
10328                    Self::layout_word_diff_highlights(
10329                        &display_hunks,
10330                        &row_infos,
10331                        start_row,
10332                        &snapshot,
10333                        &mut highlighted_ranges,
10334                        cx,
10335                    );
10336
10337                    let merged_highlighted_ranges =
10338                        if let Some((_, colors)) = document_colors.as_ref() {
10339                            &highlighted_ranges
10340                                .clone()
10341                                .into_iter()
10342                                .chain(colors.clone())
10343                                .collect()
10344                        } else {
10345                            &highlighted_ranges
10346                        };
10347                    let bg_segments_per_row = Self::bg_segments_per_row(
10348                        start_row..end_row,
10349                        &selections,
10350                        &merged_highlighted_ranges,
10351                        self.style.background,
10352                    );
10353
10354                    let mut line_layouts = Self::layout_lines(
10355                        start_row..end_row,
10356                        &snapshot,
10357                        &self.style,
10358                        editor_width,
10359                        is_row_soft_wrapped,
10360                        &bg_segments_per_row,
10361                        window,
10362                        cx,
10363                    );
10364                    let new_renderer_widths = (!is_minimap).then(|| {
10365                        line_layouts
10366                            .iter()
10367                            .flat_map(|layout| &layout.fragments)
10368                            .filter_map(|fragment| {
10369                                if let LineFragment::Element { id, size, .. } = fragment {
10370                                    Some((*id, size.width))
10371                                } else {
10372                                    None
10373                                }
10374                            })
10375                    });
10376                    let renderer_widths_changed = request_layout.has_remaining_prepaint_depth()
10377                        && new_renderer_widths.is_some_and(|new_renderer_widths| {
10378                            self.editor.update(cx, |editor, cx| {
10379                                editor.update_renderer_widths(new_renderer_widths, cx)
10380                            })
10381                        });
10382                    if renderer_widths_changed {
10383                        return self.prepaint(
10384                            None,
10385                            _inspector_id,
10386                            bounds,
10387                            request_layout,
10388                            window,
10389                            cx,
10390                        );
10391                    }
10392
10393                    let longest_line_blame_width = self
10394                        .editor
10395                        .update(cx, |editor, cx| {
10396                            if !editor.show_git_blame_inline {
10397                                return None;
10398                            }
10399                            let blame = editor.blame.as_ref()?;
10400                            let (_, blame_entry) = blame
10401                                .update(cx, |blame, cx| {
10402                                    let row_infos =
10403                                        snapshot.row_infos(snapshot.longest_row()).next()?;
10404                                    blame.blame_for_rows(&[row_infos], cx).next()
10405                                })
10406                                .flatten()?;
10407                            let mut element = render_inline_blame_entry(blame_entry, style, cx)?;
10408                            let inline_blame_padding =
10409                                ProjectSettings::get_global(cx).git.inline_blame.padding as f32
10410                                    * em_advance;
10411                            Some(
10412                                element
10413                                    .layout_as_root(AvailableSpace::min_size(), window, cx)
10414                                    .width
10415                                    + inline_blame_padding,
10416                            )
10417                        })
10418                        .unwrap_or(Pixels::ZERO);
10419
10420                    let longest_line_width = layout_line(
10421                        snapshot.longest_row(),
10422                        &snapshot,
10423                        style,
10424                        editor_width,
10425                        is_row_soft_wrapped,
10426                        window,
10427                        cx,
10428                    )
10429                    .width;
10430
10431                    let scrollbar_layout_information = ScrollbarLayoutInformation::new(
10432                        text_hitbox.bounds,
10433                        glyph_grid_cell,
10434                        size(
10435                            longest_line_width,
10436                            Pixels::from(max_row.as_f64() * f64::from(line_height)),
10437                        ),
10438                        longest_line_blame_width,
10439                        EditorSettings::get_global(cx),
10440                        scroll_beyond_last_line,
10441                    );
10442
10443                    let mut scroll_width = scrollbar_layout_information.scroll_range.width;
10444
10445                    let sticky_header_excerpt = if snapshot.buffer_snapshot().show_headers() {
10446                        snapshot.sticky_header_excerpt(scroll_position.y)
10447                    } else {
10448                        None
10449                    };
10450                    let sticky_header_excerpt_id = sticky_header_excerpt
10451                        .as_ref()
10452                        .map(|top| top.excerpt.buffer_id());
10453
10454                    let buffer = snapshot.buffer_snapshot();
10455                    let start_buffer_row = MultiBufferRow(start_anchor.to_point(&buffer).row);
10456                    let end_buffer_row = MultiBufferRow(end_anchor.to_point(&buffer).row);
10457
10458                    let preliminary_scroll_pixel_position = point(
10459                        scroll_position.x * f64::from(em_layout_width),
10460                        scroll_position.y * f64::from(line_height),
10461                    );
10462                    let indent_guides = self.layout_indent_guides(
10463                        content_origin,
10464                        text_hitbox.origin,
10465                        start_buffer_row..end_buffer_row,
10466                        preliminary_scroll_pixel_position,
10467                        line_height,
10468                        &snapshot,
10469                        window,
10470                        cx,
10471                    );
10472                    let indent_guides_for_spacers = indent_guides.clone();
10473
10474                    let blocks = (!is_minimap)
10475                        .then(|| {
10476                            window.with_element_namespace("blocks", |window| {
10477                                self.render_blocks(
10478                                    start_row..end_row,
10479                                    &snapshot,
10480                                    &hitbox,
10481                                    &text_hitbox,
10482                                    editor_width,
10483                                    &mut scroll_width,
10484                                    &editor_margins,
10485                                    em_width,
10486                                    gutter_dimensions.full_width(),
10487                                    line_height,
10488                                    &mut line_layouts,
10489                                    &local_selections,
10490                                    &selected_buffer_ids,
10491                                    &latest_selection_anchors,
10492                                    is_row_soft_wrapped,
10493                                    sticky_header_excerpt_id,
10494                                    &indent_guides_for_spacers,
10495                                    window,
10496                                    cx,
10497                                )
10498                            })
10499                        })
10500                        .unwrap_or_default();
10501                    let RenderBlocksOutput {
10502                        non_spacer_blocks: mut blocks,
10503                        mut spacer_blocks,
10504                        row_block_types,
10505                        resized_blocks,
10506                    } = blocks;
10507                    if let Some(resized_blocks) = resized_blocks {
10508                        if request_layout.has_remaining_prepaint_depth() {
10509                            self.editor.update(cx, |editor, cx| {
10510                                editor.resize_blocks(
10511                                    resized_blocks,
10512                                    autoscroll_request.map(|(autoscroll, _)| autoscroll),
10513                                    cx,
10514                                )
10515                            });
10516                            return self.prepaint(
10517                                None,
10518                                _inspector_id,
10519                                bounds,
10520                                request_layout,
10521                                window,
10522                                cx,
10523                            );
10524                        } else {
10525                            debug_panic!(
10526                                "dropping block resize because prepaint depth \
10527                                 limit was reached"
10528                            );
10529                        }
10530                    }
10531
10532                    let sticky_buffer_header = if self.should_show_buffer_headers() {
10533                        sticky_header_excerpt.map(|sticky_header_excerpt| {
10534                            window.with_element_namespace("blocks", |window| {
10535                                self.layout_sticky_buffer_header(
10536                                    sticky_header_excerpt,
10537                                    scroll_position,
10538                                    line_height,
10539                                    right_margin,
10540                                    &snapshot,
10541                                    &hitbox,
10542                                    &selected_buffer_ids,
10543                                    &blocks,
10544                                    &latest_selection_anchors,
10545                                    window,
10546                                    cx,
10547                                )
10548                            })
10549                        })
10550                    } else {
10551                        None
10552                    };
10553
10554                    let scroll_max: gpui::Point<ScrollPixelOffset> = point(
10555                        ScrollPixelOffset::from(
10556                            ((scroll_width - editor_width) / em_layout_width).max(0.0),
10557                        ),
10558                        max_scroll_top,
10559                    );
10560
10561                    self.editor.update(cx, |editor, cx| {
10562                        if editor.scroll_manager.clamp_scroll_left(scroll_max.x, cx) {
10563                            scroll_position.x = scroll_max.x.min(scroll_position.x);
10564                        }
10565
10566                        if needs_horizontal_autoscroll.0
10567                            && let Some(new_scroll_position) = editor.autoscroll_horizontally(
10568                                start_row,
10569                                editor_width,
10570                                scroll_width,
10571                                em_advance,
10572                                &line_layouts,
10573                                autoscroll_request,
10574                                window,
10575                                cx,
10576                            )
10577                        {
10578                            scroll_position = new_scroll_position;
10579                        }
10580                    });
10581
10582                    let scroll_pixel_position = point(
10583                        scroll_position.x * f64::from(em_layout_width),
10584                        scroll_position.y * f64::from(line_height),
10585                    );
10586                    let sticky_headers = if !is_minimap
10587                        && is_singleton
10588                        && EditorSettings::get_global(cx).sticky_scroll.enabled
10589                    {
10590                        let relative = self.editor.read(cx).relative_line_numbers(cx);
10591                        self.layout_sticky_headers(
10592                            &snapshot,
10593                            editor_width,
10594                            is_row_soft_wrapped,
10595                            line_height,
10596                            scroll_pixel_position,
10597                            content_origin,
10598                            &gutter_dimensions,
10599                            &gutter_hitbox,
10600                            &text_hitbox,
10601                            relative,
10602                            current_selection_head,
10603                            window,
10604                            cx,
10605                        )
10606                    } else {
10607                        None
10608                    };
10609                    let indent_guides =
10610                        if scroll_pixel_position != preliminary_scroll_pixel_position {
10611                            self.layout_indent_guides(
10612                                content_origin,
10613                                text_hitbox.origin,
10614                                start_buffer_row..end_buffer_row,
10615                                scroll_pixel_position,
10616                                line_height,
10617                                &snapshot,
10618                                window,
10619                                cx,
10620                            )
10621                        } else {
10622                            indent_guides
10623                        };
10624
10625                    let crease_trailers =
10626                        window.with_element_namespace("crease_trailers", |window| {
10627                            self.prepaint_crease_trailers(
10628                                crease_trailers,
10629                                &line_layouts,
10630                                line_height,
10631                                content_origin,
10632                                scroll_pixel_position,
10633                                em_width,
10634                                window,
10635                                cx,
10636                            )
10637                        });
10638
10639                    let (edit_prediction_popover, edit_prediction_popover_origin) = self
10640                        .editor
10641                        .update(cx, |editor, cx| {
10642                            editor.render_edit_prediction_popover(
10643                                &text_hitbox.bounds,
10644                                content_origin,
10645                                right_margin,
10646                                &snapshot,
10647                                start_row..end_row,
10648                                scroll_position.y,
10649                                scroll_position.y + height_in_lines,
10650                                &line_layouts,
10651                                line_height,
10652                                scroll_position,
10653                                scroll_pixel_position,
10654                                newest_selection_head,
10655                                editor_width,
10656                                style,
10657                                window,
10658                                cx,
10659                            )
10660                        })
10661                        .unzip();
10662
10663                    let mut inline_diagnostics = self.layout_inline_diagnostics(
10664                        &line_layouts,
10665                        &crease_trailers,
10666                        &row_block_types,
10667                        content_origin,
10668                        scroll_position,
10669                        scroll_pixel_position,
10670                        edit_prediction_popover_origin,
10671                        start_row,
10672                        end_row,
10673                        line_height,
10674                        em_width,
10675                        style,
10676                        window,
10677                        cx,
10678                    );
10679
10680                    let mut inline_blame_layout = None;
10681                    let mut inline_code_actions = None;
10682                    if let Some(newest_selection_head) = newest_selection_head {
10683                        let display_row = newest_selection_head.row();
10684                        if (start_row..end_row).contains(&display_row)
10685                            && !row_block_types.contains_key(&display_row)
10686                        {
10687                            inline_code_actions = self.layout_inline_code_actions(
10688                                newest_selection_head,
10689                                content_origin,
10690                                scroll_position,
10691                                scroll_pixel_position,
10692                                line_height,
10693                                &snapshot,
10694                                window,
10695                                cx,
10696                            );
10697
10698                            let line_ix = display_row.minus(start_row) as usize;
10699                            if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
10700                                row_infos.get(line_ix),
10701                                line_layouts.get(line_ix),
10702                                crease_trailers.get(line_ix),
10703                            ) {
10704                                let crease_trailer_layout = crease_trailer.as_ref();
10705                                if let Some(layout) = self.layout_inline_blame(
10706                                    display_row,
10707                                    row_info,
10708                                    line_layout,
10709                                    crease_trailer_layout,
10710                                    em_width,
10711                                    content_origin,
10712                                    scroll_position,
10713                                    scroll_pixel_position,
10714                                    line_height,
10715                                    window,
10716                                    cx,
10717                                ) {
10718                                    inline_blame_layout = Some(layout);
10719                                    // Blame overrides inline diagnostics
10720                                    inline_diagnostics.remove(&display_row);
10721                                }
10722                            } else {
10723                                log::error!(
10724                                    "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
10725                                    line_layouts.len(): {}, \
10726                                    crease_trailers.len(): {}",
10727                                    line_ix,
10728                                    row_infos.len(),
10729                                    line_layouts.len(),
10730                                    crease_trailers.len(),
10731                                );
10732                            }
10733                        }
10734                    }
10735
10736                    let blamed_display_rows = self.layout_blame_entries(
10737                        &row_infos,
10738                        em_width,
10739                        scroll_position,
10740                        line_height,
10741                        &gutter_hitbox,
10742                        gutter_dimensions.git_blame_entries_width,
10743                        window,
10744                        cx,
10745                    );
10746
10747                    let line_elements = self.prepaint_lines(
10748                        start_row,
10749                        &mut line_layouts,
10750                        line_height,
10751                        scroll_position,
10752                        scroll_pixel_position,
10753                        content_origin,
10754                        window,
10755                        cx,
10756                    );
10757
10758                    window.with_element_namespace("blocks", |window| {
10759                        self.layout_blocks(
10760                            &mut blocks,
10761                            &hitbox,
10762                            &gutter_hitbox,
10763                            line_height,
10764                            scroll_position,
10765                            scroll_pixel_position,
10766                            &editor_margins,
10767                            window,
10768                            cx,
10769                        );
10770                        self.layout_blocks(
10771                            &mut spacer_blocks,
10772                            &hitbox,
10773                            &gutter_hitbox,
10774                            line_height,
10775                            scroll_position,
10776                            scroll_pixel_position,
10777                            &editor_margins,
10778                            window,
10779                            cx,
10780                        );
10781                    });
10782
10783                    let cursors = self.collect_cursors(&snapshot, cx);
10784                    let visible_row_range = start_row..end_row;
10785                    let non_visible_cursors = cursors
10786                        .iter()
10787                        .any(|c| !visible_row_range.contains(&c.0.row()));
10788
10789                    let visible_cursors = self.layout_visible_cursors(
10790                        &snapshot,
10791                        &selections,
10792                        &row_block_types,
10793                        start_row..end_row,
10794                        &line_layouts,
10795                        &text_hitbox,
10796                        content_origin,
10797                        scroll_position,
10798                        scroll_pixel_position,
10799                        line_height,
10800                        em_width,
10801                        em_advance,
10802                        autoscroll_containing_element,
10803                        &redacted_ranges,
10804                        window,
10805                        cx,
10806                    );
10807                    let navigation_overlay_paint_commands = self.layout_navigation_overlays(
10808                        &snapshot,
10809                        start_row..end_row,
10810                        &line_layouts,
10811                        &text_hitbox,
10812                        content_origin,
10813                        scroll_position,
10814                        scroll_pixel_position,
10815                        line_height,
10816                        window,
10817                        cx,
10818                    );
10819
10820                    let scrollbars_layout = self.layout_scrollbars(
10821                        &snapshot,
10822                        &scrollbar_layout_information,
10823                        content_offset,
10824                        scroll_position,
10825                        non_visible_cursors,
10826                        right_margin,
10827                        editor_width,
10828                        window,
10829                        cx,
10830                    );
10831
10832                    let gutter_settings = EditorSettings::get_global(cx).gutter;
10833
10834                    let context_menu_layout =
10835                        if let Some(newest_selection_head) = newest_selection_head {
10836                            let newest_selection_point =
10837                                newest_selection_head.to_point(&snapshot.display_snapshot);
10838                            if (start_row..end_row).contains(&newest_selection_head.row()) {
10839                                self.layout_cursor_popovers(
10840                                    line_height,
10841                                    &text_hitbox,
10842                                    content_origin,
10843                                    right_margin,
10844                                    start_row,
10845                                    scroll_pixel_position,
10846                                    &line_layouts,
10847                                    newest_selection_head,
10848                                    newest_selection_point,
10849                                    style,
10850                                    window,
10851                                    cx,
10852                                )
10853                            } else {
10854                                None
10855                            }
10856                        } else {
10857                            None
10858                        };
10859
10860                    self.layout_gutter_menu(
10861                        line_height,
10862                        &text_hitbox,
10863                        content_origin,
10864                        right_margin,
10865                        scroll_pixel_position,
10866                        gutter_dimensions.width - gutter_dimensions.left_padding,
10867                        window,
10868                        cx,
10869                    );
10870
10871                    let test_indicators = if gutter_settings.runnables {
10872                        self.layout_run_indicators(
10873                            &gutter,
10874                            &run_indicator_rows,
10875                            &breakpoint_rows,
10876                            window,
10877                            cx,
10878                        )
10879                    } else {
10880                        Vec::new()
10881                    };
10882
10883                    let show_bookmarks =
10884                        snapshot.show_bookmarks.unwrap_or(gutter_settings.bookmarks);
10885
10886                    let bookmark_rows = self.editor.update(cx, |editor, cx| {
10887                        let mut rows = editor.active_bookmarks(start_row..end_row, window, cx);
10888                        rows.retain(|k| !run_indicator_rows.contains(k));
10889                        rows.retain(|k| !breakpoint_rows.contains_key(k));
10890                        rows
10891                    });
10892
10893                    let bookmarks = if show_bookmarks {
10894                        self.layout_bookmarks(&gutter, &bookmark_rows, window, cx)
10895                    } else {
10896                        Vec::new()
10897                    };
10898
10899                    let show_breakpoints = snapshot
10900                        .show_breakpoints
10901                        .unwrap_or(gutter_settings.breakpoints);
10902
10903                    breakpoint_rows.retain(|k, _| !run_indicator_rows.contains(k));
10904                    let mut breakpoints = if show_breakpoints {
10905                        self.layout_breakpoints(&gutter, &breakpoint_rows, window, cx)
10906                    } else {
10907                        Vec::new()
10908                    };
10909
10910                    let gutter_hover_button = self
10911                        .editor
10912                        .read(cx)
10913                        .gutter_hover_button
10914                        .0
10915                        .filter(|phantom| phantom.is_active)
10916                        .map(|phantom| phantom.display_row);
10917
10918                    if let Some(row) = gutter_hover_button
10919                        && !breakpoint_rows.contains_key(&row)
10920                        && !run_indicator_rows.contains(&row)
10921                        && !bookmark_rows.contains(&row)
10922                        && (show_bookmarks || show_breakpoints)
10923                    {
10924                        let position = snapshot
10925                            .display_point_to_anchor(DisplayPoint::new(row, 0), Bias::Right);
10926                        breakpoints.extend(
10927                            self.layout_gutter_hover_button(&gutter, position, row, window, cx),
10928                        );
10929                    }
10930
10931                    let git_gutter_width = Self::gutter_strip_width(line_height)
10932                        + gutter_dimensions
10933                            .git_blame_entries_width
10934                            .unwrap_or_default();
10935                    let available_width = gutter_dimensions.left_padding - git_gutter_width;
10936
10937                    let max_line_number_length = self
10938                        .editor
10939                        .read(cx)
10940                        .buffer()
10941                        .read(cx)
10942                        .snapshot(cx)
10943                        .widest_line_number()
10944                        .ilog10()
10945                        + 1;
10946
10947                    let diff_review_button = self
10948                        .should_render_diff_review_button(
10949                            start_row..end_row,
10950                            &row_infos,
10951                            &snapshot,
10952                            cx,
10953                        )
10954                        .map(|(display_row, buffer_row)| {
10955                            let is_wide = max_line_number_length
10956                                >= EditorSettings::get_global(cx).gutter.min_line_number_digits
10957                                    as u32
10958                                && buffer_row.is_some_and(|row| {
10959                                    (row + 1).ilog10() + 1 == max_line_number_length
10960                                })
10961                                || gutter_dimensions.right_padding == px(0.);
10962
10963                            let button_width = if is_wide {
10964                                available_width - px(6.)
10965                            } else {
10966                                available_width + em_width - px(6.)
10967                            };
10968
10969                            let button = self.editor.update(cx, |editor, cx| {
10970                                editor
10971                                    .render_diff_review_button(display_row, button_width, cx)
10972                                    .into_any_element()
10973                            });
10974                            gutter.prepaint_button(button, display_row, window, cx)
10975                        });
10976
10977                    self.layout_signature_help(
10978                        &hitbox,
10979                        content_origin,
10980                        scroll_pixel_position,
10981                        newest_selection_head,
10982                        start_row,
10983                        &line_layouts,
10984                        line_height,
10985                        em_width,
10986                        context_menu_layout,
10987                        window,
10988                        cx,
10989                    );
10990
10991                    if !cx.has_active_drag() {
10992                        self.layout_hover_popovers(
10993                            &snapshot,
10994                            &hitbox,
10995                            start_row..end_row,
10996                            content_origin,
10997                            scroll_pixel_position,
10998                            &line_layouts,
10999                            line_height,
11000                            em_width,
11001                            context_menu_layout,
11002                            window,
11003                            cx,
11004                        );
11005
11006                        self.layout_blame_popover(&snapshot, &hitbox, line_height, window, cx);
11007                    }
11008
11009                    let mouse_context_menu = self.layout_mouse_context_menu(
11010                        &snapshot,
11011                        start_row..end_row,
11012                        content_origin,
11013                        window,
11014                        cx,
11015                    );
11016
11017                    window.with_element_namespace("crease_toggles", |window| {
11018                        self.prepaint_crease_toggles(
11019                            &mut crease_toggles,
11020                            line_height,
11021                            &gutter_dimensions,
11022                            gutter_settings,
11023                            scroll_pixel_position,
11024                            &gutter_hitbox,
11025                            window,
11026                            cx,
11027                        )
11028                    });
11029
11030                    window.with_element_namespace("expand_toggles", |window| {
11031                        self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
11032                    });
11033
11034                    let wrap_guides = self.layout_wrap_guides(
11035                        em_advance,
11036                        scroll_position,
11037                        content_origin,
11038                        scrollbars_layout.as_ref(),
11039                        vertical_scrollbar_width,
11040                        &hitbox,
11041                        window,
11042                        cx,
11043                    );
11044
11045                    let minimap = window.with_element_namespace("minimap", |window| {
11046                        self.layout_minimap(
11047                            &snapshot,
11048                            minimap_width,
11049                            scroll_position,
11050                            &scrollbar_layout_information,
11051                            scrollbars_layout.as_ref(),
11052                            window,
11053                            cx,
11054                        )
11055                    });
11056
11057                    let invisible_symbol_font_size = font_size / 2.;
11058                    let whitespace_map = &self
11059                        .editor
11060                        .read(cx)
11061                        .buffer
11062                        .read(cx)
11063                        .language_settings(cx)
11064                        .whitespace_map;
11065
11066                    let tab_char = whitespace_map.tab.clone();
11067                    let tab_len = tab_char.len();
11068                    let tab_invisible = window.text_system().shape_line(
11069                        tab_char,
11070                        invisible_symbol_font_size,
11071                        &[TextRun {
11072                            len: tab_len,
11073                            font: self.style.text.font(),
11074                            color: cx.theme().colors().editor_invisible,
11075                            ..Default::default()
11076                        }],
11077                        None,
11078                    );
11079
11080                    let space_char = whitespace_map.space.clone();
11081                    let space_len = space_char.len();
11082                    let space_invisible = window.text_system().shape_line(
11083                        space_char,
11084                        invisible_symbol_font_size,
11085                        &[TextRun {
11086                            len: space_len,
11087                            font: self.style.text.font(),
11088                            color: cx.theme().colors().editor_invisible,
11089                            ..Default::default()
11090                        }],
11091                        None,
11092                    );
11093
11094                    let mode = snapshot.mode.clone();
11095
11096                    let sticky_scroll_header_height = sticky_headers
11097                        .as_ref()
11098                        .and_then(|headers| headers.lines.last())
11099                        .map_or(Pixels::ZERO, |last| last.offset + line_height);
11100
11101                    let has_sticky_buffer_header =
11102                        sticky_buffer_header.is_some() || sticky_header_excerpt_id.is_some();
11103                    let sticky_header_height = if has_sticky_buffer_header {
11104                        let full_height = FILE_HEADER_HEIGHT as f32 * line_height;
11105                        let display_row = blocks
11106                            .iter()
11107                            .filter(|block| block.is_buffer_header)
11108                            .find_map(|block| {
11109                                block.row.filter(|row| row.0 > scroll_position.y as u32)
11110                            });
11111                        let offset = match display_row {
11112                            Some(display_row) => {
11113                                let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
11114                                let offset = (scroll_position.y - max_row as f64).max(0.0);
11115                                let slide_up =
11116                                    Pixels::from(offset * ScrollPixelOffset::from(line_height));
11117
11118                                (full_height - slide_up).max(Pixels::ZERO)
11119                            }
11120                            None => full_height,
11121                        };
11122                        let header_bottom_padding =
11123                            BUFFER_HEADER_PADDING.to_pixels(window.rem_size());
11124                        sticky_scroll_header_height + offset - header_bottom_padding
11125                    } else {
11126                        sticky_scroll_header_height
11127                    };
11128
11129                    let (diff_hunk_controls, diff_hunk_control_bounds) =
11130                        if is_read_only && !self.editor.read(cx).delegate_stage_and_restore {
11131                            (vec![], vec![])
11132                        } else {
11133                            self.layout_diff_hunk_controls(
11134                                start_row..end_row,
11135                                &row_infos,
11136                                &text_hitbox,
11137                                current_selection_head,
11138                                line_height,
11139                                right_margin,
11140                                scroll_pixel_position,
11141                                sticky_header_height,
11142                                &display_hunks,
11143                                &highlighted_rows,
11144                                self.editor.clone(),
11145                                window,
11146                                cx,
11147                            )
11148                        };
11149
11150                    let position_map = Rc::new(PositionMap {
11151                        size: bounds.size,
11152                        visible_row_range,
11153                        scroll_position,
11154                        scroll_pixel_position,
11155                        scroll_max,
11156                        line_layouts,
11157                        line_height,
11158                        em_width,
11159                        em_advance,
11160                        em_layout_width,
11161                        snapshot,
11162                        text_align: self.style.text.text_align,
11163                        content_width: text_hitbox.size.width,
11164                        gutter_hitbox: gutter_hitbox.clone(),
11165                        text_hitbox: text_hitbox.clone(),
11166                        inline_blame_bounds: inline_blame_layout
11167                            .as_ref()
11168                            .map(|layout| (layout.bounds, layout.buffer_id, layout.entry.clone())),
11169                        display_hunks: display_hunks.clone(),
11170                        diff_hunk_control_bounds,
11171                    });
11172
11173                    self.editor.update(cx, |editor, _| {
11174                        editor.last_position_map = Some(position_map.clone())
11175                    });
11176
11177                    EditorLayout {
11178                        mode,
11179                        position_map,
11180                        visible_display_row_range: start_row..end_row,
11181                        wrap_guides,
11182                        indent_guides,
11183                        hitbox,
11184                        gutter_hitbox,
11185                        display_hunks,
11186                        content_origin,
11187                        scrollbars_layout,
11188                        minimap,
11189                        active_rows,
11190                        highlighted_rows,
11191                        highlighted_ranges,
11192                        highlighted_gutter_ranges,
11193                        redacted_ranges,
11194                        document_colors,
11195                        line_elements,
11196                        line_numbers,
11197                        blamed_display_rows,
11198                        inline_diagnostics,
11199                        inline_blame_layout,
11200                        inline_code_actions,
11201                        blocks,
11202                        spacer_blocks,
11203                        cursors,
11204                        visible_cursors,
11205                        navigation_overlay_paint_commands,
11206                        selections,
11207                        edit_prediction_popover,
11208                        diff_hunk_controls,
11209                        mouse_context_menu,
11210                        test_indicators,
11211                        bookmarks,
11212                        breakpoints,
11213                        diff_review_button,
11214                        crease_toggles,
11215                        crease_trailers,
11216                        tab_invisible,
11217                        space_invisible,
11218                        sticky_buffer_header,
11219                        sticky_headers,
11220                        expand_toggles,
11221                        text_align: self.style.text.text_align,
11222                        content_width: text_hitbox.size.width,
11223                    }
11224                })
11225            })
11226        })
11227    }
11228
11229    fn paint(
11230        &mut self,
11231        _: Option<&GlobalElementId>,
11232        _inspector_id: Option<&gpui::InspectorElementId>,
11233        bounds: Bounds<gpui::Pixels>,
11234        _: &mut Self::RequestLayoutState,
11235        layout: &mut Self::PrepaintState,
11236        window: &mut Window,
11237        cx: &mut App,
11238    ) {
11239        if !layout.mode.is_minimap() {
11240            let focus_handle = self.editor.focus_handle(cx);
11241            let key_context = self
11242                .editor
11243                .update(cx, |editor, cx| editor.key_context(window, cx));
11244
11245            window.set_key_context(key_context);
11246            window.handle_input(
11247                &focus_handle,
11248                ElementInputHandler::new(bounds, self.editor.clone()),
11249                cx,
11250            );
11251            self.register_actions(window, cx);
11252            self.register_key_listeners(window, cx, layout);
11253        }
11254
11255        let text_style = TextStyleRefinement {
11256            font_size: Some(self.style.text.font_size),
11257            line_height: Some(self.style.text.line_height),
11258            ..Default::default()
11259        };
11260        let rem_size = self.rem_size(cx);
11261        window.with_rem_size(rem_size, |window| {
11262            window.with_text_style(Some(text_style), |window| {
11263                window.with_content_mask(Some(ContentMask { bounds }), |window| {
11264                    self.paint_mouse_listeners(layout, window, cx);
11265
11266                    // Mask the editor behind sticky scroll headers. Important
11267                    // for transparent backgrounds.
11268                    let below_sticky_headers_mask = layout
11269                        .sticky_headers
11270                        .as_ref()
11271                        .and_then(|h| h.lines.last())
11272                        .map(|last| ContentMask {
11273                            bounds: Bounds {
11274                                origin: point(
11275                                    bounds.origin.x,
11276                                    bounds.origin.y + last.offset + layout.position_map.line_height,
11277                                ),
11278                                size: size(
11279                                    bounds.size.width,
11280                                    (bounds.size.height
11281                                        - last.offset
11282                                        - layout.position_map.line_height)
11283                                        .max(Pixels::ZERO),
11284                                ),
11285                            },
11286                        });
11287
11288                    window.with_content_mask(below_sticky_headers_mask, |window| {
11289                        self.paint_background(layout, window, cx);
11290
11291                        self.paint_indent_guides(layout, window, cx);
11292
11293                        if layout.gutter_hitbox.size.width > Pixels::ZERO {
11294                            self.paint_blamed_display_rows(layout, window, cx);
11295                            self.paint_line_numbers(layout, window, cx);
11296                        }
11297
11298                        self.paint_text(layout, window, cx);
11299
11300                        if !layout.spacer_blocks.is_empty() {
11301                            window.with_element_namespace("blocks", |window| {
11302                                self.paint_spacer_blocks(layout, window, cx);
11303                            });
11304                        }
11305
11306                        if layout.gutter_hitbox.size.width > Pixels::ZERO {
11307                            self.paint_gutter_highlights(layout, window, cx);
11308                            self.paint_gutter_indicators(layout, window, cx);
11309                        }
11310
11311                        if !layout.blocks.is_empty() {
11312                            window.with_element_namespace("blocks", |window| {
11313                                self.paint_non_spacer_blocks(layout, window, cx);
11314                            });
11315                        }
11316                    });
11317
11318                    window.with_element_namespace("blocks", |window| {
11319                        if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
11320                            sticky_header.paint(window, cx)
11321                        }
11322                    });
11323
11324                    self.paint_sticky_headers(layout, window, cx);
11325                    self.paint_minimap(layout, window, cx);
11326                    self.paint_scrollbars(layout, window, cx);
11327                    self.paint_edit_prediction_popover(layout, window, cx);
11328                    self.paint_mouse_context_menu(layout, window, cx);
11329                });
11330            })
11331        })
11332    }
11333}
11334
11335pub(super) fn gutter_bounds(
11336    editor_bounds: Bounds<Pixels>,
11337    gutter_dimensions: GutterDimensions,
11338) -> Bounds<Pixels> {
11339    Bounds {
11340        origin: editor_bounds.origin,
11341        size: size(gutter_dimensions.width, editor_bounds.size.height),
11342    }
11343}
11344
11345#[derive(Clone, Copy)]
11346struct ContextMenuLayout {
11347    y_flipped: bool,
11348    bounds: Bounds<Pixels>,
11349}
11350
11351/// Holds information required for layouting the editor scrollbars.
11352struct ScrollbarLayoutInformation {
11353    /// The bounds of the editor area (excluding the content offset).
11354    editor_bounds: Bounds<Pixels>,
11355    /// The available range to scroll within the document.
11356    scroll_range: Size<Pixels>,
11357    /// The space available for one glyph in the editor.
11358    glyph_grid_cell: Size<Pixels>,
11359}
11360
11361impl ScrollbarLayoutInformation {
11362    pub fn new(
11363        editor_bounds: Bounds<Pixels>,
11364        glyph_grid_cell: Size<Pixels>,
11365        document_size: Size<Pixels>,
11366        longest_line_blame_width: Pixels,
11367        settings: &EditorSettings,
11368        scroll_beyond_last_line: ScrollBeyondLastLine,
11369    ) -> Self {
11370        let vertical_overscroll = match scroll_beyond_last_line {
11371            ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
11372            ScrollBeyondLastLine::Off => glyph_grid_cell.height,
11373            ScrollBeyondLastLine::VerticalScrollMargin => {
11374                (1.0 + settings.vertical_scroll_margin) as f32 * glyph_grid_cell.height
11375            }
11376        };
11377
11378        let overscroll = size(longest_line_blame_width, vertical_overscroll);
11379
11380        ScrollbarLayoutInformation {
11381            editor_bounds,
11382            scroll_range: document_size + overscroll,
11383            glyph_grid_cell,
11384        }
11385    }
11386}
11387
11388impl IntoElement for EditorElement {
11389    type Element = Self;
11390
11391    fn into_element(self) -> Self::Element {
11392        self
11393    }
11394}
11395
11396pub struct EditorLayout {
11397    position_map: Rc<PositionMap>,
11398    hitbox: Hitbox,
11399    gutter_hitbox: Hitbox,
11400    content_origin: gpui::Point<Pixels>,
11401    scrollbars_layout: Option<EditorScrollbars>,
11402    minimap: Option<MinimapLayout>,
11403    mode: EditorMode,
11404    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
11405    indent_guides: Option<Vec<IndentGuideLayout>>,
11406    visible_display_row_range: Range<DisplayRow>,
11407    active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
11408    highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
11409    line_elements: SmallVec<[AnyElement; 1]>,
11410    line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
11411    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
11412    blamed_display_rows: Option<Vec<AnyElement>>,
11413    inline_diagnostics: HashMap<DisplayRow, AnyElement>,
11414    inline_blame_layout: Option<InlineBlameLayout>,
11415    inline_code_actions: Option<AnyElement>,
11416    blocks: Vec<BlockLayout>,
11417    spacer_blocks: Vec<BlockLayout>,
11418    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
11419    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
11420    redacted_ranges: Vec<Range<DisplayPoint>>,
11421    cursors: Vec<(DisplayPoint, Hsla)>,
11422    visible_cursors: Vec<CursorLayout>,
11423    navigation_overlay_paint_commands: Vec<NavigationOverlayPaintCommand>,
11424    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
11425    test_indicators: Vec<AnyElement>,
11426    bookmarks: Vec<AnyElement>,
11427    breakpoints: Vec<AnyElement>,
11428    diff_review_button: Option<AnyElement>,
11429    crease_toggles: Vec<Option<AnyElement>>,
11430    expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
11431    diff_hunk_controls: Vec<AnyElement>,
11432    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
11433    edit_prediction_popover: Option<AnyElement>,
11434    mouse_context_menu: Option<AnyElement>,
11435    tab_invisible: ShapedLine,
11436    space_invisible: ShapedLine,
11437    sticky_buffer_header: Option<AnyElement>,
11438    sticky_headers: Option<StickyHeaders>,
11439    document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
11440    text_align: TextAlign,
11441    content_width: Pixels,
11442}
11443
11444struct StickyHeaders {
11445    lines: Vec<StickyHeaderLine>,
11446    gutter_background: Hsla,
11447    content_background: Hsla,
11448    gutter_right_padding: Pixels,
11449}
11450
11451struct StickyHeaderLine {
11452    row: DisplayRow,
11453    offset: Pixels,
11454    line: Rc<LineWithInvisibles>,
11455    line_number: Option<ShapedLine>,
11456    elements: SmallVec<[AnyElement; 1]>,
11457    available_text_width: Pixels,
11458    hitbox: Hitbox,
11459}
11460
11461impl EditorLayout {
11462    fn line_end_overshoot(&self) -> Pixels {
11463        0.15 * self.position_map.line_height
11464    }
11465}
11466
11467impl StickyHeaders {
11468    fn paint(
11469        &mut self,
11470        layout: &mut EditorLayout,
11471        whitespace_setting: ShowWhitespaceSetting,
11472        window: &mut Window,
11473        cx: &mut App,
11474    ) {
11475        let line_height = layout.position_map.line_height;
11476
11477        for line in self.lines.iter_mut().rev() {
11478            window.paint_layer(
11479                Bounds::new(
11480                    layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
11481                    size(line.hitbox.size.width, line_height),
11482                ),
11483                |window| {
11484                    let gutter_bounds = Bounds::new(
11485                        layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
11486                        size(layout.gutter_hitbox.size.width, line_height),
11487                    );
11488                    window.paint_quad(fill(gutter_bounds, self.gutter_background));
11489
11490                    let text_bounds = Bounds::new(
11491                        layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset),
11492                        size(line.available_text_width, line_height),
11493                    );
11494                    window.paint_quad(fill(text_bounds, self.content_background));
11495
11496                    if line.hitbox.is_hovered(window) {
11497                        let hover_overlay = cx.theme().colors().panel_overlay_hover;
11498                        window.paint_quad(fill(gutter_bounds, hover_overlay));
11499                        window.paint_quad(fill(text_bounds, hover_overlay));
11500                    }
11501
11502                    line.paint(
11503                        layout,
11504                        self.gutter_right_padding,
11505                        line.available_text_width,
11506                        layout.content_origin,
11507                        line_height,
11508                        whitespace_setting,
11509                        window,
11510                        cx,
11511                    );
11512                },
11513            );
11514
11515            window.set_cursor_style(CursorStyle::IBeam, &line.hitbox);
11516        }
11517    }
11518}
11519
11520impl StickyHeaderLine {
11521    fn new(
11522        row: DisplayRow,
11523        offset: Pixels,
11524        mut line: LineWithInvisibles,
11525        line_number: Option<ShapedLine>,
11526        line_height: Pixels,
11527        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11528        content_origin: gpui::Point<Pixels>,
11529        gutter_hitbox: &Hitbox,
11530        text_hitbox: &Hitbox,
11531        window: &mut Window,
11532        cx: &mut App,
11533    ) -> Self {
11534        let mut elements = SmallVec::<[AnyElement; 1]>::new();
11535        line.prepaint_with_custom_offset(
11536            line_height,
11537            scroll_pixel_position,
11538            content_origin,
11539            offset,
11540            &mut elements,
11541            window,
11542            cx,
11543        );
11544
11545        let hitbox_bounds = Bounds::new(
11546            gutter_hitbox.origin + point(Pixels::ZERO, offset),
11547            size(text_hitbox.right() - gutter_hitbox.left(), line_height),
11548        );
11549        let available_text_width =
11550            (hitbox_bounds.size.width - gutter_hitbox.size.width).max(Pixels::ZERO);
11551
11552        Self {
11553            row,
11554            offset,
11555            line: Rc::new(line),
11556            line_number,
11557            elements,
11558            available_text_width,
11559            hitbox: window.insert_hitbox(hitbox_bounds, HitboxBehavior::BlockMouseExceptScroll),
11560        }
11561    }
11562
11563    fn paint(
11564        &mut self,
11565        layout: &EditorLayout,
11566        gutter_right_padding: Pixels,
11567        available_text_width: Pixels,
11568        content_origin: gpui::Point<Pixels>,
11569        line_height: Pixels,
11570        whitespace_setting: ShowWhitespaceSetting,
11571        window: &mut Window,
11572        cx: &mut App,
11573    ) {
11574        window.with_content_mask(
11575            Some(ContentMask {
11576                bounds: Bounds::new(
11577                    layout.position_map.text_hitbox.bounds.origin
11578                        + point(Pixels::ZERO, self.offset),
11579                    size(available_text_width, line_height),
11580                ),
11581            }),
11582            |window| {
11583                self.line.draw_with_custom_offset(
11584                    layout,
11585                    self.row,
11586                    content_origin,
11587                    self.offset,
11588                    whitespace_setting,
11589                    &[],
11590                    window,
11591                    cx,
11592                );
11593                for element in &mut self.elements {
11594                    element.paint(window, cx);
11595                }
11596            },
11597        );
11598
11599        if let Some(line_number) = &self.line_number {
11600            let gutter_origin = layout.gutter_hitbox.origin + point(Pixels::ZERO, self.offset);
11601            let gutter_width = layout.gutter_hitbox.size.width;
11602            let origin = point(
11603                gutter_origin.x + gutter_width - gutter_right_padding - line_number.width,
11604                gutter_origin.y,
11605            );
11606            line_number
11607                .paint(origin, line_height, TextAlign::Left, None, window, cx)
11608                .log_err();
11609        }
11610    }
11611}
11612
11613#[derive(Debug)]
11614struct LineNumberSegment {
11615    shaped_line: ShapedLine,
11616    hitbox: Option<Hitbox>,
11617}
11618
11619#[derive(Debug)]
11620struct LineNumberLayout {
11621    segments: SmallVec<[LineNumberSegment; 1]>,
11622}
11623
11624struct ColoredRange<T> {
11625    start: T,
11626    end: T,
11627    color: Hsla,
11628}
11629
11630impl Along for ScrollbarAxes {
11631    type Unit = bool;
11632
11633    fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
11634        match axis {
11635            ScrollbarAxis::Horizontal => self.horizontal,
11636            ScrollbarAxis::Vertical => self.vertical,
11637        }
11638    }
11639
11640    fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
11641        match axis {
11642            ScrollbarAxis::Horizontal => ScrollbarAxes {
11643                horizontal: f(self.horizontal),
11644                vertical: self.vertical,
11645            },
11646            ScrollbarAxis::Vertical => ScrollbarAxes {
11647                horizontal: self.horizontal,
11648                vertical: f(self.vertical),
11649            },
11650        }
11651    }
11652}
11653
11654#[derive(Clone)]
11655struct EditorScrollbars {
11656    pub vertical: Option<ScrollbarLayout>,
11657    pub horizontal: Option<ScrollbarLayout>,
11658    pub visible: bool,
11659}
11660
11661impl EditorScrollbars {
11662    pub fn from_scrollbar_axes(
11663        show_scrollbar: ScrollbarAxes,
11664        layout_information: &ScrollbarLayoutInformation,
11665        content_offset: gpui::Point<Pixels>,
11666        scroll_position: gpui::Point<f64>,
11667        scrollbar_width: Pixels,
11668        right_margin: Pixels,
11669        editor_width: Pixels,
11670        show_scrollbars: bool,
11671        scrollbar_state: Option<&ActiveScrollbarState>,
11672        window: &mut Window,
11673    ) -> Self {
11674        let ScrollbarLayoutInformation {
11675            editor_bounds,
11676            scroll_range,
11677            glyph_grid_cell,
11678        } = layout_information;
11679
11680        let viewport_size = size(editor_width, editor_bounds.size.height);
11681
11682        let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
11683            ScrollbarAxis::Horizontal => Bounds::from_anchor_and_size(
11684                gpui::Anchor::BottomLeft,
11685                editor_bounds.bottom_left(),
11686                size(
11687                    // The horizontal viewport size differs from the space available for the
11688                    // horizontal scrollbar, so we have to manually stitch it together here.
11689                    editor_bounds.size.width - right_margin,
11690                    scrollbar_width,
11691                ),
11692            ),
11693            ScrollbarAxis::Vertical => Bounds::from_anchor_and_size(
11694                gpui::Anchor::TopRight,
11695                editor_bounds.top_right(),
11696                size(scrollbar_width, viewport_size.height),
11697            ),
11698        };
11699
11700        let mut create_scrollbar_layout = |axis| {
11701            let viewport_size = viewport_size.along(axis);
11702            let scroll_range = scroll_range.along(axis);
11703
11704            // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
11705            (show_scrollbar.along(axis)
11706                && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
11707                .then(|| {
11708                    ScrollbarLayout::new(
11709                        window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
11710                        viewport_size,
11711                        scroll_range,
11712                        glyph_grid_cell.along(axis),
11713                        content_offset.along(axis),
11714                        scroll_position.along(axis),
11715                        show_scrollbars,
11716                        axis,
11717                    )
11718                    .with_thumb_state(
11719                        scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
11720                    )
11721                })
11722        };
11723
11724        Self {
11725            vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
11726            horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
11727            visible: show_scrollbars,
11728        }
11729    }
11730
11731    pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
11732        [
11733            (&self.vertical, ScrollbarAxis::Vertical),
11734            (&self.horizontal, ScrollbarAxis::Horizontal),
11735        ]
11736        .into_iter()
11737        .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
11738    }
11739
11740    /// Returns the currently hovered scrollbar axis, if any.
11741    pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
11742        self.iter_scrollbars()
11743            .find(|s| s.0.hitbox.is_hovered(window))
11744    }
11745}
11746
11747#[derive(Clone)]
11748struct ScrollbarLayout {
11749    hitbox: Hitbox,
11750    visible_range: Range<ScrollOffset>,
11751    text_unit_size: Pixels,
11752    thumb_bounds: Option<Bounds<Pixels>>,
11753    thumb_state: ScrollbarThumbState,
11754}
11755
11756impl ScrollbarLayout {
11757    const BORDER_WIDTH: Pixels = px(1.0);
11758    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
11759    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
11760    const MIN_THUMB_SIZE: Pixels = px(25.0);
11761
11762    fn new(
11763        scrollbar_track_hitbox: Hitbox,
11764        viewport_size: Pixels,
11765        scroll_range: Pixels,
11766        glyph_space: Pixels,
11767        content_offset: Pixels,
11768        scroll_position: ScrollOffset,
11769        show_thumb: bool,
11770        axis: ScrollbarAxis,
11771    ) -> Self {
11772        let track_bounds = scrollbar_track_hitbox.bounds;
11773        // The length of the track available to the scrollbar thumb. We deliberately
11774        // exclude the content size here so that the thumb aligns with the content.
11775        let track_length = track_bounds.size.along(axis) - content_offset;
11776
11777        Self::new_with_hitbox_and_track_length(
11778            scrollbar_track_hitbox,
11779            track_length,
11780            viewport_size,
11781            scroll_range.into(),
11782            glyph_space,
11783            content_offset.into(),
11784            scroll_position,
11785            show_thumb,
11786            axis,
11787        )
11788    }
11789
11790    fn for_minimap(
11791        minimap_track_hitbox: Hitbox,
11792        visible_lines: f64,
11793        total_editor_lines: f64,
11794        minimap_line_height: Pixels,
11795        scroll_position: ScrollOffset,
11796        minimap_scroll_top: ScrollOffset,
11797        show_thumb: bool,
11798    ) -> Self {
11799        // The scrollbar thumb size is calculated as
11800        // (visible_content/total_content) Γ— scrollbar_track_length.
11801        //
11802        // For the minimap's thumb layout, we leverage this by setting the
11803        // scrollbar track length to the entire document size (using minimap line
11804        // height). This creates a thumb that exactly represents the editor
11805        // viewport scaled to minimap proportions.
11806        //
11807        // We adjust the thumb position relative to `minimap_scroll_top` to
11808        // accommodate for the deliberately oversized track.
11809        //
11810        // This approach ensures that the minimap thumb accurately reflects the
11811        // editor's current scroll position whilst nicely synchronizing the minimap
11812        // thumb and scrollbar thumb.
11813        let scroll_range = total_editor_lines * f64::from(minimap_line_height);
11814        let viewport_size = visible_lines * f64::from(minimap_line_height);
11815
11816        let track_top_offset = -minimap_scroll_top * f64::from(minimap_line_height);
11817
11818        Self::new_with_hitbox_and_track_length(
11819            minimap_track_hitbox,
11820            Pixels::from(scroll_range),
11821            Pixels::from(viewport_size),
11822            scroll_range,
11823            minimap_line_height,
11824            track_top_offset,
11825            scroll_position,
11826            show_thumb,
11827            ScrollbarAxis::Vertical,
11828        )
11829    }
11830
11831    fn new_with_hitbox_and_track_length(
11832        scrollbar_track_hitbox: Hitbox,
11833        track_length: Pixels,
11834        viewport_size: Pixels,
11835        scroll_range: f64,
11836        glyph_space: Pixels,
11837        content_offset: ScrollOffset,
11838        scroll_position: ScrollOffset,
11839        show_thumb: bool,
11840        axis: ScrollbarAxis,
11841    ) -> Self {
11842        let text_units_per_page = viewport_size.to_f64() / glyph_space.to_f64();
11843        let visible_range = scroll_position..scroll_position + text_units_per_page;
11844        let total_text_units = scroll_range / glyph_space.to_f64();
11845
11846        let thumb_percentage = text_units_per_page / total_text_units;
11847        let thumb_size = Pixels::from(ScrollOffset::from(track_length) * thumb_percentage)
11848            .max(ScrollbarLayout::MIN_THUMB_SIZE)
11849            .min(track_length);
11850
11851        let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
11852
11853        let content_larger_than_viewport = text_unit_divisor > 0.;
11854
11855        let text_unit_size = if content_larger_than_viewport {
11856            Pixels::from(ScrollOffset::from(track_length - thumb_size) / text_unit_divisor)
11857        } else {
11858            glyph_space
11859        };
11860
11861        let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
11862            Self::thumb_bounds(
11863                &scrollbar_track_hitbox,
11864                content_offset,
11865                visible_range.start,
11866                text_unit_size,
11867                thumb_size,
11868                axis,
11869            )
11870        });
11871
11872        ScrollbarLayout {
11873            hitbox: scrollbar_track_hitbox,
11874            visible_range,
11875            text_unit_size,
11876            thumb_bounds,
11877            thumb_state: Default::default(),
11878        }
11879    }
11880
11881    fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
11882        if let Some(thumb_state) = thumb_state {
11883            Self {
11884                thumb_state,
11885                ..self
11886            }
11887        } else {
11888            self
11889        }
11890    }
11891
11892    fn thumb_bounds(
11893        scrollbar_track: &Hitbox,
11894        content_offset: f64,
11895        visible_range_start: f64,
11896        text_unit_size: Pixels,
11897        thumb_size: Pixels,
11898        axis: ScrollbarAxis,
11899    ) -> Bounds<Pixels> {
11900        let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
11901            origin
11902                + Pixels::from(
11903                    content_offset + visible_range_start * ScrollOffset::from(text_unit_size),
11904                )
11905        });
11906        Bounds::new(
11907            thumb_origin,
11908            scrollbar_track.size.apply_along(axis, |_| thumb_size),
11909        )
11910    }
11911
11912    fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
11913        self.thumb_bounds
11914            .is_some_and(|bounds| bounds.contains(position))
11915    }
11916
11917    fn marker_quads_for_ranges(
11918        &self,
11919        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
11920        column: Option<usize>,
11921    ) -> Vec<PaintQuad> {
11922        struct MinMax {
11923            min: Pixels,
11924            max: Pixels,
11925        }
11926        let (x_range, height_limit) = if let Some(column) = column {
11927            let column_width = ((self.hitbox.size.width - Self::BORDER_WIDTH) / 3.0).floor();
11928            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
11929            let end = start + column_width;
11930            (
11931                Range { start, end },
11932                MinMax {
11933                    min: Self::MIN_MARKER_HEIGHT,
11934                    max: px(f32::MAX),
11935                },
11936            )
11937        } else {
11938            (
11939                Range {
11940                    start: Self::BORDER_WIDTH,
11941                    end: self.hitbox.size.width,
11942                },
11943                MinMax {
11944                    min: Self::LINE_MARKER_HEIGHT,
11945                    max: Self::LINE_MARKER_HEIGHT,
11946                },
11947            )
11948        };
11949
11950        let row_to_y = |row: DisplayRow| row.as_f64() as f32 * self.text_unit_size;
11951        let mut pixel_ranges = row_ranges
11952            .into_iter()
11953            .map(|range| {
11954                let start_y = row_to_y(range.start);
11955                let end_y = row_to_y(range.end)
11956                    + self
11957                        .text_unit_size
11958                        .max(height_limit.min)
11959                        .min(height_limit.max);
11960                ColoredRange {
11961                    start: start_y,
11962                    end: end_y,
11963                    color: range.color,
11964                }
11965            })
11966            .peekable();
11967
11968        let mut quads = Vec::new();
11969        while let Some(mut pixel_range) = pixel_ranges.next() {
11970            while let Some(next_pixel_range) = pixel_ranges.peek() {
11971                if pixel_range.end >= next_pixel_range.start - px(1.0)
11972                    && pixel_range.color == next_pixel_range.color
11973                {
11974                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
11975                    pixel_ranges.next();
11976                } else {
11977                    break;
11978                }
11979            }
11980
11981            let bounds = Bounds::from_corners(
11982                point(x_range.start, pixel_range.start),
11983                point(x_range.end, pixel_range.end),
11984            );
11985            quads.push(quad(
11986                bounds,
11987                Corners::default(),
11988                pixel_range.color,
11989                Edges::default(),
11990                Hsla::transparent_black(),
11991                BorderStyle::default(),
11992            ));
11993        }
11994
11995        quads
11996    }
11997}
11998
11999struct MinimapLayout {
12000    pub minimap: AnyElement,
12001    pub thumb_layout: ScrollbarLayout,
12002    pub minimap_scroll_top: ScrollOffset,
12003    pub minimap_line_height: Pixels,
12004    pub thumb_border_style: MinimapThumbBorder,
12005    pub max_scroll_top: ScrollOffset,
12006}
12007
12008impl MinimapLayout {
12009    /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
12010    const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
12011    /// The minimap width as a percentage of the editor width.
12012    const MINIMAP_WIDTH_PCT: f32 = 0.15;
12013    /// Calculates the scroll top offset the minimap editor has to have based on the
12014    /// current scroll progress.
12015    fn calculate_minimap_top_offset(
12016        document_lines: f64,
12017        visible_editor_lines: f64,
12018        visible_minimap_lines: f64,
12019        scroll_position: f64,
12020    ) -> ScrollOffset {
12021        let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
12022        if non_visible_document_lines == 0. {
12023            0.
12024        } else {
12025            let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
12026            scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
12027        }
12028    }
12029}
12030
12031struct CreaseTrailerLayout {
12032    element: AnyElement,
12033    bounds: Bounds<Pixels>,
12034}
12035
12036pub(crate) struct PositionMap {
12037    pub size: Size<Pixels>,
12038    pub line_height: Pixels,
12039    pub scroll_position: gpui::Point<ScrollOffset>,
12040    pub scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
12041    pub scroll_max: gpui::Point<ScrollOffset>,
12042    pub em_width: Pixels,
12043    pub em_advance: Pixels,
12044    pub em_layout_width: Pixels,
12045    pub visible_row_range: Range<DisplayRow>,
12046    pub line_layouts: Vec<LineWithInvisibles>,
12047    pub snapshot: EditorSnapshot,
12048    pub text_align: TextAlign,
12049    pub content_width: Pixels,
12050    pub text_hitbox: Hitbox,
12051    pub gutter_hitbox: Hitbox,
12052    pub inline_blame_bounds: Option<(Bounds<Pixels>, BufferId, BlameEntry)>,
12053    pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
12054    pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
12055}
12056
12057#[derive(Debug, Copy, Clone)]
12058pub struct PointForPosition {
12059    pub previous_valid: DisplayPoint,
12060    pub next_valid: DisplayPoint,
12061    pub nearest_valid: DisplayPoint,
12062    pub exact_unclipped: DisplayPoint,
12063    pub column_overshoot_after_line_end: u32,
12064}
12065
12066impl PointForPosition {
12067    pub fn as_valid(&self) -> Option<DisplayPoint> {
12068        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
12069            Some(self.previous_valid)
12070        } else {
12071            None
12072        }
12073    }
12074
12075    pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
12076        let Some(valid_point) = self.as_valid() else {
12077            return false;
12078        };
12079        let range = selection.range();
12080
12081        let candidate_row = valid_point.row();
12082        let candidate_col = valid_point.column();
12083
12084        let start_row = range.start.row();
12085        let start_col = range.start.column();
12086        let end_row = range.end.row();
12087        let end_col = range.end.column();
12088
12089        if candidate_row < start_row || candidate_row > end_row {
12090            false
12091        } else if start_row == end_row {
12092            candidate_col >= start_col && candidate_col < end_col
12093        } else if candidate_row == start_row {
12094            candidate_col >= start_col
12095        } else if candidate_row == end_row {
12096            candidate_col < end_col
12097        } else {
12098            true
12099        }
12100    }
12101}
12102
12103impl PositionMap {
12104    pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
12105        let text_bounds = self.text_hitbox.bounds;
12106        let scroll_position = self.snapshot.scroll_position();
12107        let position = position - text_bounds.origin;
12108        let y = position.y.max(px(0.)).min(self.size.height);
12109        let x = position.x + (scroll_position.x as f32 * self.em_layout_width);
12110        let row = ((y / self.line_height) as f64 + scroll_position.y) as u32;
12111
12112        let (column, x_overshoot_after_line_end) = if let Some(line) = self
12113            .line_layouts
12114            .get(row as usize - scroll_position.y as usize)
12115        {
12116            let alignment_offset = line.alignment_offset(self.text_align, self.content_width);
12117            let x_relative_to_text = x - alignment_offset;
12118            if let Some(ix) = line.index_for_x(x_relative_to_text) {
12119                (ix as u32, px(0.))
12120            } else {
12121                (line.len as u32, px(0.).max(x_relative_to_text - line.width))
12122            }
12123        } else {
12124            (0, x)
12125        };
12126
12127        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
12128        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
12129        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
12130
12131        let nearest_valid = if previous_valid == next_valid {
12132            previous_valid
12133        } else {
12134            match self.snapshot.inlay_bias_at(exact_unclipped) {
12135                Some(Bias::Left) => next_valid,
12136                Some(Bias::Right) => previous_valid,
12137                None => previous_valid,
12138            }
12139        };
12140
12141        let column_overshoot_after_line_end =
12142            (x_overshoot_after_line_end / self.em_layout_width) as u32;
12143        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
12144        PointForPosition {
12145            previous_valid,
12146            next_valid,
12147            nearest_valid,
12148            exact_unclipped,
12149            column_overshoot_after_line_end,
12150        }
12151    }
12152
12153    fn point_for_position_on_line(
12154        &self,
12155        position: gpui::Point<Pixels>,
12156        row: DisplayRow,
12157        line: &LineWithInvisibles,
12158    ) -> PointForPosition {
12159        let text_bounds = self.text_hitbox.bounds;
12160        let scroll_position = self.snapshot.scroll_position();
12161        let position = position - text_bounds.origin;
12162        let x = position.x + (scroll_position.x as f32 * self.em_layout_width);
12163
12164        let alignment_offset = line.alignment_offset(self.text_align, self.content_width);
12165        let x_relative_to_text = x - alignment_offset;
12166        let (column, x_overshoot_after_line_end) =
12167            if let Some(ix) = line.index_for_x(x_relative_to_text) {
12168                (ix as u32, px(0.))
12169            } else {
12170                (line.len as u32, px(0.).max(x_relative_to_text - line.width))
12171            };
12172
12173        let mut exact_unclipped = DisplayPoint::new(row, column);
12174        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
12175        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
12176
12177        let nearest_valid = if previous_valid == next_valid {
12178            previous_valid
12179        } else {
12180            match self.snapshot.inlay_bias_at(exact_unclipped) {
12181                Some(Bias::Left) => next_valid,
12182                Some(Bias::Right) => previous_valid,
12183                None => previous_valid,
12184            }
12185        };
12186
12187        let column_overshoot_after_line_end =
12188            (x_overshoot_after_line_end / self.em_layout_width) as u32;
12189        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
12190        PointForPosition {
12191            previous_valid,
12192            next_valid,
12193            nearest_valid,
12194            exact_unclipped,
12195            column_overshoot_after_line_end,
12196        }
12197    }
12198}
12199
12200pub(crate) struct BlockLayout {
12201    pub(crate) id: BlockId,
12202    pub(crate) x_offset: Pixels,
12203    pub(crate) row: Option<DisplayRow>,
12204    pub(crate) element: AnyElement,
12205    pub(crate) available_space: Size<AvailableSpace>,
12206    pub(crate) style: BlockStyle,
12207    pub(crate) overlaps_gutter: bool,
12208    pub(crate) is_buffer_header: bool,
12209}
12210
12211pub fn layout_line(
12212    row: DisplayRow,
12213    snapshot: &EditorSnapshot,
12214    style: &EditorStyle,
12215    text_width: Pixels,
12216    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
12217    window: &mut Window,
12218    cx: &mut App,
12219) -> LineWithInvisibles {
12220    let use_tree_sitter =
12221        !snapshot.semantic_tokens_enabled || snapshot.use_tree_sitter_for_syntax(row, cx);
12222    let language_aware = LanguageAwareStyling {
12223        tree_sitter: use_tree_sitter,
12224        diagnostics: true,
12225    };
12226    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), language_aware, style);
12227    LineWithInvisibles::from_chunks(
12228        chunks,
12229        style,
12230        MAX_LINE_LEN,
12231        1,
12232        &snapshot.mode,
12233        text_width,
12234        is_row_soft_wrapped,
12235        &[],
12236        window,
12237        cx,
12238    )
12239    .pop()
12240    .unwrap()
12241}
12242
12243#[derive(Debug, Clone)]
12244pub struct IndentGuideLayout {
12245    origin: gpui::Point<Pixels>,
12246    length: Pixels,
12247    single_indent_width: Pixels,
12248    display_row_range: Range<DisplayRow>,
12249    depth: u32,
12250    active: bool,
12251    settings: IndentGuideSettings,
12252}
12253
12254enum NavigationOverlayPaintCommand {
12255    Label(NavigationLabelLayout),
12256}
12257
12258struct NavigationLabelLayout {
12259    element: AnyElement,
12260    #[cfg_attr(not(test), allow(dead_code))]
12261    origin: gpui::Point<Pixels>,
12262}
12263
12264struct NavigationOverlayLayoutContext<'a> {
12265    display_snapshot: &'a DisplaySnapshot,
12266    visible_display_row_range: &'a Range<DisplayRow>,
12267    line_layouts: &'a [LineWithInvisibles],
12268    text_align: TextAlign,
12269    content_width: Pixels,
12270    content_origin: gpui::Point<Pixels>,
12271    scroll_position: gpui::Point<ScrollOffset>,
12272    scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
12273    line_height: Pixels,
12274    editor_font: Font,
12275    editor_font_size: Pixels,
12276}
12277
12278const LABEL_LINE_HEIGHT_PADDING_PX: f32 = 2.0;
12279
12280pub struct CursorLayout {
12281    origin: gpui::Point<Pixels>,
12282    block_width: Pixels,
12283    line_height: Pixels,
12284    color: Hsla,
12285    shape: CursorShape,
12286    block_text: Option<ShapedLine>,
12287    cursor_name: Option<AnyElement>,
12288}
12289
12290#[derive(Debug)]
12291pub struct CursorName {
12292    string: SharedString,
12293    color: Hsla,
12294    is_top_row: bool,
12295}
12296
12297impl CursorLayout {
12298    pub fn new(
12299        origin: gpui::Point<Pixels>,
12300        block_width: Pixels,
12301        line_height: Pixels,
12302        color: Hsla,
12303        shape: CursorShape,
12304        block_text: Option<ShapedLine>,
12305    ) -> CursorLayout {
12306        CursorLayout {
12307            origin,
12308            block_width,
12309            line_height,
12310            color,
12311            shape,
12312            block_text,
12313            cursor_name: None,
12314        }
12315    }
12316
12317    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
12318        Bounds {
12319            origin: self.origin + origin,
12320            size: size(self.block_width, self.line_height),
12321        }
12322    }
12323
12324    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
12325        match self.shape {
12326            CursorShape::Bar => Bounds {
12327                origin: self.origin + origin,
12328                size: size(px(2.0), self.line_height),
12329            },
12330            CursorShape::Block | CursorShape::Hollow => Bounds {
12331                origin: self.origin + origin,
12332                size: size(self.block_width, self.line_height),
12333            },
12334            CursorShape::Underline => Bounds {
12335                origin: self.origin
12336                    + origin
12337                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
12338                size: size(self.block_width, px(2.0)),
12339            },
12340        }
12341    }
12342
12343    pub fn layout(
12344        &mut self,
12345        origin: gpui::Point<Pixels>,
12346        cursor_name: Option<CursorName>,
12347        window: &mut Window,
12348        cx: &mut App,
12349    ) {
12350        if let Some(cursor_name) = cursor_name {
12351            let bounds = self.bounds(origin);
12352            let text_size = self.line_height / 1.5;
12353
12354            let name_origin = if cursor_name.is_top_row {
12355                point(bounds.right() - px(1.), bounds.top())
12356            } else {
12357                match self.shape {
12358                    CursorShape::Bar => point(
12359                        bounds.right() - px(2.),
12360                        bounds.top() - text_size / 2. - px(1.),
12361                    ),
12362                    _ => point(
12363                        bounds.right() - px(1.),
12364                        bounds.top() - text_size / 2. - px(1.),
12365                    ),
12366                }
12367            };
12368            let mut name_element = div()
12369                .bg(self.color)
12370                .text_size(text_size)
12371                .px_0p5()
12372                .line_height(text_size + px(LABEL_LINE_HEIGHT_PADDING_PX))
12373                .text_color(cursor_name.color)
12374                .child(cursor_name.string)
12375                .into_any_element();
12376
12377            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
12378
12379            self.cursor_name = Some(name_element);
12380        }
12381    }
12382
12383    pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
12384        let bounds = self.bounds(origin);
12385
12386        //Draw background or border quad
12387        let cursor = if matches!(self.shape, CursorShape::Hollow) {
12388            outline(bounds, self.color, BorderStyle::Solid)
12389        } else {
12390            fill(bounds, self.color)
12391        };
12392
12393        if let Some(name) = &mut self.cursor_name {
12394            name.paint(window, cx);
12395        }
12396
12397        window.paint_quad(cursor);
12398
12399        if let Some(block_text) = &self.block_text {
12400            block_text
12401                .paint(
12402                    self.origin + origin,
12403                    self.line_height,
12404                    TextAlign::Left,
12405                    None,
12406                    window,
12407                    cx,
12408                )
12409                .log_err();
12410        }
12411    }
12412
12413    pub fn shape(&self) -> CursorShape {
12414        self.shape
12415    }
12416}
12417
12418#[derive(Debug)]
12419pub struct HighlightedRange {
12420    pub start_y: Pixels,
12421    pub line_height: Pixels,
12422    pub lines: Vec<HighlightedRangeLine>,
12423    pub color: Hsla,
12424    pub corner_radius: Pixels,
12425}
12426
12427#[derive(Debug)]
12428pub struct HighlightedRangeLine {
12429    pub start_x: Pixels,
12430    pub end_x: Pixels,
12431}
12432
12433impl HighlightedRange {
12434    pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
12435        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
12436            self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
12437            self.paint_lines(
12438                self.start_y + self.line_height,
12439                &self.lines[1..],
12440                fill,
12441                bounds,
12442                window,
12443            );
12444        } else {
12445            self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
12446        }
12447    }
12448
12449    fn paint_lines(
12450        &self,
12451        start_y: Pixels,
12452        lines: &[HighlightedRangeLine],
12453        fill: bool,
12454        _bounds: Bounds<Pixels>,
12455        window: &mut Window,
12456    ) {
12457        if lines.is_empty() {
12458            return;
12459        }
12460
12461        let first_line = lines.first().unwrap();
12462        let last_line = lines.last().unwrap();
12463
12464        let first_top_left = point(first_line.start_x, start_y);
12465        let first_top_right = point(first_line.end_x, start_y);
12466
12467        let curve_height = point(Pixels::ZERO, self.corner_radius);
12468        let curve_width = |start_x: Pixels, end_x: Pixels| {
12469            let max = (end_x - start_x) / 2.;
12470            let width = if max < self.corner_radius {
12471                max
12472            } else {
12473                self.corner_radius
12474            };
12475
12476            point(width, Pixels::ZERO)
12477        };
12478
12479        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
12480        let mut builder = if fill {
12481            gpui::PathBuilder::fill()
12482        } else {
12483            gpui::PathBuilder::stroke(px(1.))
12484        };
12485        builder.move_to(first_top_right - top_curve_width);
12486        builder.curve_to(first_top_right + curve_height, first_top_right);
12487
12488        let mut iter = lines.iter().enumerate().peekable();
12489        while let Some((ix, line)) = iter.next() {
12490            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
12491
12492            if let Some((_, next_line)) = iter.peek() {
12493                let next_top_right = point(next_line.end_x, bottom_right.y);
12494
12495                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
12496                    Ordering::Equal => {
12497                        builder.line_to(bottom_right);
12498                    }
12499                    Ordering::Less => {
12500                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
12501                        builder.line_to(bottom_right - curve_height);
12502                        if self.corner_radius > Pixels::ZERO {
12503                            builder.curve_to(bottom_right - curve_width, bottom_right);
12504                        }
12505                        builder.line_to(next_top_right + curve_width);
12506                        if self.corner_radius > Pixels::ZERO {
12507                            builder.curve_to(next_top_right + curve_height, next_top_right);
12508                        }
12509                    }
12510                    Ordering::Greater => {
12511                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
12512                        builder.line_to(bottom_right - curve_height);
12513                        if self.corner_radius > Pixels::ZERO {
12514                            builder.curve_to(bottom_right + curve_width, bottom_right);
12515                        }
12516                        builder.line_to(next_top_right - curve_width);
12517                        if self.corner_radius > Pixels::ZERO {
12518                            builder.curve_to(next_top_right + curve_height, next_top_right);
12519                        }
12520                    }
12521                }
12522            } else {
12523                let curve_width = curve_width(line.start_x, line.end_x);
12524                builder.line_to(bottom_right - curve_height);
12525                if self.corner_radius > Pixels::ZERO {
12526                    builder.curve_to(bottom_right - curve_width, bottom_right);
12527                }
12528
12529                let bottom_left = point(line.start_x, bottom_right.y);
12530                builder.line_to(bottom_left + curve_width);
12531                if self.corner_radius > Pixels::ZERO {
12532                    builder.curve_to(bottom_left - curve_height, bottom_left);
12533                }
12534            }
12535        }
12536
12537        if first_line.start_x > last_line.start_x {
12538            let curve_width = curve_width(last_line.start_x, first_line.start_x);
12539            let second_top_left = point(last_line.start_x, start_y + self.line_height);
12540            builder.line_to(second_top_left + curve_height);
12541            if self.corner_radius > Pixels::ZERO {
12542                builder.curve_to(second_top_left + curve_width, second_top_left);
12543            }
12544            let first_bottom_left = point(first_line.start_x, second_top_left.y);
12545            builder.line_to(first_bottom_left - curve_width);
12546            if self.corner_radius > Pixels::ZERO {
12547                builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
12548            }
12549        }
12550
12551        builder.line_to(first_top_left + curve_height);
12552        if self.corner_radius > Pixels::ZERO {
12553            builder.curve_to(first_top_left + top_curve_width, first_top_left);
12554        }
12555        builder.line_to(first_top_right - top_curve_width);
12556
12557        if let Ok(path) = builder.build() {
12558            window.paint_path(path, self.color);
12559        }
12560    }
12561}
12562
12563pub(crate) struct StickyHeader {
12564    pub sticky_row: DisplayRow,
12565    pub start_point: Point,
12566    pub offset: ScrollOffset,
12567}
12568
12569enum CursorPopoverType {
12570    CodeContextMenu,
12571    EditPrediction,
12572}
12573
12574pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12575    (delta.pow(1.2) / 100.0).min(px(3.0)).into()
12576}
12577
12578fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12579    (delta.pow(1.2) / 300.0).into()
12580}
12581
12582pub fn register_action<T: Action>(
12583    editor: &Entity<Editor>,
12584    window: &mut Window,
12585    listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
12586) {
12587    let editor = editor.clone();
12588    window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
12589        let action = action.downcast_ref().unwrap();
12590        if phase == DispatchPhase::Bubble {
12591            editor.update(cx, |editor, cx| {
12592                listener(editor, action, window, cx);
12593            })
12594        }
12595    })
12596}
12597
12598/// Shared between `prepaint` and `compute_auto_height_layout` to ensure
12599/// both full and auto-height editors compute wrap widths consistently.
12600fn calculate_wrap_width(
12601    soft_wrap: SoftWrap,
12602    editor_width: Pixels,
12603    em_width: Pixels,
12604) -> Option<Pixels> {
12605    let wrap_width_for = |column: u32| (column as f32 * em_width).ceil();
12606
12607    match soft_wrap {
12608        SoftWrap::GitDiff => None,
12609        SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
12610        SoftWrap::EditorWidth => Some(editor_width),
12611        SoftWrap::Bounded(column) => Some(editor_width.min(wrap_width_for(column))),
12612    }
12613}
12614
12615fn compute_auto_height_layout(
12616    editor: &mut Editor,
12617    min_lines: usize,
12618    max_lines: Option<usize>,
12619    known_dimensions: Size<Option<Pixels>>,
12620    available_width: AvailableSpace,
12621    window: &mut Window,
12622    cx: &mut Context<Editor>,
12623) -> Option<Size<Pixels>> {
12624    let width = known_dimensions.width.or({
12625        if let AvailableSpace::Definite(available_width) = available_width {
12626            Some(available_width)
12627        } else {
12628            None
12629        }
12630    })?;
12631    if let Some(height) = known_dimensions.height {
12632        return Some(size(width, height));
12633    }
12634
12635    let style = editor.style.as_ref().unwrap();
12636    let font_id = window.text_system().resolve_font(&style.text.font());
12637    let font_size = style.text.font_size.to_pixels(window.rem_size());
12638    let line_height = style.text.line_height_in_pixels(window.rem_size());
12639    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
12640
12641    let mut snapshot = editor.snapshot(window, cx);
12642    let gutter_dimensions = snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
12643
12644    editor.gutter_dimensions = gutter_dimensions;
12645    let text_width = width - gutter_dimensions.width;
12646    let overscroll = size(em_width, px(0.));
12647
12648    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
12649    let wrap_width = calculate_wrap_width(editor.soft_wrap_mode(cx), editor_width, em_width)
12650        .map(|width| width.min(editor_width));
12651    if wrap_width.is_some() && editor.set_wrap_width(wrap_width, cx) {
12652        snapshot = editor.snapshot(window, cx);
12653    }
12654
12655    let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
12656
12657    let min_height = line_height * min_lines as f32;
12658    let content_height = scroll_height.max(min_height);
12659
12660    let final_height = if let Some(max_lines) = max_lines {
12661        let max_height = line_height * max_lines as f32;
12662        content_height.min(max_height)
12663    } else {
12664        content_height
12665    };
12666
12667    Some(size(width, final_height))
12668}
12669
12670#[cfg(test)]
12671mod tests {
12672    use super::*;
12673    use crate::{
12674        Editor, HighlightKey, MultiBuffer, NavigationOverlayKey, NavigationOverlayLabel,
12675        NavigationTargetOverlay, SelectionEffects,
12676        display_map::{BlockPlacement, BlockProperties},
12677        editor_tests::{init_test, update_test_language_settings},
12678    };
12679    use gpui::{TestAppContext, VisualTestContext};
12680    use language::{Buffer, language_settings, tree_sitter_python};
12681    use log::info;
12682    use rand::{RngCore, rngs::StdRng};
12683    use std::num::NonZeroU32;
12684    use util::test::sample_text;
12685
12686    enum PrimaryNavigationOverlay {}
12687
12688    const PRIMARY_NAVIGATION_OVERLAY_KEY: NavigationOverlayKey =
12689        NavigationOverlayKey::unique::<PrimaryNavigationOverlay>();
12690
12691    fn navigation_overlay(
12692        label_text: &'static str,
12693        target_range: Range<Anchor>,
12694        covered_text_range: Option<Range<Anchor>>,
12695    ) -> NavigationTargetOverlay {
12696        NavigationTargetOverlay {
12697            target_range,
12698            label: NavigationOverlayLabel {
12699                text: SharedString::from(label_text),
12700                text_color: Hsla::black(),
12701                x_offset: Pixels::ZERO,
12702                scale_factor: 1.0,
12703            },
12704            covered_text_range,
12705        }
12706    }
12707
12708    fn navigation_label_layouts(state: &EditorLayout) -> Vec<&NavigationLabelLayout> {
12709        state
12710            .navigation_overlay_paint_commands
12711            .iter()
12712            .map(|command| match command {
12713                NavigationOverlayPaintCommand::Label(label) => label,
12714            })
12715            .collect()
12716    }
12717
12718    const fn placeholder_hitbox() -> Hitbox {
12719        use gpui::HitboxId;
12720        let zero_bounds = Bounds {
12721            origin: point(Pixels::ZERO, Pixels::ZERO),
12722            size: Size {
12723                width: Pixels::ZERO,
12724                height: Pixels::ZERO,
12725            },
12726        };
12727
12728        Hitbox {
12729            id: HitboxId::placeholder(),
12730            bounds: zero_bounds,
12731            content_mask: ContentMask {
12732                bounds: zero_bounds,
12733            },
12734            behavior: HitboxBehavior::Normal,
12735        }
12736    }
12737
12738    fn test_gutter(line_height: Pixels, snapshot: &EditorSnapshot) -> Gutter<'_> {
12739        const DIMENSIONS: GutterDimensions = GutterDimensions {
12740            left_padding: Pixels::ZERO,
12741            right_padding: Pixels::ZERO,
12742            width: px(30.0),
12743            margin: Pixels::ZERO,
12744            git_blame_entries_width: None,
12745        };
12746        const EMPTY_ROW_INFO: RowInfo = RowInfo {
12747            buffer_id: None,
12748            buffer_row: None,
12749            multibuffer_row: None,
12750            diff_status: None,
12751            expand_info: None,
12752            wrapped_buffer_row: None,
12753        };
12754
12755        const fn row_info(row: u32) -> RowInfo {
12756            RowInfo {
12757                buffer_row: Some(row),
12758                ..EMPTY_ROW_INFO
12759            }
12760        }
12761
12762        const ROW_INFOS: [RowInfo; 6] = [
12763            row_info(0),
12764            row_info(1),
12765            row_info(2),
12766            row_info(3),
12767            row_info(4),
12768            row_info(5),
12769        ];
12770
12771        const HITBOX: Hitbox = placeholder_hitbox();
12772        Gutter {
12773            line_height,
12774            range: DisplayRow(0)..DisplayRow(6),
12775            scroll_position: gpui::Point::default(),
12776            dimensions: &DIMENSIONS,
12777            hitbox: &HITBOX,
12778            snapshot: snapshot,
12779            row_infos: &ROW_INFOS,
12780        }
12781    }
12782
12783    #[gpui::test]
12784    async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
12785        init_test(cx, |_| {});
12786        let window = cx.add_window(|window, cx| {
12787            let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12788            let mut editor = Editor::new(
12789                EditorMode::AutoHeight {
12790                    min_lines: 1,
12791                    max_lines: None,
12792                },
12793                buffer,
12794                None,
12795                window,
12796                cx,
12797            );
12798            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12799            editor
12800        });
12801        let cx = &mut VisualTestContext::from_window(*window, cx);
12802        let editor = window.root(cx).unwrap();
12803        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12804
12805        for x in 1..=100 {
12806            let (_, state) = cx.draw(
12807                Default::default(),
12808                size(px(200. + 0.13 * x as f32), px(500.)),
12809                |_, _| EditorElement::new(&editor, style.clone()),
12810            );
12811
12812            assert!(
12813                state.position_map.scroll_max.x == 0.,
12814                "Soft wrapped editor should have no horizontal scrolling!"
12815            );
12816        }
12817    }
12818
12819    #[gpui::test]
12820    async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
12821        init_test(cx, |_| {});
12822        let window = cx.add_window(|window, cx| {
12823            let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12824            let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
12825            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12826            editor
12827        });
12828        let cx = &mut VisualTestContext::from_window(*window, cx);
12829        let editor = window.root(cx).unwrap();
12830        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12831
12832        for x in 1..=100 {
12833            let (_, state) = cx.draw(
12834                Default::default(),
12835                size(px(200. + 0.13 * x as f32), px(500.)),
12836                |_, _| EditorElement::new(&editor, style.clone()),
12837            );
12838
12839            assert!(
12840                state.position_map.scroll_max.x == 0.,
12841                "Soft wrapped editor should have no horizontal scrolling!"
12842            );
12843        }
12844    }
12845
12846    #[gpui::test]
12847    fn test_navigation_overlay_covered_text_highlights_are_replaced(cx: &mut TestAppContext) {
12848        init_test(cx, |_| {});
12849        let window = cx.add_window(|window, cx| {
12850            let buffer = MultiBuffer::build_simple("overlay replacement", cx);
12851            Editor::new(EditorMode::full(), buffer, None, window, cx)
12852        });
12853        let editor = window.root(cx).unwrap();
12854
12855        editor.update(cx, |editor, cx| {
12856            let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
12857            let target_start = buffer_snapshot.anchor_after(Point::new(0, 0));
12858            let target_end = buffer_snapshot.anchor_after(Point::new(0, 7));
12859            let covered_text_end = buffer_snapshot.anchor_after(Point::new(0, 2));
12860
12861            editor.set_navigation_overlays(
12862                PRIMARY_NAVIGATION_OVERLAY_KEY,
12863                vec![navigation_overlay(
12864                    "ov",
12865                    target_start..target_end,
12866                    Some(target_start..covered_text_end),
12867                )],
12868                cx,
12869            );
12870            assert!(
12871                editor
12872                    .text_highlights(
12873                        HighlightKey::NavigationOverlay(PRIMARY_NAVIGATION_OVERLAY_KEY),
12874                        cx,
12875                    )
12876                    .is_some()
12877            );
12878
12879            editor.set_navigation_overlays(
12880                PRIMARY_NAVIGATION_OVERLAY_KEY,
12881                vec![navigation_overlay("ov", target_start..target_end, None)],
12882                cx,
12883            );
12884            assert!(
12885                editor
12886                    .text_highlights(
12887                        HighlightKey::NavigationOverlay(PRIMARY_NAVIGATION_OVERLAY_KEY),
12888                        cx,
12889                    )
12890                    .is_none()
12891            );
12892        });
12893    }
12894
12895    #[gpui::test]
12896    async fn test_navigation_overlay_repositions_when_editor_width_changes(
12897        cx: &mut TestAppContext,
12898    ) {
12899        init_test(cx, |_| {});
12900        let text = "jump target overlay ".repeat(16);
12901        let window = cx.add_window(|window, cx| {
12902            let buffer = MultiBuffer::build_simple(&text, cx);
12903            let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
12904            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12905            editor
12906        });
12907        let cx = &mut VisualTestContext::from_window(*window, cx);
12908        let editor = window.root(cx).unwrap();
12909
12910        editor.update(cx, |editor, cx| {
12911            let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
12912            let target_start = buffer_snapshot.anchor_after(Point::new(0, 30));
12913            let target_end = buffer_snapshot.anchor_after(Point::new(0, 40));
12914
12915            editor.set_navigation_overlays(
12916                PRIMARY_NAVIGATION_OVERLAY_KEY,
12917                vec![navigation_overlay("jj", target_start..target_end, None)],
12918                cx,
12919            );
12920        });
12921
12922        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12923        let (_, wide_state) = cx.draw(Default::default(), size(px(520.), px(260.)), |_, _| {
12924            EditorElement::new(&editor, style.clone())
12925        });
12926        let (_, narrow_state) = cx.draw(Default::default(), size(px(140.), px(260.)), |_, _| {
12927            EditorElement::new(&editor, style.clone())
12928        });
12929
12930        let wide_label_layouts = navigation_label_layouts(&wide_state);
12931        let narrow_label_layouts = navigation_label_layouts(&narrow_state);
12932
12933        assert_eq!(wide_label_layouts.len(), 1);
12934        assert_eq!(narrow_label_layouts.len(), 1);
12935
12936        let wide_label_origin = wide_label_layouts[0].origin;
12937        let narrow_label_origin = narrow_label_layouts[0].origin;
12938
12939        assert!(
12940            narrow_label_origin.y > wide_label_origin.y,
12941            "expected inline label to move to a later wrapped row when the editor narrows"
12942        );
12943        assert!(
12944            narrow_label_origin.x < wide_label_origin.x,
12945            "expected inline label to recompute its horizontal position for the wrapped row"
12946        );
12947    }
12948
12949    #[gpui::test]
12950    fn test_layout_line_numbers(cx: &mut TestAppContext) {
12951        init_test(cx, |_| {});
12952        let window = cx.add_window(|window, cx| {
12953            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12954            Editor::new(EditorMode::full(), buffer, None, window, cx)
12955        });
12956
12957        let editor = window.root(cx).unwrap();
12958        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12959        let line_height = window
12960            .update(cx, |_, window, _| {
12961                style.text.line_height_in_pixels(window.rem_size())
12962            })
12963            .unwrap();
12964        let element = EditorElement::new(&editor, style);
12965        let snapshot = window
12966            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12967            .unwrap();
12968
12969        let layouts = cx
12970            .update_window(*window, |_, window, cx| {
12971                element.layout_line_numbers(
12972                    &test_gutter(line_height, &snapshot),
12973                    &BTreeMap::default(),
12974                    Some(DisplayRow(0)),
12975                    window,
12976                    cx,
12977                )
12978            })
12979            .unwrap();
12980        assert_eq!(layouts.len(), 6);
12981
12982        let relative_rows = window
12983            .update(cx, |editor, window, cx| {
12984                let snapshot = editor.snapshot(window, cx);
12985                snapshot.calculate_relative_line_numbers(
12986                    &(DisplayRow(0)..DisplayRow(6)),
12987                    DisplayRow(3),
12988                    false,
12989                )
12990            })
12991            .unwrap();
12992        assert_eq!(relative_rows[&DisplayRow(0)], 3);
12993        assert_eq!(relative_rows[&DisplayRow(1)], 2);
12994        assert_eq!(relative_rows[&DisplayRow(2)], 1);
12995        // current line has no relative number
12996        assert!(!relative_rows.contains_key(&DisplayRow(3)));
12997        assert_eq!(relative_rows[&DisplayRow(4)], 1);
12998        assert_eq!(relative_rows[&DisplayRow(5)], 2);
12999
13000        // works if cursor is before screen
13001        let relative_rows = window
13002            .update(cx, |editor, window, cx| {
13003                let snapshot = editor.snapshot(window, cx);
13004                snapshot.calculate_relative_line_numbers(
13005                    &(DisplayRow(3)..DisplayRow(6)),
13006                    DisplayRow(1),
13007                    false,
13008                )
13009            })
13010            .unwrap();
13011        assert_eq!(relative_rows.len(), 3);
13012        assert_eq!(relative_rows[&DisplayRow(3)], 2);
13013        assert_eq!(relative_rows[&DisplayRow(4)], 3);
13014        assert_eq!(relative_rows[&DisplayRow(5)], 4);
13015
13016        // works if cursor is after screen
13017        let relative_rows = window
13018            .update(cx, |editor, window, cx| {
13019                let snapshot = editor.snapshot(window, cx);
13020                snapshot.calculate_relative_line_numbers(
13021                    &(DisplayRow(0)..DisplayRow(3)),
13022                    DisplayRow(6),
13023                    false,
13024                )
13025            })
13026            .unwrap();
13027        assert_eq!(relative_rows.len(), 3);
13028        assert_eq!(relative_rows[&DisplayRow(0)], 5);
13029        assert_eq!(relative_rows[&DisplayRow(1)], 4);
13030        assert_eq!(relative_rows[&DisplayRow(2)], 3);
13031
13032        let gutter = Gutter {
13033            row_infos: &(0..6)
13034                .map(|row| RowInfo {
13035                    buffer_row: Some(row),
13036                    diff_status: (row == DELETED_LINE).then(|| {
13037                        DiffHunkStatus::deleted(
13038                            buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
13039                        )
13040                    }),
13041                    ..Default::default()
13042                })
13043                .collect::<Vec<_>>(),
13044            ..test_gutter(line_height, &snapshot)
13045        };
13046
13047        const DELETED_LINE: u32 = 3;
13048        let layouts = cx
13049            .update_window(*window, |_, window, cx| {
13050                element.layout_line_numbers(
13051                    &gutter,
13052                    &BTreeMap::default(),
13053                    Some(DisplayRow(0)),
13054                    window,
13055                    cx,
13056                )
13057            })
13058            .unwrap();
13059        assert_eq!(layouts.len(), 5,);
13060        assert!(
13061            layouts.get(&MultiBufferRow(DELETED_LINE)).is_none(),
13062            "Deleted line should not have a line number"
13063        );
13064    }
13065
13066    #[gpui::test]
13067    async fn test_layout_line_numbers_with_folded_lines(cx: &mut TestAppContext) {
13068        init_test(cx, |_| {});
13069
13070        let python_lang = languages::language("python", tree_sitter_python::LANGUAGE.into());
13071
13072        let window = cx.add_window(|window, cx| {
13073            let buffer = cx.new(|cx| {
13074                Buffer::local(
13075                    indoc::indoc! {"
13076                        fn test() -> int {
13077                            return 2;
13078                        }
13079
13080                        fn another_test() -> int {
13081                            # This is a very peculiar method that is hard to grasp.
13082                            return 4;
13083                        }
13084                    "},
13085                    cx,
13086                )
13087                .with_language(python_lang, cx)
13088            });
13089
13090            let buffer = MultiBuffer::build_from_buffer(buffer, cx);
13091            Editor::new(EditorMode::full(), buffer, None, window, cx)
13092        });
13093
13094        let editor = window.root(cx).unwrap();
13095        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
13096        let line_height = window
13097            .update(cx, |_, window, _| {
13098                style.text.line_height_in_pixels(window.rem_size())
13099            })
13100            .unwrap();
13101        let element = EditorElement::new(&editor, style);
13102        let snapshot = window
13103            .update(cx, |editor, window, cx| {
13104                editor.fold_at(MultiBufferRow(0), window, cx);
13105                editor.snapshot(window, cx)
13106            })
13107            .unwrap();
13108
13109        let layouts = cx
13110            .update_window(*window, |_, window, cx| {
13111                element.layout_line_numbers(
13112                    &test_gutter(line_height, &snapshot),
13113                    &BTreeMap::default(),
13114                    Some(DisplayRow(3)),
13115                    window,
13116                    cx,
13117                )
13118            })
13119            .unwrap();
13120        assert_eq!(layouts.len(), 6);
13121
13122        let relative_rows = window
13123            .update(cx, |editor, window, cx| {
13124                let snapshot = editor.snapshot(window, cx);
13125                snapshot.calculate_relative_line_numbers(
13126                    &(DisplayRow(0)..DisplayRow(6)),
13127                    DisplayRow(3),
13128                    false,
13129                )
13130            })
13131            .unwrap();
13132        assert_eq!(relative_rows[&DisplayRow(0)], 3);
13133        assert_eq!(relative_rows[&DisplayRow(1)], 2);
13134        assert_eq!(relative_rows[&DisplayRow(2)], 1);
13135        // current line has no relative number
13136        assert!(!relative_rows.contains_key(&DisplayRow(3)));
13137        assert_eq!(relative_rows[&DisplayRow(4)], 1);
13138        assert_eq!(relative_rows[&DisplayRow(5)], 2);
13139    }
13140
13141    #[gpui::test]
13142    fn test_layout_line_numbers_wrapping(cx: &mut TestAppContext) {
13143        init_test(cx, |_| {});
13144        let window = cx.add_window(|window, cx| {
13145            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
13146            Editor::new(EditorMode::full(), buffer, None, window, cx)
13147        });
13148
13149        update_test_language_settings(cx, &|s| {
13150            s.defaults.preferred_line_length = Some(5_u32);
13151            s.defaults.soft_wrap = Some(language_settings::SoftWrap::Bounded);
13152        });
13153
13154        let editor = window.root(cx).unwrap();
13155        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
13156        let line_height = window
13157            .update(cx, |_, window, _| {
13158                style.text.line_height_in_pixels(window.rem_size())
13159            })
13160            .unwrap();
13161        let element = EditorElement::new(&editor, style);
13162        let snapshot = window
13163            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
13164            .unwrap();
13165
13166        let layouts = cx
13167            .update_window(*window, |_, window, cx| {
13168                element.layout_line_numbers(
13169                    &test_gutter(line_height, &snapshot),
13170                    &BTreeMap::default(),
13171                    Some(DisplayRow(0)),
13172                    window,
13173                    cx,
13174                )
13175            })
13176            .unwrap();
13177        assert_eq!(layouts.len(), 3);
13178
13179        let relative_rows = window
13180            .update(cx, |editor, window, cx| {
13181                let snapshot = editor.snapshot(window, cx);
13182                snapshot.calculate_relative_line_numbers(
13183                    &(DisplayRow(0)..DisplayRow(6)),
13184                    DisplayRow(3),
13185                    true,
13186                )
13187            })
13188            .unwrap();
13189
13190        assert_eq!(relative_rows[&DisplayRow(0)], 3);
13191        assert_eq!(relative_rows[&DisplayRow(1)], 2);
13192        assert_eq!(relative_rows[&DisplayRow(2)], 1);
13193        // current line has no relative number
13194        assert!(!relative_rows.contains_key(&DisplayRow(3)));
13195        assert_eq!(relative_rows[&DisplayRow(4)], 1);
13196        assert_eq!(relative_rows[&DisplayRow(5)], 2);
13197
13198        let layouts = cx
13199            .update_window(*window, |_, window, cx| {
13200                element.layout_line_numbers(
13201                    &Gutter {
13202                        row_infos: &(0..6)
13203                            .map(|row| RowInfo {
13204                                buffer_row: Some(row),
13205                                diff_status: Some(DiffHunkStatus::deleted(
13206                                    buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
13207                                )),
13208                                ..Default::default()
13209                            })
13210                            .collect::<Vec<_>>(),
13211                        ..test_gutter(line_height, &snapshot)
13212                    },
13213                    &BTreeMap::from_iter([(DisplayRow(0), LineHighlightSpec::default())]),
13214                    Some(DisplayRow(0)),
13215                    window,
13216                    cx,
13217                )
13218            })
13219            .unwrap();
13220        assert!(
13221            layouts.is_empty(),
13222            "Deleted lines should have no line number"
13223        );
13224
13225        let relative_rows = window
13226            .update(cx, |editor, window, cx| {
13227                let snapshot = editor.snapshot(window, cx);
13228                snapshot.calculate_relative_line_numbers(
13229                    &(DisplayRow(0)..DisplayRow(6)),
13230                    DisplayRow(3),
13231                    true,
13232                )
13233            })
13234            .unwrap();
13235
13236        // Deleted lines should still have relative numbers
13237        assert_eq!(relative_rows[&DisplayRow(0)], 3);
13238        assert_eq!(relative_rows[&DisplayRow(1)], 2);
13239        assert_eq!(relative_rows[&DisplayRow(2)], 1);
13240        // current line, even if deleted, has no relative number
13241        assert!(!relative_rows.contains_key(&DisplayRow(3)));
13242        assert_eq!(relative_rows[&DisplayRow(4)], 1);
13243        assert_eq!(relative_rows[&DisplayRow(5)], 2);
13244    }
13245
13246    #[gpui::test]
13247    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
13248        init_test(cx, |_| {});
13249
13250        let window = cx.add_window(|window, cx| {
13251            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
13252            Editor::new(EditorMode::full(), buffer, None, window, cx)
13253        });
13254        let cx = &mut VisualTestContext::from_window(*window, cx);
13255        let editor = window.root(cx).unwrap();
13256        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
13257
13258        window
13259            .update(cx, |editor, window, cx| {
13260                editor.cursor_offset_on_selection = true;
13261                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
13262                    s.select_ranges([
13263                        Point::new(0, 0)..Point::new(1, 0),
13264                        Point::new(3, 2)..Point::new(3, 3),
13265                        Point::new(5, 6)..Point::new(6, 0),
13266                    ]);
13267                });
13268            })
13269            .unwrap();
13270
13271        let (_, state) = cx.draw(
13272            point(px(500.), px(500.)),
13273            size(px(500.), px(500.)),
13274            |_, _| EditorElement::new(&editor, style),
13275        );
13276
13277        assert_eq!(state.selections.len(), 1);
13278        let local_selections = &state.selections[0].1;
13279        assert_eq!(local_selections.len(), 3);
13280        // moves cursor back one line
13281        assert_eq!(
13282            local_selections[0].head,
13283            DisplayPoint::new(DisplayRow(0), 6)
13284        );
13285        assert_eq!(
13286            local_selections[0].range,
13287            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
13288        );
13289
13290        // moves cursor back one column
13291        assert_eq!(
13292            local_selections[1].range,
13293            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
13294        );
13295        assert_eq!(
13296            local_selections[1].head,
13297            DisplayPoint::new(DisplayRow(3), 2)
13298        );
13299
13300        // leaves cursor on the max point
13301        assert_eq!(
13302            local_selections[2].range,
13303            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
13304        );
13305        assert_eq!(
13306            local_selections[2].head,
13307            DisplayPoint::new(DisplayRow(6), 0)
13308        );
13309
13310        // active lines does not include 1 (even though the range of the selection does)
13311        assert_eq!(
13312            state.active_rows.keys().cloned().collect::<Vec<_>>(),
13313            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
13314        );
13315    }
13316
13317    #[gpui::test]
13318    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
13319        init_test(cx, |_| {});
13320
13321        let window = cx.add_window(|window, cx| {
13322            let buffer = MultiBuffer::build_simple("", cx);
13323            Editor::new(EditorMode::full(), buffer, None, window, cx)
13324        });
13325        let cx = &mut VisualTestContext::from_window(*window, cx);
13326        let editor = window.root(cx).unwrap();
13327        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
13328        window
13329            .update(cx, |editor, window, cx| {
13330                editor.set_placeholder_text("hello", window, cx);
13331                editor.insert_blocks(
13332                    [BlockProperties {
13333                        style: BlockStyle::Fixed,
13334                        placement: BlockPlacement::Above(Anchor::Min),
13335                        height: Some(3),
13336                        render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
13337                        priority: 0,
13338                    }],
13339                    None,
13340                    cx,
13341                );
13342
13343                // Blur the editor so that it displays placeholder text.
13344                window.blur();
13345            })
13346            .unwrap();
13347
13348        let (_, state) = cx.draw(
13349            point(px(500.), px(500.)),
13350            size(px(500.), px(500.)),
13351            |_, _| EditorElement::new(&editor, style),
13352        );
13353        assert_eq!(state.position_map.line_layouts.len(), 4);
13354        assert_eq!(state.line_numbers.len(), 1);
13355        assert_eq!(
13356            state
13357                .line_numbers
13358                .get(&MultiBufferRow(0))
13359                .map(|line_number| line_number
13360                    .segments
13361                    .first()
13362                    .unwrap()
13363                    .shaped_line
13364                    .text
13365                    .as_ref()),
13366            Some("1")
13367        );
13368    }
13369
13370    #[gpui::test]
13371    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
13372        const TAB_SIZE: u32 = 4;
13373
13374        let input_text = "\t \t|\t| a b";
13375        let expected_invisibles = vec![
13376            Invisible::Tab {
13377                line_start_offset: 0,
13378                line_end_offset: TAB_SIZE as usize,
13379            },
13380            Invisible::Whitespace {
13381                line_offset: TAB_SIZE as usize,
13382            },
13383            Invisible::Tab {
13384                line_start_offset: TAB_SIZE as usize + 1,
13385                line_end_offset: TAB_SIZE as usize * 2,
13386            },
13387            Invisible::Tab {
13388                line_start_offset: TAB_SIZE as usize * 2 + 1,
13389                line_end_offset: TAB_SIZE as usize * 3,
13390            },
13391            Invisible::Whitespace {
13392                line_offset: TAB_SIZE as usize * 3 + 1,
13393            },
13394            Invisible::Whitespace {
13395                line_offset: TAB_SIZE as usize * 3 + 3,
13396            },
13397        ];
13398        assert_eq!(
13399            expected_invisibles.len(),
13400            input_text
13401                .chars()
13402                .filter(|initial_char| initial_char.is_whitespace())
13403                .count(),
13404            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
13405        );
13406
13407        for show_line_numbers in [true, false] {
13408            init_test(cx, |s| {
13409                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
13410                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
13411            });
13412
13413            let actual_invisibles = collect_invisibles_from_new_editor(
13414                cx,
13415                EditorMode::full(),
13416                input_text,
13417                px(500.0),
13418                show_line_numbers,
13419            );
13420
13421            assert_eq!(expected_invisibles, actual_invisibles);
13422        }
13423    }
13424
13425    #[gpui::test]
13426    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
13427        init_test(cx, |s| {
13428            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
13429            s.defaults.tab_size = NonZeroU32::new(4);
13430        });
13431
13432        for editor_mode_without_invisibles in [
13433            EditorMode::SingleLine,
13434            EditorMode::AutoHeight {
13435                min_lines: 1,
13436                max_lines: Some(100),
13437            },
13438        ] {
13439            for show_line_numbers in [true, false] {
13440                let invisibles = collect_invisibles_from_new_editor(
13441                    cx,
13442                    editor_mode_without_invisibles.clone(),
13443                    "\t\t\t| | a b",
13444                    px(500.0),
13445                    show_line_numbers,
13446                );
13447                assert!(
13448                    invisibles.is_empty(),
13449                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
13450                );
13451            }
13452        }
13453    }
13454
13455    #[gpui::test]
13456    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
13457        let tab_size = 4;
13458        let input_text = "a\tbcd     ".repeat(9);
13459        let repeated_invisibles = [
13460            Invisible::Tab {
13461                line_start_offset: 1,
13462                line_end_offset: tab_size as usize,
13463            },
13464            Invisible::Whitespace {
13465                line_offset: tab_size as usize + 3,
13466            },
13467            Invisible::Whitespace {
13468                line_offset: tab_size as usize + 4,
13469            },
13470            Invisible::Whitespace {
13471                line_offset: tab_size as usize + 5,
13472            },
13473            Invisible::Whitespace {
13474                line_offset: tab_size as usize + 6,
13475            },
13476            Invisible::Whitespace {
13477                line_offset: tab_size as usize + 7,
13478            },
13479        ];
13480        let expected_invisibles = std::iter::once(repeated_invisibles)
13481            .cycle()
13482            .take(9)
13483            .flatten()
13484            .collect::<Vec<_>>();
13485        assert_eq!(
13486            expected_invisibles.len(),
13487            input_text
13488                .chars()
13489                .filter(|initial_char| initial_char.is_whitespace())
13490                .count(),
13491            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
13492        );
13493        info!("Expected invisibles: {expected_invisibles:?}");
13494
13495        init_test(cx, |_| {});
13496
13497        // Put the same string with repeating whitespace pattern into editors of various size,
13498        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
13499        let resize_step = 10.0;
13500        let mut editor_width = 200.0;
13501        while editor_width <= 1000.0 {
13502            for show_line_numbers in [true, false] {
13503                update_test_language_settings(cx, &|s| {
13504                    s.defaults.tab_size = NonZeroU32::new(tab_size);
13505                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
13506                    s.defaults.preferred_line_length = Some(editor_width as u32);
13507                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::Bounded);
13508                });
13509
13510                let actual_invisibles = collect_invisibles_from_new_editor(
13511                    cx,
13512                    EditorMode::full(),
13513                    &input_text,
13514                    px(editor_width),
13515                    show_line_numbers,
13516                );
13517
13518                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
13519                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
13520                let mut i = 0;
13521                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
13522                    i = actual_index;
13523                    match expected_invisibles.get(i) {
13524                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
13525                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
13526                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
13527                            _ => {
13528                                panic!(
13529                                    "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
13530                                )
13531                            }
13532                        },
13533                        None => {
13534                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
13535                        }
13536                    }
13537                }
13538                let missing_expected_invisibles = &expected_invisibles[i + 1..];
13539                assert!(
13540                    missing_expected_invisibles.is_empty(),
13541                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
13542                );
13543
13544                editor_width += resize_step;
13545            }
13546        }
13547    }
13548
13549    fn collect_invisibles_from_new_editor(
13550        cx: &mut TestAppContext,
13551        editor_mode: EditorMode,
13552        input_text: &str,
13553        editor_width: Pixels,
13554        show_line_numbers: bool,
13555    ) -> Vec<Invisible> {
13556        info!(
13557            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
13558            f32::from(editor_width)
13559        );
13560        let window = cx.add_window(|window, cx| {
13561            let buffer = MultiBuffer::build_simple(input_text, cx);
13562            Editor::new(editor_mode, buffer, None, window, cx)
13563        });
13564        let cx = &mut VisualTestContext::from_window(*window, cx);
13565        let editor = window.root(cx).unwrap();
13566
13567        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
13568        window
13569            .update(cx, |editor, _, cx| {
13570                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
13571                editor.set_wrap_width(Some(editor_width), cx);
13572                editor.set_show_line_numbers(show_line_numbers, cx);
13573            })
13574            .unwrap();
13575        let (_, state) = cx.draw(
13576            point(px(500.), px(500.)),
13577            size(px(500.), px(500.)),
13578            |_, _| EditorElement::new(&editor, style),
13579        );
13580        state
13581            .position_map
13582            .line_layouts
13583            .iter()
13584            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
13585            .cloned()
13586            .collect()
13587    }
13588
13589    #[gpui::test]
13590    fn test_merge_overlapping_ranges() {
13591        let base_bg = Hsla::white();
13592        let color1 = Hsla {
13593            h: 0.0,
13594            s: 0.5,
13595            l: 0.5,
13596            a: 0.5,
13597        };
13598        let color2 = Hsla {
13599            h: 120.0,
13600            s: 0.5,
13601            l: 0.5,
13602            a: 0.5,
13603        };
13604
13605        let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
13606        let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
13607            v.iter()
13608                .map(|(r, _)| (r.start.column(), r.end.column()))
13609                .collect()
13610        };
13611
13612        // Test overlapping ranges blend colors
13613        let overlapping = vec![
13614            (display_point(5)..display_point(15), color1),
13615            (display_point(10)..display_point(20), color2),
13616        ];
13617        let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
13618        assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
13619
13620        // Test middle segment should have blended color
13621        let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
13622        assert_eq!(result[1].1, blended);
13623
13624        // Test adjacent same-color ranges merge
13625        let adjacent_same = vec![
13626            (display_point(5)..display_point(10), color1),
13627            (display_point(10)..display_point(15), color1),
13628        ];
13629        let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
13630        assert_eq!(cols(&result), vec![(5, 15)]);
13631
13632        // Test contained range splits
13633        let contained = vec![
13634            (display_point(5)..display_point(20), color1),
13635            (display_point(10)..display_point(15), color2),
13636        ];
13637        let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
13638        assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
13639
13640        // Test multiple overlaps split at every boundary
13641        let color3 = Hsla {
13642            h: 240.0,
13643            s: 0.5,
13644            l: 0.5,
13645            a: 0.5,
13646        };
13647        let complex = vec![
13648            (display_point(5)..display_point(12), color1),
13649            (display_point(8)..display_point(16), color2),
13650            (display_point(10)..display_point(14), color3),
13651        ];
13652        let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
13653        assert_eq!(
13654            cols(&result),
13655            vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
13656        );
13657    }
13658
13659    #[gpui::test]
13660    fn test_bg_segments_per_row() {
13661        let base_bg = Hsla::white();
13662
13663        // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
13664        {
13665            let selection_color = Hsla {
13666                h: 200.0,
13667                s: 0.5,
13668                l: 0.5,
13669                a: 0.5,
13670            };
13671            let player_color = PlayerColor {
13672                cursor: selection_color,
13673                background: selection_color,
13674                selection: selection_color,
13675            };
13676
13677            let spanning_selection = SelectionLayout {
13678                head: DisplayPoint::new(DisplayRow(3), 7),
13679                cursor_shape: CursorShape::Bar,
13680                is_newest: true,
13681                is_local: true,
13682                range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
13683                active_rows: DisplayRow(1)..DisplayRow(4),
13684                user_name: None,
13685            };
13686
13687            let selections = vec![(player_color, vec![spanning_selection])];
13688            let result = EditorElement::bg_segments_per_row(
13689                DisplayRow(0)..DisplayRow(5),
13690                &selections,
13691                &[],
13692                base_bg,
13693            );
13694
13695            assert_eq!(result.len(), 5);
13696            assert!(result[0].is_empty());
13697            assert_eq!(result[1].len(), 1);
13698            assert_eq!(result[2].len(), 1);
13699            assert_eq!(result[3].len(), 1);
13700            assert!(result[4].is_empty());
13701
13702            assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13703            assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13704            assert_eq!(result[1][0].0.end.column(), u32::MAX);
13705            assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13706            assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13707            assert_eq!(result[2][0].0.end.column(), u32::MAX);
13708            assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
13709            assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
13710        }
13711
13712        // Case B: selection ends exactly at the start of row 3, excluding row 3
13713        {
13714            let selection_color = Hsla {
13715                h: 120.0,
13716                s: 0.5,
13717                l: 0.5,
13718                a: 0.5,
13719            };
13720            let player_color = PlayerColor {
13721                cursor: selection_color,
13722                background: selection_color,
13723                selection: selection_color,
13724            };
13725
13726            let selection = SelectionLayout {
13727                head: DisplayPoint::new(DisplayRow(2), 0),
13728                cursor_shape: CursorShape::Bar,
13729                is_newest: true,
13730                is_local: true,
13731                range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
13732                active_rows: DisplayRow(1)..DisplayRow(3),
13733                user_name: None,
13734            };
13735
13736            let selections = vec![(player_color, vec![selection])];
13737            let result = EditorElement::bg_segments_per_row(
13738                DisplayRow(0)..DisplayRow(4),
13739                &selections,
13740                &[],
13741                base_bg,
13742            );
13743
13744            assert_eq!(result.len(), 4);
13745            assert!(result[0].is_empty());
13746            assert_eq!(result[1].len(), 1);
13747            assert_eq!(result[2].len(), 1);
13748            assert!(result[3].is_empty());
13749
13750            assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13751            assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13752            assert_eq!(result[1][0].0.end.column(), u32::MAX);
13753            assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13754            assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13755            assert_eq!(result[2][0].0.end.column(), u32::MAX);
13756        }
13757    }
13758
13759    #[cfg(test)]
13760    fn generate_test_run(len: usize, color: Hsla) -> TextRun {
13761        TextRun {
13762            len,
13763            color,
13764            ..Default::default()
13765        }
13766    }
13767
13768    #[gpui::test]
13769    fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
13770        init_test(cx, |_| {});
13771
13772        let dx = |start: u32, end: u32| {
13773            DisplayPoint::new(DisplayRow(0), start)..DisplayPoint::new(DisplayRow(0), end)
13774        };
13775
13776        let text_color = Hsla {
13777            h: 210.0,
13778            s: 0.1,
13779            l: 0.4,
13780            a: 1.0,
13781        };
13782        let bg_1 = Hsla {
13783            h: 30.0,
13784            s: 0.6,
13785            l: 0.8,
13786            a: 1.0,
13787        };
13788        let bg_2 = Hsla {
13789            h: 200.0,
13790            s: 0.6,
13791            l: 0.2,
13792            a: 1.0,
13793        };
13794        let min_contrast = 45.0;
13795        let adjusted_bg1 = ensure_minimum_contrast(text_color, bg_1, min_contrast);
13796        let adjusted_bg2 = ensure_minimum_contrast(text_color, bg_2, min_contrast);
13797
13798        // Case A: single run; disjoint segments inside the run
13799        {
13800            let runs = vec![generate_test_run(20, text_color)];
13801            let segs = vec![(dx(5, 10), bg_1), (dx(12, 16), bg_2)];
13802            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13803            // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
13804            assert_eq!(
13805                out.iter().map(|r| r.len).collect::<Vec<_>>(),
13806                vec![5, 5, 2, 4, 4]
13807            );
13808            assert_eq!(out[0].color, text_color);
13809            assert_eq!(out[1].color, adjusted_bg1);
13810            assert_eq!(out[2].color, text_color);
13811            assert_eq!(out[3].color, adjusted_bg2);
13812            assert_eq!(out[4].color, text_color);
13813        }
13814
13815        // Case B: multiple runs; segment extends to end of line (u32::MAX)
13816        {
13817            let runs = vec![
13818                generate_test_run(8, text_color),
13819                generate_test_run(7, text_color),
13820            ];
13821            let segs = vec![(dx(6, u32::MAX), bg_1)];
13822            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13823            // Expected slices across runs: [0,6) [6,8) | [0,7)
13824            assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
13825            assert_eq!(out[0].color, text_color);
13826            assert_eq!(out[1].color, adjusted_bg1);
13827            assert_eq!(out[2].color, adjusted_bg1);
13828        }
13829
13830        // Case C: multi-byte characters
13831        {
13832            // for text: "Hello 🌍 δΈ–η•Œ!"
13833            let runs = vec![
13834                generate_test_run(5, text_color), // "Hello"
13835                generate_test_run(6, text_color), // " 🌍 "
13836                generate_test_run(6, text_color), // "δΈ–η•Œ"
13837                generate_test_run(1, text_color), // "!"
13838            ];
13839            // selecting "🌍 δΈ–"
13840            let segs = vec![(dx(6, 14), bg_1)];
13841            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13842            // "Hello" | " " | "🌍 " | "δΈ–" | "η•Œ" | "!"
13843            assert_eq!(
13844                out.iter().map(|r| r.len).collect::<Vec<_>>(),
13845                vec![5, 1, 5, 3, 3, 1]
13846            );
13847            assert_eq!(out[0].color, text_color); // "Hello"
13848            assert_eq!(out[2].color, adjusted_bg1); // "🌍 "
13849            assert_eq!(out[3].color, adjusted_bg1); // "δΈ–"
13850            assert_eq!(out[4].color, text_color); // "η•Œ"
13851            assert_eq!(out[5].color, text_color); // "!"
13852        }
13853
13854        // Case D: split multiple consecutive text runs with segments
13855        {
13856            let segs = vec![
13857                (dx(2, 4), bg_1),   // selecting "cd"
13858                (dx(4, 8), bg_2),   // selecting "efgh"
13859                (dx(9, 11), bg_1),  // selecting "jk"
13860                (dx(12, 16), bg_2), // selecting "mnop"
13861                (dx(18, 19), bg_1), // selecting "s"
13862            ];
13863
13864            // for text: "abcdef"
13865            let runs = vec![
13866                generate_test_run(2, text_color), // ab
13867                generate_test_run(4, text_color), // cdef
13868            ];
13869            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13870            // new splits "ab", "cd", "ef"
13871            assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![2, 2, 2]);
13872            assert_eq!(out[0].color, text_color);
13873            assert_eq!(out[1].color, adjusted_bg1);
13874            assert_eq!(out[2].color, adjusted_bg2);
13875
13876            // for text: "ghijklmn"
13877            let runs = vec![
13878                generate_test_run(3, text_color), // ghi
13879                generate_test_run(2, text_color), // jk
13880                generate_test_run(3, text_color), // lmn
13881            ];
13882            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 6); // 2 + 4 from first run
13883            // new splits "gh", "i", "jk", "l", "mn"
13884            assert_eq!(
13885                out.iter().map(|r| r.len).collect::<Vec<_>>(),
13886                vec![2, 1, 2, 1, 2]
13887            );
13888            assert_eq!(out[0].color, adjusted_bg2);
13889            assert_eq!(out[1].color, text_color);
13890            assert_eq!(out[2].color, adjusted_bg1);
13891            assert_eq!(out[3].color, text_color);
13892            assert_eq!(out[4].color, adjusted_bg2);
13893
13894            // for text: "opqrs"
13895            let runs = vec![
13896                generate_test_run(1, text_color), // o
13897                generate_test_run(4, text_color), // pqrs
13898            ];
13899            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 14); // 6 + 3 + 2 + 3 from first two runs
13900            // new splits "o", "p", "qr", "s"
13901            assert_eq!(
13902                out.iter().map(|r| r.len).collect::<Vec<_>>(),
13903                vec![1, 1, 2, 1]
13904            );
13905            assert_eq!(out[0].color, adjusted_bg2);
13906            assert_eq!(out[1].color, adjusted_bg2);
13907            assert_eq!(out[2].color, text_color);
13908            assert_eq!(out[3].color, adjusted_bg1);
13909        }
13910    }
13911
13912    #[test]
13913    fn test_spacer_pattern_period() {
13914        // line height is smaller than target height, so we just return half the line height
13915        assert_eq!(EditorElement::spacer_pattern_period(10.0, 20.0), 5.0);
13916
13917        // line height is exactly half the target height, perfect match
13918        assert_eq!(EditorElement::spacer_pattern_period(20.0, 10.0), 10.0);
13919
13920        // line height is close to half the target height
13921        assert_eq!(EditorElement::spacer_pattern_period(20.0, 9.0), 10.0);
13922
13923        // line height is close to 1/4 the target height
13924        assert_eq!(EditorElement::spacer_pattern_period(20.0, 4.8), 5.0);
13925    }
13926
13927    #[gpui::test(iterations = 100)]
13928    fn test_random_spacer_pattern_period(mut rng: StdRng) {
13929        let line_height = rng.next_u32() as f32;
13930        let target_height = rng.next_u32() as f32;
13931
13932        let result = EditorElement::spacer_pattern_period(line_height, target_height);
13933
13934        let k = line_height / result;
13935        assert!(k - k.round() < 0.0000001); // approximately integer
13936        assert!((k.round() as u32).is_multiple_of(2));
13937    }
13938
13939    #[test]
13940    fn test_calculate_wrap_width() {
13941        let editor_width = px(800.0);
13942        let em_width = px(8.0);
13943
13944        assert_eq!(
13945            calculate_wrap_width(SoftWrap::GitDiff, editor_width, em_width),
13946            None,
13947        );
13948
13949        assert_eq!(
13950            calculate_wrap_width(SoftWrap::None, editor_width, em_width),
13951            Some(px((MAX_LINE_LEN as f32 / 2.0 * 8.0).ceil())),
13952        );
13953
13954        assert_eq!(
13955            calculate_wrap_width(SoftWrap::EditorWidth, editor_width, em_width),
13956            Some(px(800.0)),
13957        );
13958
13959        assert_eq!(
13960            calculate_wrap_width(SoftWrap::Bounded(72), editor_width, em_width),
13961            Some(px((72.0 * 8.0_f32).ceil())),
13962        );
13963        assert_eq!(
13964            calculate_wrap_width(SoftWrap::Bounded(200), px(400.0), em_width),
13965            Some(px(400.0)),
13966        );
13967    }
13968}