element.rs

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