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                .group("buffer-header-group")
 8147                .size_full()
 8148                .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
 8149                .pl_1()
 8150                .pr_2()
 8151                .rounded_sm()
 8152                .gap_1p5()
 8153                .when(is_sticky, |el| el.shadow_md())
 8154                .border_1()
 8155                .map(|border| {
 8156                    let border_color =
 8157                        if is_selected && is_folded && focus_handle.contains_focused(window, cx) {
 8158                            colors.border_focused
 8159                        } else {
 8160                            colors.border
 8161                        };
 8162                    border.border_color(border_color)
 8163                })
 8164                .bg(colors.editor_subheader_background)
 8165                .hover(|style| style.bg(colors.element_hover))
 8166                .map(|header| {
 8167                    let editor = editor.clone();
 8168                    let buffer_id = for_excerpt.buffer_id;
 8169                    let toggle_chevron_icon =
 8170                        FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
 8171                    let button_size = rems_from_px(28.);
 8172
 8173                    header.child(
 8174                        div()
 8175                            .hover(|style| style.bg(colors.element_selected))
 8176                            .rounded_xs()
 8177                            .child(
 8178                                ButtonLike::new("toggle-buffer-fold")
 8179                                    .style(ButtonStyle::Transparent)
 8180                                    .height(button_size.into())
 8181                                    .width(button_size)
 8182                                    .children(toggle_chevron_icon)
 8183                                    .tooltip({
 8184                                        let focus_handle = focus_handle.clone();
 8185                                        let is_folded_for_tooltip = is_folded;
 8186                                        move |_window, cx| {
 8187                                            Tooltip::with_meta_in(
 8188                                                if is_folded_for_tooltip {
 8189                                                    "Unfold Excerpt"
 8190                                                } else {
 8191                                                    "Fold Excerpt"
 8192                                                },
 8193                                                Some(&ToggleFold),
 8194                                                format!(
 8195                                                    "{} to toggle all",
 8196                                                    text_for_keystroke(
 8197                                                        &Modifiers::alt(),
 8198                                                        "click",
 8199                                                        cx
 8200                                                    )
 8201                                                ),
 8202                                                &focus_handle,
 8203                                                cx,
 8204                                            )
 8205                                        }
 8206                                    })
 8207                                    .on_click(move |event, window, cx| {
 8208                                        if event.modifiers().alt {
 8209                                            editor.update(cx, |editor, cx| {
 8210                                                editor.toggle_fold_all(&ToggleFoldAll, window, cx);
 8211                                            });
 8212                                        } else {
 8213                                            if is_folded {
 8214                                                editor.update(cx, |editor, cx| {
 8215                                                    editor.unfold_buffer(buffer_id, cx);
 8216                                                });
 8217                                            } else {
 8218                                                editor.update(cx, |editor, cx| {
 8219                                                    editor.fold_buffer(buffer_id, cx);
 8220                                                });
 8221                                            }
 8222                                        }
 8223                                    }),
 8224                            ),
 8225                    )
 8226                })
 8227                .children(
 8228                    editor_read
 8229                        .addons
 8230                        .values()
 8231                        .filter_map(|addon| {
 8232                            addon.render_buffer_header_controls(for_excerpt, window, cx)
 8233                        })
 8234                        .take(1),
 8235                )
 8236                .when(!is_read_only, |this| {
 8237                    this.child(
 8238                        h_flex()
 8239                            .size_3()
 8240                            .justify_center()
 8241                            .flex_shrink_0()
 8242                            .children(indicator),
 8243                    )
 8244                })
 8245                .child(
 8246                    h_flex()
 8247                        .cursor_pointer()
 8248                        .id("path_header_block")
 8249                        .min_w_0()
 8250                        .size_full()
 8251                        .gap_1()
 8252                        .justify_between()
 8253                        .overflow_hidden()
 8254                        .child(h_flex().min_w_0().flex_1().gap_0p5().overflow_hidden().map(
 8255                            |path_header| {
 8256                                let filename = filename
 8257                                    .map(SharedString::from)
 8258                                    .unwrap_or_else(|| "untitled".into());
 8259
 8260                                let full_path = match parent_path.as_deref() {
 8261                                    Some(parent) if !parent.is_empty() => {
 8262                                        format!("{}{}", parent, filename.as_str())
 8263                                    }
 8264                                    _ => filename.as_str().to_string(),
 8265                                };
 8266
 8267                                path_header
 8268                                    .child(
 8269                                        ButtonLike::new("filename-button")
 8270                                            .when(ItemSettings::get_global(cx).file_icons, |this| {
 8271                                                let path = path::Path::new(filename.as_str());
 8272                                                let icon = FileIcons::get_icon(path, cx)
 8273                                                    .unwrap_or_default();
 8274
 8275                                                this.child(
 8276                                                    Icon::from_path(icon).color(Color::Muted),
 8277                                                )
 8278                                            })
 8279                                            .child(
 8280                                                Label::new(filename)
 8281                                                    .single_line()
 8282                                                    .color(file_status_label_color(file_status))
 8283                                                    .buffer_font(cx)
 8284                                                    .when(
 8285                                                        file_status.is_some_and(|s| s.is_deleted()),
 8286                                                        |label| label.strikethrough(),
 8287                                                    ),
 8288                                            )
 8289                                            .tooltip(move |_, cx| {
 8290                                                Tooltip::with_meta(
 8291                                                    "Open File",
 8292                                                    None,
 8293                                                    full_path.clone(),
 8294                                                    cx,
 8295                                                )
 8296                                            })
 8297                                            .on_click(window.listener_for(editor, {
 8298                                                let jump_data = jump_data.clone();
 8299                                                move |editor, e: &ClickEvent, window, cx| {
 8300                                                    editor.open_excerpts_common(
 8301                                                        Some(jump_data.clone()),
 8302                                                        e.modifiers().secondary(),
 8303                                                        window,
 8304                                                        cx,
 8305                                                    );
 8306                                                }
 8307                                            })),
 8308                                    )
 8309                                    .when_some(parent_path, |then, path| {
 8310                                        then.child(
 8311                                            Label::new(path)
 8312                                                .buffer_font(cx)
 8313                                                .truncate_start()
 8314                                                .color(
 8315                                                    if file_status
 8316                                                        .is_some_and(FileStatus::is_deleted)
 8317                                                    {
 8318                                                        Color::Custom(colors.text_disabled)
 8319                                                    } else {
 8320                                                        Color::Custom(colors.text_muted)
 8321                                                    },
 8322                                                ),
 8323                                        )
 8324                                    })
 8325                                    .when(!for_excerpt.buffer.capability.editable(), |el| {
 8326                                        el.child(Icon::new(IconName::FileLock).color(Color::Muted))
 8327                                    })
 8328                                    .when_some(breadcrumbs, |then, breadcrumbs| {
 8329                                        then.child(render_breadcrumb_text(
 8330                                            breadcrumbs,
 8331                                            None,
 8332                                            editor_handle,
 8333                                            true,
 8334                                            window,
 8335                                            cx,
 8336                                        ))
 8337                                    })
 8338                            },
 8339                        ))
 8340                        .when(can_open_excerpts && relative_path.is_some(), |this| {
 8341                            this.child(
 8342                                div()
 8343                                    .when(!is_selected, |this| {
 8344                                        this.visible_on_hover("buffer-header-group")
 8345                                    })
 8346                                    .child(
 8347                                        Button::new("open-file-button", "Open File")
 8348                                            .style(ButtonStyle::OutlinedGhost)
 8349                                            .when(is_selected, |this| {
 8350                                                this.key_binding(KeyBinding::for_action_in(
 8351                                                    &OpenExcerpts,
 8352                                                    &focus_handle,
 8353                                                    cx,
 8354                                                ))
 8355                                            })
 8356                                            .on_click(window.listener_for(editor, {
 8357                                                let jump_data = jump_data.clone();
 8358                                                move |editor, e: &ClickEvent, window, cx| {
 8359                                                    editor.open_excerpts_common(
 8360                                                        Some(jump_data.clone()),
 8361                                                        e.modifiers().secondary(),
 8362                                                        window,
 8363                                                        cx,
 8364                                                    );
 8365                                                }
 8366                                            })),
 8367                                    ),
 8368                            )
 8369                        })
 8370                        .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 8371                        .on_click(window.listener_for(editor, {
 8372                            let buffer_id = for_excerpt.buffer_id;
 8373                            move |editor, e: &ClickEvent, window, cx| {
 8374                                if e.modifiers().alt {
 8375                                    editor.open_excerpts_common(
 8376                                        Some(jump_data.clone()),
 8377                                        e.modifiers().secondary(),
 8378                                        window,
 8379                                        cx,
 8380                                    );
 8381                                    return;
 8382                                }
 8383
 8384                                if is_folded {
 8385                                    editor.unfold_buffer(buffer_id, cx);
 8386                                } else {
 8387                                    editor.fold_buffer(buffer_id, cx);
 8388                                }
 8389                            }
 8390                        })),
 8391                ),
 8392        );
 8393
 8394    let file = for_excerpt.buffer.file().cloned();
 8395    let editor = editor.clone();
 8396
 8397    right_click_menu("buffer-header-context-menu")
 8398        .trigger(move |_, _, _| header)
 8399        .menu(move |window, cx| {
 8400            let menu_context = focus_handle.clone();
 8401            let editor = editor.clone();
 8402            let file = file.clone();
 8403            ContextMenu::build(window, cx, move |mut menu, window, cx| {
 8404                if let Some(file) = file
 8405                    && let Some(project) = editor.read(cx).project()
 8406                    && let Some(worktree) =
 8407                        project.read(cx).worktree_for_id(file.worktree_id(cx), cx)
 8408                {
 8409                    let path_style = file.path_style(cx);
 8410                    let worktree = worktree.read(cx);
 8411                    let relative_path = file.path();
 8412                    let entry_for_path = worktree.entry_for_path(relative_path);
 8413                    let abs_path = entry_for_path.map(|e| {
 8414                        e.canonical_path
 8415                            .as_deref()
 8416                            .map_or_else(|| worktree.absolutize(relative_path), Path::to_path_buf)
 8417                    });
 8418                    let has_relative_path = worktree.root_entry().is_some_and(Entry::is_dir);
 8419
 8420                    let parent_abs_path = abs_path
 8421                        .as_ref()
 8422                        .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
 8423                    let relative_path = has_relative_path
 8424                        .then_some(relative_path)
 8425                        .map(ToOwned::to_owned);
 8426
 8427                    let visible_in_project_panel = relative_path.is_some() && worktree.is_visible();
 8428                    let reveal_in_project_panel = entry_for_path
 8429                        .filter(|_| visible_in_project_panel)
 8430                        .map(|entry| entry.id);
 8431                    menu = menu
 8432                        .when_some(abs_path, |menu, abs_path| {
 8433                            menu.entry(
 8434                                "Copy Path",
 8435                                Some(Box::new(zed_actions::workspace::CopyPath)),
 8436                                window.handler_for(&editor, move |_, _, cx| {
 8437                                    cx.write_to_clipboard(ClipboardItem::new_string(
 8438                                        abs_path.to_string_lossy().into_owned(),
 8439                                    ));
 8440                                }),
 8441                            )
 8442                        })
 8443                        .when_some(relative_path, |menu, relative_path| {
 8444                            menu.entry(
 8445                                "Copy Relative Path",
 8446                                Some(Box::new(zed_actions::workspace::CopyRelativePath)),
 8447                                window.handler_for(&editor, move |_, _, cx| {
 8448                                    cx.write_to_clipboard(ClipboardItem::new_string(
 8449                                        relative_path.display(path_style).to_string(),
 8450                                    ));
 8451                                }),
 8452                            )
 8453                        })
 8454                        .when(
 8455                            reveal_in_project_panel.is_some() || parent_abs_path.is_some(),
 8456                            |menu| menu.separator(),
 8457                        )
 8458                        .when_some(reveal_in_project_panel, |menu, entry_id| {
 8459                            menu.entry(
 8460                                "Reveal In Project Panel",
 8461                                Some(Box::new(RevealInProjectPanel::default())),
 8462                                window.handler_for(&editor, move |editor, _, cx| {
 8463                                    if let Some(project) = &mut editor.project {
 8464                                        project.update(cx, |_, cx| {
 8465                                            cx.emit(project::Event::RevealInProjectPanel(entry_id))
 8466                                        });
 8467                                    }
 8468                                }),
 8469                            )
 8470                        })
 8471                        .when_some(parent_abs_path, |menu, parent_abs_path| {
 8472                            menu.entry(
 8473                                "Open in Terminal",
 8474                                Some(Box::new(OpenInTerminal)),
 8475                                window.handler_for(&editor, move |_, window, cx| {
 8476                                    window.dispatch_action(
 8477                                        OpenTerminal {
 8478                                            working_directory: parent_abs_path.clone(),
 8479                                            local: false,
 8480                                        }
 8481                                        .boxed_clone(),
 8482                                        cx,
 8483                                    );
 8484                                }),
 8485                            )
 8486                        });
 8487                }
 8488
 8489                menu.context(menu_context)
 8490            })
 8491        })
 8492}
 8493
 8494pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
 8495
 8496impl AcceptEditPredictionBinding {
 8497    pub fn keystroke(&self) -> Option<&KeybindingKeystroke> {
 8498        if let Some(binding) = self.0.as_ref() {
 8499            match &binding.keystrokes() {
 8500                [keystroke, ..] => Some(keystroke),
 8501                _ => None,
 8502            }
 8503        } else {
 8504            None
 8505        }
 8506    }
 8507}
 8508
 8509fn prepaint_gutter_button(
 8510    mut button: AnyElement,
 8511    row: DisplayRow,
 8512    line_height: Pixels,
 8513    gutter_dimensions: &GutterDimensions,
 8514    scroll_position: gpui::Point<ScrollOffset>,
 8515    gutter_hitbox: &Hitbox,
 8516    window: &mut Window,
 8517    cx: &mut App,
 8518) -> AnyElement {
 8519    let available_space = size(
 8520        AvailableSpace::MinContent,
 8521        AvailableSpace::Definite(line_height),
 8522    );
 8523    let indicator_size = button.layout_as_root(available_space, window, cx);
 8524    let git_gutter_width = EditorElement::gutter_strip_width(line_height)
 8525        + gutter_dimensions
 8526            .git_blame_entries_width
 8527            .unwrap_or_default();
 8528
 8529    let x = git_gutter_width + px(2.);
 8530
 8531    let mut y =
 8532        Pixels::from((row.as_f64() - scroll_position.y) * ScrollPixelOffset::from(line_height));
 8533    y += (line_height - indicator_size.height) / 2.;
 8534
 8535    button.prepaint_as_root(
 8536        gutter_hitbox.origin + point(x, y),
 8537        available_space,
 8538        window,
 8539        cx,
 8540    );
 8541    button
 8542}
 8543
 8544fn render_inline_blame_entry(
 8545    blame_entry: BlameEntry,
 8546    style: &EditorStyle,
 8547    cx: &mut App,
 8548) -> Option<AnyElement> {
 8549    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 8550    renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
 8551}
 8552
 8553fn render_blame_entry_popover(
 8554    blame_entry: BlameEntry,
 8555    scroll_handle: ScrollHandle,
 8556    commit_message: Option<ParsedCommitMessage>,
 8557    markdown: Entity<Markdown>,
 8558    workspace: WeakEntity<Workspace>,
 8559    blame: &Entity<GitBlame>,
 8560    buffer: BufferId,
 8561    window: &mut Window,
 8562    cx: &mut App,
 8563) -> Option<AnyElement> {
 8564    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 8565    let blame = blame.read(cx);
 8566    let repository = blame.repository(cx, buffer)?;
 8567    renderer.render_blame_entry_popover(
 8568        blame_entry,
 8569        scroll_handle,
 8570        commit_message,
 8571        markdown,
 8572        repository,
 8573        workspace,
 8574        window,
 8575        cx,
 8576    )
 8577}
 8578
 8579fn render_blame_entry(
 8580    ix: usize,
 8581    blame: &Entity<GitBlame>,
 8582    blame_entry: BlameEntry,
 8583    style: &EditorStyle,
 8584    last_used_color: &mut Option<(Hsla, Oid)>,
 8585    editor: Entity<Editor>,
 8586    workspace: Entity<Workspace>,
 8587    buffer: BufferId,
 8588    renderer: &dyn BlameRenderer,
 8589    window: &mut Window,
 8590    cx: &mut App,
 8591) -> Option<AnyElement> {
 8592    let index: u32 = blame_entry.sha.into();
 8593    let mut sha_color = cx.theme().players().color_for_participant(index).cursor;
 8594
 8595    // If the last color we used is the same as the one we get for this line, but
 8596    // the commit SHAs are different, then we try again to get a different color.
 8597    if let Some((color, sha)) = *last_used_color
 8598        && sha != blame_entry.sha
 8599        && color == sha_color
 8600    {
 8601        sha_color = cx.theme().players().color_for_participant(index + 1).cursor;
 8602    }
 8603    last_used_color.replace((sha_color, blame_entry.sha));
 8604
 8605    let blame = blame.read(cx);
 8606    let details = blame.details_for_entry(buffer, &blame_entry);
 8607    let repository = blame.repository(cx, buffer)?;
 8608    renderer.render_blame_entry(
 8609        &style.text,
 8610        blame_entry,
 8611        details,
 8612        repository,
 8613        workspace.downgrade(),
 8614        editor,
 8615        ix,
 8616        sha_color,
 8617        window,
 8618        cx,
 8619    )
 8620}
 8621
 8622#[derive(Debug)]
 8623pub(crate) struct LineWithInvisibles {
 8624    fragments: SmallVec<[LineFragment; 1]>,
 8625    invisibles: Vec<Invisible>,
 8626    len: usize,
 8627    pub(crate) width: Pixels,
 8628    font_size: Pixels,
 8629}
 8630
 8631enum LineFragment {
 8632    Text(ShapedLine),
 8633    Element {
 8634        id: ChunkRendererId,
 8635        element: Option<AnyElement>,
 8636        size: Size<Pixels>,
 8637        len: usize,
 8638    },
 8639}
 8640
 8641impl fmt::Debug for LineFragment {
 8642    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 8643        match self {
 8644            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
 8645            LineFragment::Element { size, len, .. } => f
 8646                .debug_struct("Element")
 8647                .field("size", size)
 8648                .field("len", len)
 8649                .finish(),
 8650        }
 8651    }
 8652}
 8653
 8654impl LineWithInvisibles {
 8655    fn from_chunks<'a>(
 8656        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
 8657        editor_style: &EditorStyle,
 8658        max_line_len: usize,
 8659        max_line_count: usize,
 8660        editor_mode: &EditorMode,
 8661        text_width: Pixels,
 8662        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 8663        bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
 8664        window: &mut Window,
 8665        cx: &mut App,
 8666    ) -> Vec<Self> {
 8667        let text_style = &editor_style.text;
 8668        let mut layouts = Vec::with_capacity(max_line_count);
 8669        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
 8670        let mut line = String::new();
 8671        let mut invisibles = Vec::new();
 8672        let mut width = Pixels::ZERO;
 8673        let mut len = 0;
 8674        let mut styles = Vec::new();
 8675        let mut non_whitespace_added = false;
 8676        let mut row = 0;
 8677        let mut line_exceeded_max_len = false;
 8678        let font_size = text_style.font_size.to_pixels(window.rem_size());
 8679        let min_contrast = EditorSettings::get_global(cx).minimum_contrast_for_highlights;
 8680
 8681        let ellipsis = SharedString::from("β‹―");
 8682
 8683        for highlighted_chunk in chunks.chain([HighlightedChunk {
 8684            text: "\n",
 8685            style: None,
 8686            is_tab: false,
 8687            is_inlay: false,
 8688            replacement: None,
 8689        }]) {
 8690            if let Some(replacement) = highlighted_chunk.replacement {
 8691                if !line.is_empty() {
 8692                    let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
 8693                    let text_runs: &[TextRun] = if segments.is_empty() {
 8694                        &styles
 8695                    } else {
 8696                        &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
 8697                    };
 8698                    let shaped_line = window.text_system().shape_line(
 8699                        line.clone().into(),
 8700                        font_size,
 8701                        text_runs,
 8702                        None,
 8703                    );
 8704                    width += shaped_line.width;
 8705                    len += shaped_line.len;
 8706                    fragments.push(LineFragment::Text(shaped_line));
 8707                    line.clear();
 8708                    styles.clear();
 8709                }
 8710
 8711                match replacement {
 8712                    ChunkReplacement::Renderer(renderer) => {
 8713                        let available_width = if renderer.constrain_width {
 8714                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
 8715                                ellipsis.clone()
 8716                            } else {
 8717                                SharedString::from(Arc::from(highlighted_chunk.text))
 8718                            };
 8719                            let shaped_line = window.text_system().shape_line(
 8720                                chunk,
 8721                                font_size,
 8722                                &[text_style.to_run(highlighted_chunk.text.len())],
 8723                                None,
 8724                            );
 8725                            AvailableSpace::Definite(shaped_line.width)
 8726                        } else {
 8727                            AvailableSpace::MinContent
 8728                        };
 8729
 8730                        let mut element = (renderer.render)(&mut ChunkRendererContext {
 8731                            context: cx,
 8732                            window,
 8733                            max_width: text_width,
 8734                        });
 8735                        let line_height = text_style.line_height_in_pixels(window.rem_size());
 8736                        let size = element.layout_as_root(
 8737                            size(available_width, AvailableSpace::Definite(line_height)),
 8738                            window,
 8739                            cx,
 8740                        );
 8741
 8742                        width += size.width;
 8743                        len += highlighted_chunk.text.len();
 8744                        fragments.push(LineFragment::Element {
 8745                            id: renderer.id,
 8746                            element: Some(element),
 8747                            size,
 8748                            len: highlighted_chunk.text.len(),
 8749                        });
 8750                    }
 8751                    ChunkReplacement::Str(x) => {
 8752                        let text_style = if let Some(style) = highlighted_chunk.style {
 8753                            Cow::Owned(text_style.clone().highlight(style))
 8754                        } else {
 8755                            Cow::Borrowed(text_style)
 8756                        };
 8757
 8758                        let run = TextRun {
 8759                            len: x.len(),
 8760                            font: text_style.font(),
 8761                            color: text_style.color,
 8762                            background_color: text_style.background_color,
 8763                            underline: text_style.underline,
 8764                            strikethrough: text_style.strikethrough,
 8765                        };
 8766                        let line_layout = window
 8767                            .text_system()
 8768                            .shape_line(x, font_size, &[run], None)
 8769                            .with_len(highlighted_chunk.text.len());
 8770
 8771                        width += line_layout.width;
 8772                        len += highlighted_chunk.text.len();
 8773                        fragments.push(LineFragment::Text(line_layout))
 8774                    }
 8775                }
 8776            } else {
 8777                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
 8778                    if ix > 0 {
 8779                        let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
 8780                        let text_runs = if segments.is_empty() {
 8781                            &styles
 8782                        } else {
 8783                            &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
 8784                        };
 8785                        let shaped_line = window.text_system().shape_line(
 8786                            line.clone().into(),
 8787                            font_size,
 8788                            text_runs,
 8789                            None,
 8790                        );
 8791                        width += shaped_line.width;
 8792                        len += shaped_line.len;
 8793                        fragments.push(LineFragment::Text(shaped_line));
 8794                        layouts.push(Self {
 8795                            width: mem::take(&mut width),
 8796                            len: mem::take(&mut len),
 8797                            fragments: mem::take(&mut fragments),
 8798                            invisibles: std::mem::take(&mut invisibles),
 8799                            font_size,
 8800                        });
 8801
 8802                        line.clear();
 8803                        styles.clear();
 8804                        row += 1;
 8805                        line_exceeded_max_len = false;
 8806                        non_whitespace_added = false;
 8807                        if row == max_line_count {
 8808                            return layouts;
 8809                        }
 8810                    }
 8811
 8812                    if !line_chunk.is_empty() && !line_exceeded_max_len {
 8813                        let text_style = if let Some(style) = highlighted_chunk.style {
 8814                            Cow::Owned(text_style.clone().highlight(style))
 8815                        } else {
 8816                            Cow::Borrowed(text_style)
 8817                        };
 8818
 8819                        if line.len() + line_chunk.len() > max_line_len {
 8820                            let mut chunk_len = max_line_len - line.len();
 8821                            while !line_chunk.is_char_boundary(chunk_len) {
 8822                                chunk_len -= 1;
 8823                            }
 8824                            line_chunk = &line_chunk[..chunk_len];
 8825                            line_exceeded_max_len = true;
 8826                        }
 8827
 8828                        styles.push(TextRun {
 8829                            len: line_chunk.len(),
 8830                            font: text_style.font(),
 8831                            color: text_style.color,
 8832                            background_color: text_style.background_color,
 8833                            underline: text_style.underline,
 8834                            strikethrough: text_style.strikethrough,
 8835                        });
 8836
 8837                        if editor_mode.is_full() && !highlighted_chunk.is_inlay {
 8838                            // Line wrap pads its contents with fake whitespaces,
 8839                            // avoid printing them
 8840                            let is_soft_wrapped = is_row_soft_wrapped(row);
 8841                            if highlighted_chunk.is_tab {
 8842                                if non_whitespace_added || !is_soft_wrapped {
 8843                                    invisibles.push(Invisible::Tab {
 8844                                        line_start_offset: line.len(),
 8845                                        line_end_offset: line.len() + line_chunk.len(),
 8846                                    });
 8847                                }
 8848                            } else {
 8849                                invisibles.extend(line_chunk.char_indices().filter_map(
 8850                                    |(index, c)| {
 8851                                        let is_whitespace = c.is_whitespace();
 8852                                        non_whitespace_added |= !is_whitespace;
 8853                                        if is_whitespace
 8854                                            && (non_whitespace_added || !is_soft_wrapped)
 8855                                        {
 8856                                            Some(Invisible::Whitespace {
 8857                                                line_offset: line.len() + index,
 8858                                            })
 8859                                        } else {
 8860                                            None
 8861                                        }
 8862                                    },
 8863                                ))
 8864                            }
 8865                        }
 8866
 8867                        line.push_str(line_chunk);
 8868                    }
 8869                }
 8870            }
 8871        }
 8872
 8873        layouts
 8874    }
 8875
 8876    /// Takes text runs and non-overlapping left-to-right background ranges with color.
 8877    /// Returns new text runs with adjusted contrast as per background ranges.
 8878    fn split_runs_by_bg_segments(
 8879        text_runs: &[TextRun],
 8880        bg_segments: &[(Range<DisplayPoint>, Hsla)],
 8881        min_contrast: f32,
 8882        start_col_offset: usize,
 8883    ) -> Vec<TextRun> {
 8884        let mut output_runs: Vec<TextRun> = Vec::with_capacity(text_runs.len());
 8885        let mut line_col = start_col_offset;
 8886        let mut segment_ix = 0usize;
 8887
 8888        for text_run in text_runs.iter() {
 8889            let run_start_col = line_col;
 8890            let run_end_col = run_start_col + text_run.len;
 8891            while segment_ix < bg_segments.len()
 8892                && (bg_segments[segment_ix].0.end.column() as usize) <= run_start_col
 8893            {
 8894                segment_ix += 1;
 8895            }
 8896            let mut cursor_col = run_start_col;
 8897            let mut local_segment_ix = segment_ix;
 8898            while local_segment_ix < bg_segments.len() {
 8899                let (range, segment_color) = &bg_segments[local_segment_ix];
 8900                let segment_start_col = range.start.column() as usize;
 8901                let segment_end_col = range.end.column() as usize;
 8902                if segment_start_col >= run_end_col {
 8903                    break;
 8904                }
 8905                if segment_start_col > cursor_col {
 8906                    let span_len = segment_start_col - cursor_col;
 8907                    output_runs.push(TextRun {
 8908                        len: span_len,
 8909                        font: text_run.font.clone(),
 8910                        color: text_run.color,
 8911                        background_color: text_run.background_color,
 8912                        underline: text_run.underline,
 8913                        strikethrough: text_run.strikethrough,
 8914                    });
 8915                    cursor_col = segment_start_col;
 8916                }
 8917                let segment_slice_end_col = segment_end_col.min(run_end_col);
 8918                if segment_slice_end_col > cursor_col {
 8919                    let new_text_color =
 8920                        ensure_minimum_contrast(text_run.color, *segment_color, min_contrast);
 8921                    output_runs.push(TextRun {
 8922                        len: segment_slice_end_col - cursor_col,
 8923                        font: text_run.font.clone(),
 8924                        color: new_text_color,
 8925                        background_color: text_run.background_color,
 8926                        underline: text_run.underline,
 8927                        strikethrough: text_run.strikethrough,
 8928                    });
 8929                    cursor_col = segment_slice_end_col;
 8930                }
 8931                if segment_end_col >= run_end_col {
 8932                    break;
 8933                }
 8934                local_segment_ix += 1;
 8935            }
 8936            if cursor_col < run_end_col {
 8937                output_runs.push(TextRun {
 8938                    len: run_end_col - cursor_col,
 8939                    font: text_run.font.clone(),
 8940                    color: text_run.color,
 8941                    background_color: text_run.background_color,
 8942                    underline: text_run.underline,
 8943                    strikethrough: text_run.strikethrough,
 8944                });
 8945            }
 8946            line_col = run_end_col;
 8947            segment_ix = local_segment_ix;
 8948        }
 8949        output_runs
 8950    }
 8951
 8952    fn prepaint(
 8953        &mut self,
 8954        line_height: Pixels,
 8955        scroll_position: gpui::Point<ScrollOffset>,
 8956        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 8957        row: DisplayRow,
 8958        content_origin: gpui::Point<Pixels>,
 8959        line_elements: &mut SmallVec<[AnyElement; 1]>,
 8960        window: &mut Window,
 8961        cx: &mut App,
 8962    ) {
 8963        let line_y = f32::from(line_height) * Pixels::from(row.as_f64() - scroll_position.y);
 8964        self.prepaint_with_custom_offset(
 8965            line_height,
 8966            scroll_pixel_position,
 8967            content_origin,
 8968            line_y,
 8969            line_elements,
 8970            window,
 8971            cx,
 8972        );
 8973    }
 8974
 8975    fn prepaint_with_custom_offset(
 8976        &mut self,
 8977        line_height: Pixels,
 8978        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 8979        content_origin: gpui::Point<Pixels>,
 8980        line_y: Pixels,
 8981        line_elements: &mut SmallVec<[AnyElement; 1]>,
 8982        window: &mut Window,
 8983        cx: &mut App,
 8984    ) {
 8985        let mut fragment_origin =
 8986            content_origin + gpui::point(Pixels::from(-scroll_pixel_position.x), line_y);
 8987        for fragment in &mut self.fragments {
 8988            match fragment {
 8989                LineFragment::Text(line) => {
 8990                    fragment_origin.x += line.width;
 8991                }
 8992                LineFragment::Element { element, size, .. } => {
 8993                    let mut element = element
 8994                        .take()
 8995                        .expect("you can't prepaint LineWithInvisibles twice");
 8996
 8997                    // Center the element vertically within the line.
 8998                    let mut element_origin = fragment_origin;
 8999                    element_origin.y += (line_height - size.height) / 2.;
 9000                    element.prepaint_at(element_origin, window, cx);
 9001                    line_elements.push(element);
 9002
 9003                    fragment_origin.x += size.width;
 9004                }
 9005            }
 9006        }
 9007    }
 9008
 9009    fn draw(
 9010        &self,
 9011        layout: &EditorLayout,
 9012        row: DisplayRow,
 9013        content_origin: gpui::Point<Pixels>,
 9014        whitespace_setting: ShowWhitespaceSetting,
 9015        selection_ranges: &[Range<DisplayPoint>],
 9016        window: &mut Window,
 9017        cx: &mut App,
 9018    ) {
 9019        self.draw_with_custom_offset(
 9020            layout,
 9021            row,
 9022            content_origin,
 9023            layout.position_map.line_height
 9024                * (row.as_f64() - layout.position_map.scroll_position.y) as f32,
 9025            whitespace_setting,
 9026            selection_ranges,
 9027            window,
 9028            cx,
 9029        );
 9030    }
 9031
 9032    fn draw_with_custom_offset(
 9033        &self,
 9034        layout: &EditorLayout,
 9035        row: DisplayRow,
 9036        content_origin: gpui::Point<Pixels>,
 9037        line_y: Pixels,
 9038        whitespace_setting: ShowWhitespaceSetting,
 9039        selection_ranges: &[Range<DisplayPoint>],
 9040        window: &mut Window,
 9041        cx: &mut App,
 9042    ) {
 9043        let line_height = layout.position_map.line_height;
 9044        let mut fragment_origin = content_origin
 9045            + gpui::point(
 9046                Pixels::from(-layout.position_map.scroll_pixel_position.x),
 9047                line_y,
 9048            );
 9049
 9050        for fragment in &self.fragments {
 9051            match fragment {
 9052                LineFragment::Text(line) => {
 9053                    line.paint(
 9054                        fragment_origin,
 9055                        line_height,
 9056                        layout.text_align,
 9057                        Some(layout.content_width),
 9058                        window,
 9059                        cx,
 9060                    )
 9061                    .log_err();
 9062                    fragment_origin.x += line.width;
 9063                }
 9064                LineFragment::Element { size, .. } => {
 9065                    fragment_origin.x += size.width;
 9066                }
 9067            }
 9068        }
 9069
 9070        self.draw_invisibles(
 9071            selection_ranges,
 9072            layout,
 9073            content_origin,
 9074            line_y,
 9075            row,
 9076            line_height,
 9077            whitespace_setting,
 9078            window,
 9079            cx,
 9080        );
 9081    }
 9082
 9083    fn draw_background(
 9084        &self,
 9085        layout: &EditorLayout,
 9086        row: DisplayRow,
 9087        content_origin: gpui::Point<Pixels>,
 9088        window: &mut Window,
 9089        cx: &mut App,
 9090    ) {
 9091        let line_height = layout.position_map.line_height;
 9092        let line_y = line_height * (row.as_f64() - layout.position_map.scroll_position.y) as f32;
 9093
 9094        let mut fragment_origin = content_origin
 9095            + gpui::point(
 9096                Pixels::from(-layout.position_map.scroll_pixel_position.x),
 9097                line_y,
 9098            );
 9099
 9100        for fragment in &self.fragments {
 9101            match fragment {
 9102                LineFragment::Text(line) => {
 9103                    line.paint_background(
 9104                        fragment_origin,
 9105                        line_height,
 9106                        layout.text_align,
 9107                        Some(layout.content_width),
 9108                        window,
 9109                        cx,
 9110                    )
 9111                    .log_err();
 9112                    fragment_origin.x += line.width;
 9113                }
 9114                LineFragment::Element { size, .. } => {
 9115                    fragment_origin.x += size.width;
 9116                }
 9117            }
 9118        }
 9119    }
 9120
 9121    fn draw_invisibles(
 9122        &self,
 9123        selection_ranges: &[Range<DisplayPoint>],
 9124        layout: &EditorLayout,
 9125        content_origin: gpui::Point<Pixels>,
 9126        line_y: Pixels,
 9127        row: DisplayRow,
 9128        line_height: Pixels,
 9129        whitespace_setting: ShowWhitespaceSetting,
 9130        window: &mut Window,
 9131        cx: &mut App,
 9132    ) {
 9133        let extract_whitespace_info = |invisible: &Invisible| {
 9134            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
 9135                Invisible::Tab {
 9136                    line_start_offset,
 9137                    line_end_offset,
 9138                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
 9139                Invisible::Whitespace { line_offset } => {
 9140                    (*line_offset, line_offset + 1, &layout.space_invisible)
 9141                }
 9142            };
 9143
 9144            let x_offset: ScrollPixelOffset = self.x_for_index(token_offset).into();
 9145            let invisible_offset: ScrollPixelOffset =
 9146                ((layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0)
 9147                    .into();
 9148            let origin = content_origin
 9149                + gpui::point(
 9150                    Pixels::from(
 9151                        x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
 9152                    ),
 9153                    line_y,
 9154                );
 9155
 9156            (
 9157                [token_offset, token_end_offset],
 9158                Box::new(move |window: &mut Window, cx: &mut App| {
 9159                    invisible_symbol
 9160                        .paint(origin, line_height, TextAlign::Left, None, window, cx)
 9161                        .log_err();
 9162                }),
 9163            )
 9164        };
 9165
 9166        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
 9167        match whitespace_setting {
 9168            ShowWhitespaceSetting::None => (),
 9169            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
 9170            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
 9171                let invisible_point = DisplayPoint::new(row, start as u32);
 9172                if !selection_ranges
 9173                    .iter()
 9174                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
 9175                {
 9176                    return;
 9177                }
 9178
 9179                paint(window, cx);
 9180            }),
 9181
 9182            ShowWhitespaceSetting::Trailing => {
 9183                let mut previous_start = self.len;
 9184                for ([start, end], paint) in invisible_iter.rev() {
 9185                    if previous_start != end {
 9186                        break;
 9187                    }
 9188                    previous_start = start;
 9189                    paint(window, cx);
 9190                }
 9191            }
 9192
 9193            // For a whitespace to be on a boundary, any of the following conditions need to be met:
 9194            // - It is a tab
 9195            // - It is adjacent to an edge (start or end)
 9196            // - It is adjacent to a whitespace (left or right)
 9197            ShowWhitespaceSetting::Boundary => {
 9198                // 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
 9199                // the above cases.
 9200                // Note: We zip in the original `invisibles` to check for tab equality
 9201                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
 9202                for (([start, end], paint), invisible) in
 9203                    invisible_iter.zip_eq(self.invisibles.iter())
 9204                {
 9205                    let should_render = match (&last_seen, invisible) {
 9206                        (_, Invisible::Tab { .. }) => true,
 9207                        (Some((_, last_end, _)), _) => *last_end == start,
 9208                        _ => false,
 9209                    };
 9210
 9211                    if should_render || start == 0 || end == self.len {
 9212                        paint(window, cx);
 9213
 9214                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
 9215                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
 9216                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
 9217                            // Note that we need to make sure that the last one is actually adjacent
 9218                            if !should_render_last && last_end == start {
 9219                                paint_last(window, cx);
 9220                            }
 9221                        }
 9222                    }
 9223
 9224                    // Manually render anything within a selection
 9225                    let invisible_point = DisplayPoint::new(row, start as u32);
 9226                    if selection_ranges.iter().any(|region| {
 9227                        region.start <= invisible_point && invisible_point < region.end
 9228                    }) {
 9229                        paint(window, cx);
 9230                    }
 9231
 9232                    last_seen = Some((should_render, end, paint));
 9233                }
 9234            }
 9235        }
 9236    }
 9237
 9238    pub fn x_for_index(&self, index: usize) -> Pixels {
 9239        let mut fragment_start_x = Pixels::ZERO;
 9240        let mut fragment_start_index = 0;
 9241
 9242        for fragment in &self.fragments {
 9243            match fragment {
 9244                LineFragment::Text(shaped_line) => {
 9245                    let fragment_end_index = fragment_start_index + shaped_line.len;
 9246                    if index < fragment_end_index {
 9247                        return fragment_start_x
 9248                            + shaped_line.x_for_index(index - fragment_start_index);
 9249                    }
 9250                    fragment_start_x += shaped_line.width;
 9251                    fragment_start_index = fragment_end_index;
 9252                }
 9253                LineFragment::Element { len, size, .. } => {
 9254                    let fragment_end_index = fragment_start_index + len;
 9255                    if index < fragment_end_index {
 9256                        return fragment_start_x;
 9257                    }
 9258                    fragment_start_x += size.width;
 9259                    fragment_start_index = fragment_end_index;
 9260                }
 9261            }
 9262        }
 9263
 9264        fragment_start_x
 9265    }
 9266
 9267    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
 9268        let mut fragment_start_x = Pixels::ZERO;
 9269        let mut fragment_start_index = 0;
 9270
 9271        for fragment in &self.fragments {
 9272            match fragment {
 9273                LineFragment::Text(shaped_line) => {
 9274                    let fragment_end_x = fragment_start_x + shaped_line.width;
 9275                    if x < fragment_end_x {
 9276                        return Some(
 9277                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
 9278                        );
 9279                    }
 9280                    fragment_start_x = fragment_end_x;
 9281                    fragment_start_index += shaped_line.len;
 9282                }
 9283                LineFragment::Element { len, size, .. } => {
 9284                    let fragment_end_x = fragment_start_x + size.width;
 9285                    if x < fragment_end_x {
 9286                        return Some(fragment_start_index);
 9287                    }
 9288                    fragment_start_index += len;
 9289                    fragment_start_x = fragment_end_x;
 9290                }
 9291            }
 9292        }
 9293
 9294        None
 9295    }
 9296
 9297    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
 9298        let mut fragment_start_index = 0;
 9299
 9300        for fragment in &self.fragments {
 9301            match fragment {
 9302                LineFragment::Text(shaped_line) => {
 9303                    let fragment_end_index = fragment_start_index + shaped_line.len;
 9304                    if index < fragment_end_index {
 9305                        return shaped_line.font_id_for_index(index - fragment_start_index);
 9306                    }
 9307                    fragment_start_index = fragment_end_index;
 9308                }
 9309                LineFragment::Element { len, .. } => {
 9310                    let fragment_end_index = fragment_start_index + len;
 9311                    if index < fragment_end_index {
 9312                        return None;
 9313                    }
 9314                    fragment_start_index = fragment_end_index;
 9315                }
 9316            }
 9317        }
 9318
 9319        None
 9320    }
 9321
 9322    pub fn alignment_offset(&self, text_align: TextAlign, content_width: Pixels) -> Pixels {
 9323        let line_width = self.width;
 9324        match text_align {
 9325            TextAlign::Left => px(0.0),
 9326            TextAlign::Center => (content_width - line_width) / 2.0,
 9327            TextAlign::Right => content_width - line_width,
 9328        }
 9329    }
 9330}
 9331
 9332#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 9333enum Invisible {
 9334    /// A tab character
 9335    ///
 9336    /// A tab character is internally represented by spaces (configured by the user's tab width)
 9337    /// aligned to the nearest column, so it's necessary to store the start and end offset for
 9338    /// adjacency checks.
 9339    Tab {
 9340        line_start_offset: usize,
 9341        line_end_offset: usize,
 9342    },
 9343    Whitespace {
 9344        line_offset: usize,
 9345    },
 9346}
 9347
 9348impl EditorElement {
 9349    /// Returns the rem size to use when rendering the [`EditorElement`].
 9350    ///
 9351    /// This allows UI elements to scale based on the `buffer_font_size`.
 9352    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
 9353        match self.editor.read(cx).mode {
 9354            EditorMode::Full {
 9355                scale_ui_elements_with_buffer_font_size: true,
 9356                ..
 9357            }
 9358            | EditorMode::Minimap { .. } => {
 9359                let buffer_font_size = self.style.text.font_size;
 9360                match buffer_font_size {
 9361                    AbsoluteLength::Pixels(pixels) => {
 9362                        let rem_size_scale = {
 9363                            // Our default UI font size is 14px on a 16px base scale.
 9364                            // This means the default UI font size is 0.875rems.
 9365                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
 9366
 9367                            // We then determine the delta between a single rem and the default font
 9368                            // size scale.
 9369                            let default_font_size_delta = 1. - default_font_size_scale;
 9370
 9371                            // Finally, we add this delta to 1rem to get the scale factor that
 9372                            // should be used to scale up the UI.
 9373                            1. + default_font_size_delta
 9374                        };
 9375
 9376                        Some(pixels * rem_size_scale)
 9377                    }
 9378                    AbsoluteLength::Rems(rems) => {
 9379                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
 9380                    }
 9381                }
 9382            }
 9383            // We currently use single-line and auto-height editors in UI contexts,
 9384            // so we don't want to scale everything with the buffer font size, as it
 9385            // ends up looking off.
 9386            _ => None,
 9387        }
 9388    }
 9389
 9390    fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
 9391        if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
 9392            parent.upgrade()
 9393        } else {
 9394            Some(self.editor.clone())
 9395        }
 9396    }
 9397}
 9398
 9399#[derive(Default)]
 9400pub struct EditorRequestLayoutState {
 9401    // We use prepaint depth to limit the number of times prepaint is
 9402    // called recursively. We need this so that we can update stale
 9403    // data for e.g. block heights in block map.
 9404    prepaint_depth: Rc<Cell<usize>>,
 9405}
 9406
 9407impl EditorRequestLayoutState {
 9408    // In ideal conditions we only need one more subsequent prepaint call for resize to take effect.
 9409    // i.e. MAX_PREPAINT_DEPTH = 2, but since moving blocks inline (place_near), more lines from
 9410    // below get exposed, and we end up querying blocks for those lines too in subsequent renders.
 9411    // Setting MAX_PREPAINT_DEPTH = 3, passes all tests. Just to be on the safe side we set it to 5, so
 9412    // that subsequent shrinking does not lead to incorrect block placing.
 9413    const MAX_PREPAINT_DEPTH: usize = 5;
 9414
 9415    fn increment_prepaint_depth(&self) -> EditorPrepaintGuard {
 9416        let depth = self.prepaint_depth.get();
 9417        self.prepaint_depth.set(depth + 1);
 9418        EditorPrepaintGuard {
 9419            prepaint_depth: self.prepaint_depth.clone(),
 9420        }
 9421    }
 9422
 9423    fn can_prepaint(&self) -> bool {
 9424        self.prepaint_depth.get() < Self::MAX_PREPAINT_DEPTH
 9425    }
 9426}
 9427
 9428struct EditorPrepaintGuard {
 9429    prepaint_depth: Rc<Cell<usize>>,
 9430}
 9431
 9432impl Drop for EditorPrepaintGuard {
 9433    fn drop(&mut self) {
 9434        let depth = self.prepaint_depth.get();
 9435        self.prepaint_depth.set(depth.saturating_sub(1));
 9436    }
 9437}
 9438
 9439impl Element for EditorElement {
 9440    type RequestLayoutState = EditorRequestLayoutState;
 9441    type PrepaintState = EditorLayout;
 9442
 9443    fn id(&self) -> Option<ElementId> {
 9444        None
 9445    }
 9446
 9447    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
 9448        None
 9449    }
 9450
 9451    fn request_layout(
 9452        &mut self,
 9453        _: Option<&GlobalElementId>,
 9454        _inspector_id: Option<&gpui::InspectorElementId>,
 9455        window: &mut Window,
 9456        cx: &mut App,
 9457    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
 9458        let rem_size = self.rem_size(cx);
 9459        window.with_rem_size(rem_size, |window| {
 9460            self.editor.update(cx, |editor, cx| {
 9461                editor.set_style(self.style.clone(), window, cx);
 9462
 9463                let layout_id = match editor.mode {
 9464                    EditorMode::SingleLine => {
 9465                        let rem_size = window.rem_size();
 9466                        let height = self.style.text.line_height_in_pixels(rem_size);
 9467                        let mut style = Style::default();
 9468                        style.size.height = height.into();
 9469                        style.size.width = relative(1.).into();
 9470                        window.request_layout(style, None, cx)
 9471                    }
 9472                    EditorMode::AutoHeight {
 9473                        min_lines,
 9474                        max_lines,
 9475                    } => {
 9476                        let editor_handle = cx.entity();
 9477                        window.request_measured_layout(
 9478                            Style::default(),
 9479                            move |known_dimensions, available_space, window, cx| {
 9480                                editor_handle
 9481                                    .update(cx, |editor, cx| {
 9482                                        compute_auto_height_layout(
 9483                                            editor,
 9484                                            min_lines,
 9485                                            max_lines,
 9486                                            known_dimensions,
 9487                                            available_space.width,
 9488                                            window,
 9489                                            cx,
 9490                                        )
 9491                                    })
 9492                                    .unwrap_or_default()
 9493                            },
 9494                        )
 9495                    }
 9496                    EditorMode::Minimap { .. } => {
 9497                        let mut style = Style::default();
 9498                        style.size.width = relative(1.).into();
 9499                        style.size.height = relative(1.).into();
 9500                        window.request_layout(style, None, cx)
 9501                    }
 9502                    EditorMode::Full {
 9503                        sizing_behavior, ..
 9504                    } => {
 9505                        let mut style = Style::default();
 9506                        style.size.width = relative(1.).into();
 9507                        if sizing_behavior == SizingBehavior::SizeByContent {
 9508                            let snapshot = editor.snapshot(window, cx);
 9509                            let line_height =
 9510                                self.style.text.line_height_in_pixels(window.rem_size());
 9511                            let scroll_height =
 9512                                (snapshot.max_point().row().next_row().0 as f32) * line_height;
 9513                            style.size.height = scroll_height.into();
 9514                        } else {
 9515                            style.size.height = relative(1.).into();
 9516                        }
 9517                        window.request_layout(style, None, cx)
 9518                    }
 9519                };
 9520
 9521                (layout_id, EditorRequestLayoutState::default())
 9522            })
 9523        })
 9524    }
 9525
 9526    fn prepaint(
 9527        &mut self,
 9528        _: Option<&GlobalElementId>,
 9529        _inspector_id: Option<&gpui::InspectorElementId>,
 9530        bounds: Bounds<Pixels>,
 9531        request_layout: &mut Self::RequestLayoutState,
 9532        window: &mut Window,
 9533        cx: &mut App,
 9534    ) -> Self::PrepaintState {
 9535        let _prepaint_depth_guard = request_layout.increment_prepaint_depth();
 9536        let text_style = TextStyleRefinement {
 9537            font_size: Some(self.style.text.font_size),
 9538            line_height: Some(self.style.text.line_height),
 9539            ..Default::default()
 9540        };
 9541
 9542        let is_minimap = self.editor.read(cx).mode.is_minimap();
 9543        let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
 9544
 9545        if !is_minimap {
 9546            let focus_handle = self.editor.focus_handle(cx);
 9547            window.set_view_id(self.editor.entity_id());
 9548            window.set_focus_handle(&focus_handle, cx);
 9549        }
 9550
 9551        let rem_size = self.rem_size(cx);
 9552        window.with_rem_size(rem_size, |window| {
 9553            window.with_text_style(Some(text_style), |window| {
 9554                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 9555                    let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
 9556                        (editor.snapshot(window, cx), editor.read_only(cx))
 9557                    });
 9558                    let style = &self.style;
 9559
 9560                    let rem_size = window.rem_size();
 9561                    let font_id = window.text_system().resolve_font(&style.text.font());
 9562                    let font_size = style.text.font_size.to_pixels(rem_size);
 9563                    let line_height = style.text.line_height_in_pixels(rem_size);
 9564                    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
 9565                    let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
 9566                    let em_layout_width = window.text_system().em_layout_width(font_id, font_size);
 9567                    let glyph_grid_cell = size(em_advance, line_height);
 9568
 9569                    let gutter_dimensions =
 9570                        snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
 9571                    let text_width = bounds.size.width - gutter_dimensions.width;
 9572
 9573                    let settings = EditorSettings::get_global(cx);
 9574                    let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
 9575                    let vertical_scrollbar_width = (scrollbars_shown
 9576                        && settings.scrollbar.axes.vertical
 9577                        && self.editor.read(cx).show_scrollbars.vertical)
 9578                        .then_some(style.scrollbar_width)
 9579                        .unwrap_or_default();
 9580                    let minimap_width = self
 9581                        .get_minimap_width(
 9582                            &settings.minimap,
 9583                            scrollbars_shown,
 9584                            text_width,
 9585                            em_width,
 9586                            font_size,
 9587                            rem_size,
 9588                            cx,
 9589                        )
 9590                        .unwrap_or_default();
 9591
 9592                    let right_margin = minimap_width + vertical_scrollbar_width;
 9593
 9594                    let editor_width =
 9595                        text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
 9596                    let editor_margins = EditorMargins {
 9597                        gutter: gutter_dimensions,
 9598                        right: right_margin,
 9599                    };
 9600
 9601                    snapshot = self.editor.update(cx, |editor, cx| {
 9602                        editor.last_bounds = Some(bounds);
 9603                        editor.gutter_dimensions = gutter_dimensions;
 9604                        editor.set_visible_line_count(
 9605                            (bounds.size.height / line_height) as f64,
 9606                            window,
 9607                            cx,
 9608                        );
 9609                        editor.set_visible_column_count(f64::from(editor_width / em_advance));
 9610
 9611                        if matches!(
 9612                            editor.mode,
 9613                            EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
 9614                        ) {
 9615                            snapshot
 9616                        } else {
 9617                            let wrap_width = calculate_wrap_width(
 9618                                editor.soft_wrap_mode(cx),
 9619                                editor_width,
 9620                                em_layout_width,
 9621                            );
 9622
 9623                            if editor.set_wrap_width(wrap_width, cx) {
 9624                                editor.snapshot(window, cx)
 9625                            } else {
 9626                                snapshot
 9627                            }
 9628                        }
 9629                    });
 9630
 9631                    let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
 9632                    let gutter_hitbox = window.insert_hitbox(
 9633                        gutter_bounds(bounds, gutter_dimensions),
 9634                        HitboxBehavior::Normal,
 9635                    );
 9636                    let text_hitbox = window.insert_hitbox(
 9637                        Bounds {
 9638                            origin: gutter_hitbox.top_right(),
 9639                            size: size(text_width, bounds.size.height),
 9640                        },
 9641                        HitboxBehavior::Normal,
 9642                    );
 9643
 9644                    // Offset the content_bounds from the text_bounds by the gutter margin (which
 9645                    // is roughly half a character wide) to make hit testing work more like how we want.
 9646                    let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
 9647                    let content_origin = text_hitbox.origin + content_offset;
 9648
 9649                    let height_in_lines = f64::from(bounds.size.height / line_height);
 9650                    let max_row = snapshot.max_point().row().as_f64();
 9651
 9652                    // Calculate how much of the editor is clipped by parent containers (e.g., List).
 9653                    // This allows us to only render lines that are actually visible, which is
 9654                    // critical for performance when large AutoHeight editors are inside Lists.
 9655                    let visible_bounds = window.content_mask().bounds;
 9656                    let clipped_top = (visible_bounds.origin.y - bounds.origin.y).max(px(0.));
 9657                    let clipped_top_in_lines = f64::from(clipped_top / line_height);
 9658                    let visible_height_in_lines =
 9659                        f64::from(visible_bounds.size.height / line_height);
 9660
 9661                    // The max scroll position for the top of the window
 9662                    let max_scroll_top = if matches!(
 9663                        snapshot.mode,
 9664                        EditorMode::SingleLine
 9665                            | EditorMode::AutoHeight { .. }
 9666                            | EditorMode::Full {
 9667                                sizing_behavior: SizingBehavior::ExcludeOverscrollMargin
 9668                                    | SizingBehavior::SizeByContent,
 9669                                ..
 9670                            }
 9671                    ) {
 9672                        (max_row - height_in_lines + 1.).max(0.)
 9673                    } else {
 9674                        let settings = EditorSettings::get_global(cx);
 9675                        match settings.scroll_beyond_last_line {
 9676                            ScrollBeyondLastLine::OnePage => max_row,
 9677                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
 9678                            ScrollBeyondLastLine::VerticalScrollMargin => {
 9679                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
 9680                                    .max(0.)
 9681                            }
 9682                        }
 9683                    };
 9684
 9685                    let (
 9686                        autoscroll_request,
 9687                        autoscroll_containing_element,
 9688                        needs_horizontal_autoscroll,
 9689                    ) = self.editor.update(cx, |editor, cx| {
 9690                        let autoscroll_request = editor.scroll_manager.take_autoscroll_request();
 9691
 9692                        let autoscroll_containing_element =
 9693                            autoscroll_request.is_some() || editor.has_pending_selection();
 9694
 9695                        let (needs_horizontal_autoscroll, was_scrolled) = editor
 9696                            .autoscroll_vertically(
 9697                                bounds,
 9698                                line_height,
 9699                                max_scroll_top,
 9700                                autoscroll_request,
 9701                                window,
 9702                                cx,
 9703                            );
 9704                        if was_scrolled.0 {
 9705                            snapshot = editor.snapshot(window, cx);
 9706                        }
 9707                        (
 9708                            autoscroll_request,
 9709                            autoscroll_containing_element,
 9710                            needs_horizontal_autoscroll,
 9711                        )
 9712                    });
 9713
 9714                    let mut scroll_position = snapshot.scroll_position();
 9715                    // The scroll position is a fractional point, the whole number of which represents
 9716                    // the top of the window in terms of display rows.
 9717                    // We add clipped_top_in_lines to skip rows that are clipped by parent containers,
 9718                    // but we don't modify scroll_position itself since the parent handles positioning.
 9719                    let max_row = snapshot.max_point().row();
 9720                    let start_row = cmp::min(
 9721                        DisplayRow((scroll_position.y + clipped_top_in_lines).floor() as u32),
 9722                        max_row,
 9723                    );
 9724                    let end_row = cmp::min(
 9725                        (scroll_position.y + clipped_top_in_lines + visible_height_in_lines).ceil()
 9726                            as u32,
 9727                        max_row.next_row().0,
 9728                    );
 9729                    let end_row = DisplayRow(end_row);
 9730
 9731                    let row_infos = snapshot // note we only get the visual range
 9732                        .row_infos(start_row)
 9733                        .take((start_row..end_row).len())
 9734                        .collect::<Vec<RowInfo>>();
 9735                    let is_row_soft_wrapped = |row: usize| {
 9736                        row_infos
 9737                            .get(row)
 9738                            .is_none_or(|info| info.buffer_row.is_none())
 9739                    };
 9740
 9741                    let start_anchor = if start_row == Default::default() {
 9742                        Anchor::min()
 9743                    } else {
 9744                        snapshot.buffer_snapshot().anchor_before(
 9745                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
 9746                        )
 9747                    };
 9748                    let end_anchor = if end_row > max_row {
 9749                        Anchor::max()
 9750                    } else {
 9751                        snapshot.buffer_snapshot().anchor_before(
 9752                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
 9753                        )
 9754                    };
 9755
 9756                    let mut highlighted_rows = self
 9757                        .editor
 9758                        .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
 9759
 9760                    let is_light = cx.theme().appearance().is_light();
 9761
 9762                    let mut highlighted_ranges = self
 9763                        .editor_with_selections(cx)
 9764                        .map(|editor| {
 9765                            if editor == self.editor {
 9766                                editor.read(cx).background_highlights_in_range(
 9767                                    start_anchor..end_anchor,
 9768                                    &snapshot.display_snapshot,
 9769                                    cx.theme(),
 9770                                )
 9771                            } else {
 9772                                editor.update(cx, |editor, cx| {
 9773                                    let snapshot = editor.snapshot(window, cx);
 9774                                    let start_anchor = if start_row == Default::default() {
 9775                                        Anchor::min()
 9776                                    } else {
 9777                                        snapshot.buffer_snapshot().anchor_before(
 9778                                            DisplayPoint::new(start_row, 0)
 9779                                                .to_offset(&snapshot, Bias::Left),
 9780                                        )
 9781                                    };
 9782                                    let end_anchor = if end_row > max_row {
 9783                                        Anchor::max()
 9784                                    } else {
 9785                                        snapshot.buffer_snapshot().anchor_before(
 9786                                            DisplayPoint::new(end_row, 0)
 9787                                                .to_offset(&snapshot, Bias::Right),
 9788                                        )
 9789                                    };
 9790
 9791                                    editor.background_highlights_in_range(
 9792                                        start_anchor..end_anchor,
 9793                                        &snapshot.display_snapshot,
 9794                                        cx.theme(),
 9795                                    )
 9796                                })
 9797                            }
 9798                        })
 9799                        .unwrap_or_default();
 9800
 9801                    for (ix, row_info) in row_infos.iter().enumerate() {
 9802                        let Some(diff_status) = row_info.diff_status else {
 9803                            continue;
 9804                        };
 9805
 9806                        let background_color = match diff_status.kind {
 9807                            DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
 9808                            DiffHunkStatusKind::Deleted => {
 9809                                cx.theme().colors().version_control_deleted
 9810                            }
 9811                            DiffHunkStatusKind::Modified => {
 9812                                debug_panic!("modified diff status for row info");
 9813                                continue;
 9814                            }
 9815                        };
 9816
 9817                        let hunk_opacity = if is_light { 0.16 } else { 0.12 };
 9818
 9819                        let hollow_highlight = LineHighlight {
 9820                            background: (background_color.opacity(if is_light {
 9821                                0.08
 9822                            } else {
 9823                                0.06
 9824                            }))
 9825                            .into(),
 9826                            border: Some(if is_light {
 9827                                background_color.opacity(0.48)
 9828                            } else {
 9829                                background_color.opacity(0.36)
 9830                            }),
 9831                            include_gutter: true,
 9832                            type_id: None,
 9833                        };
 9834
 9835                        let filled_highlight = LineHighlight {
 9836                            background: solid_background(background_color.opacity(hunk_opacity)),
 9837                            border: None,
 9838                            include_gutter: true,
 9839                            type_id: None,
 9840                        };
 9841
 9842                        let background = if Self::diff_hunk_hollow(diff_status, cx) {
 9843                            hollow_highlight
 9844                        } else {
 9845                            filled_highlight
 9846                        };
 9847
 9848                        let base_display_point =
 9849                            DisplayPoint::new(start_row + DisplayRow(ix as u32), 0);
 9850
 9851                        highlighted_rows
 9852                            .entry(base_display_point.row())
 9853                            .or_insert(background);
 9854                    }
 9855
 9856                    // Add diff review drag selection highlight to text area
 9857                    if let Some(drag_state) = &self.editor.read(cx).diff_review_drag_state {
 9858                        let range = drag_state.row_range(&snapshot.display_snapshot);
 9859                        let start_row = range.start().0;
 9860                        let end_row = range.end().0;
 9861                        let drag_highlight_color =
 9862                            cx.theme().colors().editor_active_line_background;
 9863                        let drag_highlight = LineHighlight {
 9864                            background: solid_background(drag_highlight_color),
 9865                            border: Some(cx.theme().colors().border_focused),
 9866                            include_gutter: true,
 9867                            type_id: None,
 9868                        };
 9869                        for row_num in start_row..=end_row {
 9870                            highlighted_rows
 9871                                .entry(DisplayRow(row_num))
 9872                                .or_insert(drag_highlight);
 9873                        }
 9874                    }
 9875
 9876                    let highlighted_gutter_ranges =
 9877                        self.editor.read(cx).gutter_highlights_in_range(
 9878                            start_anchor..end_anchor,
 9879                            &snapshot.display_snapshot,
 9880                            cx,
 9881                        );
 9882
 9883                    let document_colors = self
 9884                        .editor
 9885                        .read(cx)
 9886                        .colors
 9887                        .as_ref()
 9888                        .map(|colors| colors.editor_display_highlights(&snapshot));
 9889                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
 9890                        start_anchor..end_anchor,
 9891                        &snapshot.display_snapshot,
 9892                        cx,
 9893                    );
 9894
 9895                    let (local_selections, selected_buffer_ids, latest_selection_anchors): (
 9896                        Vec<Selection<Point>>,
 9897                        Vec<BufferId>,
 9898                        HashMap<BufferId, Anchor>,
 9899                    ) = self
 9900                        .editor_with_selections(cx)
 9901                        .map(|editor| {
 9902                            editor.update(cx, |editor, cx| {
 9903                                let all_selections =
 9904                                    editor.selections.all::<Point>(&snapshot.display_snapshot);
 9905                                let all_anchor_selections =
 9906                                    editor.selections.all_anchors(&snapshot.display_snapshot);
 9907                                let selected_buffer_ids =
 9908                                    if editor.buffer_kind(cx) == ItemBufferKind::Singleton {
 9909                                        Vec::new()
 9910                                    } else {
 9911                                        let mut selected_buffer_ids =
 9912                                            Vec::with_capacity(all_selections.len());
 9913
 9914                                        for selection in all_selections {
 9915                                            for buffer_id in snapshot
 9916                                                .buffer_snapshot()
 9917                                                .buffer_ids_for_range(selection.range())
 9918                                            {
 9919                                                if selected_buffer_ids.last() != Some(&buffer_id) {
 9920                                                    selected_buffer_ids.push(buffer_id);
 9921                                                }
 9922                                            }
 9923                                        }
 9924
 9925                                        selected_buffer_ids
 9926                                    };
 9927
 9928                                let mut selections = editor.selections.disjoint_in_range(
 9929                                    start_anchor..end_anchor,
 9930                                    &snapshot.display_snapshot,
 9931                                );
 9932                                selections
 9933                                    .extend(editor.selections.pending(&snapshot.display_snapshot));
 9934
 9935                                let mut anchors_by_buffer: HashMap<BufferId, (usize, Anchor)> =
 9936                                    HashMap::default();
 9937                                for selection in all_anchor_selections.iter() {
 9938                                    let head = selection.head();
 9939                                    if let Some(buffer_id) = head.text_anchor.buffer_id {
 9940                                        anchors_by_buffer
 9941                                            .entry(buffer_id)
 9942                                            .and_modify(|(latest_id, latest_anchor)| {
 9943                                                if selection.id > *latest_id {
 9944                                                    *latest_id = selection.id;
 9945                                                    *latest_anchor = head;
 9946                                                }
 9947                                            })
 9948                                            .or_insert((selection.id, head));
 9949                                    }
 9950                                }
 9951                                let latest_selection_anchors = anchors_by_buffer
 9952                                    .into_iter()
 9953                                    .map(|(buffer_id, (_, anchor))| (buffer_id, anchor))
 9954                                    .collect();
 9955
 9956                                (selections, selected_buffer_ids, latest_selection_anchors)
 9957                            })
 9958                        })
 9959                        .unwrap_or_else(|| (Vec::new(), Vec::new(), HashMap::default()));
 9960
 9961                    let (selections, mut active_rows, newest_selection_head) = self
 9962                        .layout_selections(
 9963                            start_anchor,
 9964                            end_anchor,
 9965                            &local_selections,
 9966                            &snapshot,
 9967                            start_row,
 9968                            end_row,
 9969                            window,
 9970                            cx,
 9971                        );
 9972
 9973                    // relative rows are based on newest selection, even outside the visible area
 9974                    let current_selection_head = self.editor.update(cx, |editor, cx| {
 9975                        (editor.selections.count() != 0).then(|| {
 9976                            let newest = editor
 9977                                .selections
 9978                                .newest::<Point>(&editor.display_snapshot(cx));
 9979
 9980                            SelectionLayout::new(
 9981                                newest,
 9982                                editor.selections.line_mode(),
 9983                                editor.cursor_offset_on_selection,
 9984                                editor.cursor_shape,
 9985                                &snapshot,
 9986                                true,
 9987                                true,
 9988                                None,
 9989                            )
 9990                            .head
 9991                            .row()
 9992                        })
 9993                    });
 9994
 9995                    let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
 9996                        editor.active_breakpoints(start_row..end_row, window, cx)
 9997                    });
 9998                    for (display_row, (_, bp, state)) in &breakpoint_rows {
 9999                        if bp.is_enabled() && state.is_none_or(|s| s.verified) {
10000                            active_rows.entry(*display_row).or_default().breakpoint = true;
10001                        }
10002                    }
10003
10004                    let line_numbers = self.layout_line_numbers(
10005                        Some(&gutter_hitbox),
10006                        gutter_dimensions,
10007                        line_height,
10008                        scroll_position,
10009                        start_row..end_row,
10010                        &row_infos,
10011                        &active_rows,
10012                        current_selection_head,
10013                        &snapshot,
10014                        window,
10015                        cx,
10016                    );
10017
10018                    // We add the gutter breakpoint indicator to breakpoint_rows after painting
10019                    // line numbers so we don't paint a line number debug accent color if a user
10020                    // has their mouse over that line when a breakpoint isn't there
10021                    self.editor.update(cx, |editor, _| {
10022                        if let Some(phantom_breakpoint) = &mut editor
10023                            .gutter_breakpoint_indicator
10024                            .0
10025                            .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
10026                        {
10027                            // Is there a non-phantom breakpoint on this line?
10028                            phantom_breakpoint.collides_with_existing_breakpoint = true;
10029                            breakpoint_rows
10030                                .entry(phantom_breakpoint.display_row)
10031                                .or_insert_with(|| {
10032                                    let position = snapshot.display_point_to_anchor(
10033                                        DisplayPoint::new(phantom_breakpoint.display_row, 0),
10034                                        Bias::Right,
10035                                    );
10036                                    let breakpoint = Breakpoint::new_standard();
10037                                    phantom_breakpoint.collides_with_existing_breakpoint = false;
10038                                    (position, breakpoint, None)
10039                                });
10040                        }
10041                    });
10042
10043                    let mut expand_toggles =
10044                        window.with_element_namespace("expand_toggles", |window| {
10045                            self.layout_expand_toggles(
10046                                &gutter_hitbox,
10047                                gutter_dimensions,
10048                                em_width,
10049                                line_height,
10050                                scroll_position,
10051                                &row_infos,
10052                                window,
10053                                cx,
10054                            )
10055                        });
10056
10057                    let mut crease_toggles =
10058                        window.with_element_namespace("crease_toggles", |window| {
10059                            self.layout_crease_toggles(
10060                                start_row..end_row,
10061                                &row_infos,
10062                                &active_rows,
10063                                &snapshot,
10064                                window,
10065                                cx,
10066                            )
10067                        });
10068                    let crease_trailers =
10069                        window.with_element_namespace("crease_trailers", |window| {
10070                            self.layout_crease_trailers(
10071                                row_infos.iter().cloned(),
10072                                &snapshot,
10073                                window,
10074                                cx,
10075                            )
10076                        });
10077
10078                    let display_hunks = self.layout_gutter_diff_hunks(
10079                        line_height,
10080                        &gutter_hitbox,
10081                        start_row..end_row,
10082                        &snapshot,
10083                        window,
10084                        cx,
10085                    );
10086
10087                    Self::layout_word_diff_highlights(
10088                        &display_hunks,
10089                        &row_infos,
10090                        start_row,
10091                        &snapshot,
10092                        &mut highlighted_ranges,
10093                        cx,
10094                    );
10095
10096                    let merged_highlighted_ranges =
10097                        if let Some((_, colors)) = document_colors.as_ref() {
10098                            &highlighted_ranges
10099                                .clone()
10100                                .into_iter()
10101                                .chain(colors.clone())
10102                                .collect()
10103                        } else {
10104                            &highlighted_ranges
10105                        };
10106                    let bg_segments_per_row = Self::bg_segments_per_row(
10107                        start_row..end_row,
10108                        &selections,
10109                        &merged_highlighted_ranges,
10110                        self.style.background,
10111                    );
10112
10113                    let mut line_layouts = Self::layout_lines(
10114                        start_row..end_row,
10115                        &snapshot,
10116                        &self.style,
10117                        editor_width,
10118                        is_row_soft_wrapped,
10119                        &bg_segments_per_row,
10120                        window,
10121                        cx,
10122                    );
10123                    let new_renderer_widths = (!is_minimap).then(|| {
10124                        line_layouts
10125                            .iter()
10126                            .flat_map(|layout| &layout.fragments)
10127                            .filter_map(|fragment| {
10128                                if let LineFragment::Element { id, size, .. } = fragment {
10129                                    Some((*id, size.width))
10130                                } else {
10131                                    None
10132                                }
10133                            })
10134                    });
10135                    if new_renderer_widths.is_some_and(|new_renderer_widths| {
10136                        self.editor.update(cx, |editor, cx| {
10137                            editor.update_renderer_widths(new_renderer_widths, cx)
10138                        })
10139                    }) {
10140                        // If the fold widths have changed, we need to prepaint
10141                        // the element again to account for any changes in
10142                        // wrapping.
10143                        if request_layout.can_prepaint() {
10144                            return self.prepaint(
10145                                None,
10146                                _inspector_id,
10147                                bounds,
10148                                request_layout,
10149                                window,
10150                                cx,
10151                            );
10152                        } else {
10153                            debug_panic!(concat!(
10154                                "skipping recursive prepaint at max depth. ",
10155                                "renderer widths may be stale."
10156                            ));
10157                        }
10158                    }
10159
10160                    let longest_line_blame_width = self
10161                        .editor
10162                        .update(cx, |editor, cx| {
10163                            if !editor.show_git_blame_inline {
10164                                return None;
10165                            }
10166                            let blame = editor.blame.as_ref()?;
10167                            let (_, blame_entry) = blame
10168                                .update(cx, |blame, cx| {
10169                                    let row_infos =
10170                                        snapshot.row_infos(snapshot.longest_row()).next()?;
10171                                    blame.blame_for_rows(&[row_infos], cx).next()
10172                                })
10173                                .flatten()?;
10174                            let mut element = render_inline_blame_entry(blame_entry, style, cx)?;
10175                            let inline_blame_padding =
10176                                ProjectSettings::get_global(cx).git.inline_blame.padding as f32
10177                                    * em_advance;
10178                            Some(
10179                                element
10180                                    .layout_as_root(AvailableSpace::min_size(), window, cx)
10181                                    .width
10182                                    + inline_blame_padding,
10183                            )
10184                        })
10185                        .unwrap_or(Pixels::ZERO);
10186
10187                    let longest_line_width = layout_line(
10188                        snapshot.longest_row(),
10189                        &snapshot,
10190                        style,
10191                        editor_width,
10192                        is_row_soft_wrapped,
10193                        window,
10194                        cx,
10195                    )
10196                    .width;
10197
10198                    let scrollbar_layout_information = ScrollbarLayoutInformation::new(
10199                        text_hitbox.bounds,
10200                        glyph_grid_cell,
10201                        size(
10202                            longest_line_width,
10203                            Pixels::from(max_row.as_f64() * f64::from(line_height)),
10204                        ),
10205                        longest_line_blame_width,
10206                        EditorSettings::get_global(cx),
10207                    );
10208
10209                    let mut scroll_width = scrollbar_layout_information.scroll_range.width;
10210
10211                    let sticky_header_excerpt = if snapshot.buffer_snapshot().show_headers() {
10212                        snapshot.sticky_header_excerpt(scroll_position.y)
10213                    } else {
10214                        None
10215                    };
10216                    let sticky_header_excerpt_id =
10217                        sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
10218
10219                    let blocks = (!is_minimap)
10220                        .then(|| {
10221                            window.with_element_namespace("blocks", |window| {
10222                                self.render_blocks(
10223                                    start_row..end_row,
10224                                    &snapshot,
10225                                    &hitbox,
10226                                    &text_hitbox,
10227                                    editor_width,
10228                                    &mut scroll_width,
10229                                    &editor_margins,
10230                                    em_width,
10231                                    gutter_dimensions.full_width(),
10232                                    line_height,
10233                                    &mut line_layouts,
10234                                    &local_selections,
10235                                    &selected_buffer_ids,
10236                                    &latest_selection_anchors,
10237                                    is_row_soft_wrapped,
10238                                    sticky_header_excerpt_id,
10239                                    window,
10240                                    cx,
10241                                )
10242                            })
10243                        })
10244                        .unwrap_or_default();
10245                    let RenderBlocksOutput {
10246                        mut blocks,
10247                        row_block_types,
10248                        resized_blocks,
10249                    } = blocks;
10250                    if let Some(resized_blocks) = resized_blocks {
10251                        self.editor.update(cx, |editor, cx| {
10252                            editor.resize_blocks(
10253                                resized_blocks,
10254                                autoscroll_request.map(|(autoscroll, _)| autoscroll),
10255                                cx,
10256                            )
10257                        });
10258                        if request_layout.can_prepaint() {
10259                            return self.prepaint(
10260                                None,
10261                                _inspector_id,
10262                                bounds,
10263                                request_layout,
10264                                window,
10265                                cx,
10266                            );
10267                        } else {
10268                            debug_panic!(concat!(
10269                                "skipping recursive prepaint at max depth. ",
10270                                "block layout may be stale."
10271                            ));
10272                        }
10273                    }
10274
10275                    let sticky_buffer_header = if self.should_show_buffer_headers() {
10276                        sticky_header_excerpt.map(|sticky_header_excerpt| {
10277                            window.with_element_namespace("blocks", |window| {
10278                                self.layout_sticky_buffer_header(
10279                                    sticky_header_excerpt,
10280                                    scroll_position,
10281                                    line_height,
10282                                    right_margin,
10283                                    &snapshot,
10284                                    &hitbox,
10285                                    &selected_buffer_ids,
10286                                    &blocks,
10287                                    &latest_selection_anchors,
10288                                    window,
10289                                    cx,
10290                                )
10291                            })
10292                        })
10293                    } else {
10294                        None
10295                    };
10296
10297                    let start_buffer_row =
10298                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot()).row);
10299                    let end_buffer_row =
10300                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot()).row);
10301
10302                    let scroll_max: gpui::Point<ScrollPixelOffset> = point(
10303                        ScrollPixelOffset::from(
10304                            ((scroll_width - editor_width) / em_layout_width).max(0.0),
10305                        ),
10306                        max_scroll_top,
10307                    );
10308
10309                    self.editor.update(cx, |editor, cx| {
10310                        if editor.scroll_manager.clamp_scroll_left(scroll_max.x, cx) {
10311                            scroll_position.x = scroll_max.x.min(scroll_position.x);
10312                        }
10313
10314                        if needs_horizontal_autoscroll.0
10315                            && let Some(new_scroll_position) = editor.autoscroll_horizontally(
10316                                start_row,
10317                                editor_width,
10318                                scroll_width,
10319                                em_advance,
10320                                &line_layouts,
10321                                autoscroll_request,
10322                                window,
10323                                cx,
10324                            )
10325                        {
10326                            scroll_position = new_scroll_position;
10327                        }
10328                    });
10329
10330                    let scroll_pixel_position = point(
10331                        scroll_position.x * f64::from(em_layout_width),
10332                        scroll_position.y * f64::from(line_height),
10333                    );
10334                    let sticky_headers = if !is_minimap
10335                        && is_singleton
10336                        && EditorSettings::get_global(cx).sticky_scroll.enabled
10337                    {
10338                        let relative = self.editor.read(cx).relative_line_numbers(cx);
10339                        self.layout_sticky_headers(
10340                            &snapshot,
10341                            editor_width,
10342                            is_row_soft_wrapped,
10343                            line_height,
10344                            scroll_pixel_position,
10345                            content_origin,
10346                            &gutter_dimensions,
10347                            &gutter_hitbox,
10348                            &text_hitbox,
10349                            relative,
10350                            current_selection_head,
10351                            window,
10352                            cx,
10353                        )
10354                    } else {
10355                        None
10356                    };
10357                    self.editor.update(cx, |editor, _| {
10358                        editor.scroll_manager.set_sticky_header_line_count(
10359                            sticky_headers.as_ref().map_or(0, |h| h.lines.len()),
10360                        );
10361                    });
10362                    let indent_guides = self.layout_indent_guides(
10363                        content_origin,
10364                        text_hitbox.origin,
10365                        start_buffer_row..end_buffer_row,
10366                        scroll_pixel_position,
10367                        line_height,
10368                        &snapshot,
10369                        window,
10370                        cx,
10371                    );
10372
10373                    let crease_trailers =
10374                        window.with_element_namespace("crease_trailers", |window| {
10375                            self.prepaint_crease_trailers(
10376                                crease_trailers,
10377                                &line_layouts,
10378                                line_height,
10379                                content_origin,
10380                                scroll_pixel_position,
10381                                em_width,
10382                                window,
10383                                cx,
10384                            )
10385                        });
10386
10387                    let (edit_prediction_popover, edit_prediction_popover_origin) = self
10388                        .editor
10389                        .update(cx, |editor, cx| {
10390                            editor.render_edit_prediction_popover(
10391                                &text_hitbox.bounds,
10392                                content_origin,
10393                                right_margin,
10394                                &snapshot,
10395                                start_row..end_row,
10396                                scroll_position.y,
10397                                scroll_position.y + height_in_lines,
10398                                &line_layouts,
10399                                line_height,
10400                                scroll_position,
10401                                scroll_pixel_position,
10402                                newest_selection_head,
10403                                editor_width,
10404                                style,
10405                                window,
10406                                cx,
10407                            )
10408                        })
10409                        .unzip();
10410
10411                    let mut inline_diagnostics = self.layout_inline_diagnostics(
10412                        &line_layouts,
10413                        &crease_trailers,
10414                        &row_block_types,
10415                        content_origin,
10416                        scroll_position,
10417                        scroll_pixel_position,
10418                        edit_prediction_popover_origin,
10419                        start_row,
10420                        end_row,
10421                        line_height,
10422                        em_width,
10423                        style,
10424                        window,
10425                        cx,
10426                    );
10427
10428                    let mut inline_blame_layout = None;
10429                    let mut inline_code_actions = None;
10430                    if let Some(newest_selection_head) = newest_selection_head {
10431                        let display_row = newest_selection_head.row();
10432                        if (start_row..end_row).contains(&display_row)
10433                            && !row_block_types.contains_key(&display_row)
10434                        {
10435                            inline_code_actions = self.layout_inline_code_actions(
10436                                newest_selection_head,
10437                                content_origin,
10438                                scroll_position,
10439                                scroll_pixel_position,
10440                                line_height,
10441                                &snapshot,
10442                                window,
10443                                cx,
10444                            );
10445
10446                            let line_ix = display_row.minus(start_row) as usize;
10447                            if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
10448                                row_infos.get(line_ix),
10449                                line_layouts.get(line_ix),
10450                                crease_trailers.get(line_ix),
10451                            ) {
10452                                let crease_trailer_layout = crease_trailer.as_ref();
10453                                if let Some(layout) = self.layout_inline_blame(
10454                                    display_row,
10455                                    row_info,
10456                                    line_layout,
10457                                    crease_trailer_layout,
10458                                    em_width,
10459                                    content_origin,
10460                                    scroll_position,
10461                                    scroll_pixel_position,
10462                                    line_height,
10463                                    window,
10464                                    cx,
10465                                ) {
10466                                    inline_blame_layout = Some(layout);
10467                                    // Blame overrides inline diagnostics
10468                                    inline_diagnostics.remove(&display_row);
10469                                }
10470                            } else {
10471                                log::error!(
10472                                    "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
10473                                    line_layouts.len(): {}, \
10474                                    crease_trailers.len(): {}",
10475                                    line_ix,
10476                                    row_infos.len(),
10477                                    line_layouts.len(),
10478                                    crease_trailers.len(),
10479                                );
10480                            }
10481                        }
10482                    }
10483
10484                    let blamed_display_rows = self.layout_blame_entries(
10485                        &row_infos,
10486                        em_width,
10487                        scroll_position,
10488                        line_height,
10489                        &gutter_hitbox,
10490                        gutter_dimensions.git_blame_entries_width,
10491                        window,
10492                        cx,
10493                    );
10494
10495                    let line_elements = self.prepaint_lines(
10496                        start_row,
10497                        &mut line_layouts,
10498                        line_height,
10499                        scroll_position,
10500                        scroll_pixel_position,
10501                        content_origin,
10502                        window,
10503                        cx,
10504                    );
10505
10506                    window.with_element_namespace("blocks", |window| {
10507                        self.layout_blocks(
10508                            &mut blocks,
10509                            &hitbox,
10510                            line_height,
10511                            scroll_position,
10512                            scroll_pixel_position,
10513                            window,
10514                            cx,
10515                        );
10516                    });
10517
10518                    let cursors = self.collect_cursors(&snapshot, cx);
10519                    let visible_row_range = start_row..end_row;
10520                    let non_visible_cursors = cursors
10521                        .iter()
10522                        .any(|c| !visible_row_range.contains(&c.0.row()));
10523
10524                    let visible_cursors = self.layout_visible_cursors(
10525                        &snapshot,
10526                        &selections,
10527                        &row_block_types,
10528                        start_row..end_row,
10529                        &line_layouts,
10530                        &text_hitbox,
10531                        content_origin,
10532                        scroll_position,
10533                        scroll_pixel_position,
10534                        line_height,
10535                        em_width,
10536                        em_advance,
10537                        autoscroll_containing_element,
10538                        &redacted_ranges,
10539                        window,
10540                        cx,
10541                    );
10542
10543                    let scrollbars_layout = self.layout_scrollbars(
10544                        &snapshot,
10545                        &scrollbar_layout_information,
10546                        content_offset,
10547                        scroll_position,
10548                        non_visible_cursors,
10549                        right_margin,
10550                        editor_width,
10551                        window,
10552                        cx,
10553                    );
10554
10555                    let gutter_settings = EditorSettings::get_global(cx).gutter;
10556
10557                    let context_menu_layout =
10558                        if let Some(newest_selection_head) = newest_selection_head {
10559                            let newest_selection_point =
10560                                newest_selection_head.to_point(&snapshot.display_snapshot);
10561                            if (start_row..end_row).contains(&newest_selection_head.row()) {
10562                                self.layout_cursor_popovers(
10563                                    line_height,
10564                                    &text_hitbox,
10565                                    content_origin,
10566                                    right_margin,
10567                                    start_row,
10568                                    scroll_pixel_position,
10569                                    &line_layouts,
10570                                    newest_selection_head,
10571                                    newest_selection_point,
10572                                    style,
10573                                    window,
10574                                    cx,
10575                                )
10576                            } else {
10577                                None
10578                            }
10579                        } else {
10580                            None
10581                        };
10582
10583                    self.layout_gutter_menu(
10584                        line_height,
10585                        &text_hitbox,
10586                        content_origin,
10587                        right_margin,
10588                        scroll_pixel_position,
10589                        gutter_dimensions.width - gutter_dimensions.left_padding,
10590                        window,
10591                        cx,
10592                    );
10593
10594                    let test_indicators = if gutter_settings.runnables {
10595                        self.layout_run_indicators(
10596                            line_height,
10597                            start_row..end_row,
10598                            &row_infos,
10599                            scroll_position,
10600                            &gutter_dimensions,
10601                            &gutter_hitbox,
10602                            &snapshot,
10603                            &mut breakpoint_rows,
10604                            window,
10605                            cx,
10606                        )
10607                    } else {
10608                        Vec::new()
10609                    };
10610
10611                    let show_breakpoints = snapshot
10612                        .show_breakpoints
10613                        .unwrap_or(gutter_settings.breakpoints);
10614                    let breakpoints = if show_breakpoints {
10615                        self.layout_breakpoints(
10616                            line_height,
10617                            start_row..end_row,
10618                            scroll_position,
10619                            &gutter_dimensions,
10620                            &gutter_hitbox,
10621                            &snapshot,
10622                            breakpoint_rows,
10623                            &row_infos,
10624                            window,
10625                            cx,
10626                        )
10627                    } else {
10628                        Vec::new()
10629                    };
10630
10631                    let git_gutter_width = Self::gutter_strip_width(line_height)
10632                        + gutter_dimensions
10633                            .git_blame_entries_width
10634                            .unwrap_or_default();
10635                    let available_width = gutter_dimensions.left_padding - git_gutter_width;
10636
10637                    let max_line_number_length = self
10638                        .editor
10639                        .read(cx)
10640                        .buffer()
10641                        .read(cx)
10642                        .snapshot(cx)
10643                        .widest_line_number()
10644                        .ilog10()
10645                        + 1;
10646
10647                    let diff_review_button = self
10648                        .should_render_diff_review_button(
10649                            start_row..end_row,
10650                            &row_infos,
10651                            &snapshot,
10652                            cx,
10653                        )
10654                        .map(|(display_row, buffer_row)| {
10655                            let is_wide = max_line_number_length
10656                                >= EditorSettings::get_global(cx).gutter.min_line_number_digits
10657                                    as u32
10658                                && buffer_row.is_some_and(|row| {
10659                                    (row + 1).ilog10() + 1 == max_line_number_length
10660                                })
10661                                || gutter_dimensions.right_padding == px(0.);
10662
10663                            let button_width = if is_wide {
10664                                available_width - px(6.)
10665                            } else {
10666                                available_width + em_width - px(6.)
10667                            };
10668
10669                            let button = self.editor.update(cx, |editor, cx| {
10670                                editor
10671                                    .render_diff_review_button(display_row, button_width, cx)
10672                                    .into_any_element()
10673                            });
10674                            prepaint_gutter_button(
10675                                button,
10676                                display_row,
10677                                line_height,
10678                                &gutter_dimensions,
10679                                scroll_position,
10680                                &gutter_hitbox,
10681                                window,
10682                                cx,
10683                            )
10684                        });
10685
10686                    self.layout_signature_help(
10687                        &hitbox,
10688                        content_origin,
10689                        scroll_pixel_position,
10690                        newest_selection_head,
10691                        start_row,
10692                        &line_layouts,
10693                        line_height,
10694                        em_width,
10695                        context_menu_layout,
10696                        window,
10697                        cx,
10698                    );
10699
10700                    if !cx.has_active_drag() {
10701                        self.layout_hover_popovers(
10702                            &snapshot,
10703                            &hitbox,
10704                            start_row..end_row,
10705                            content_origin,
10706                            scroll_pixel_position,
10707                            &line_layouts,
10708                            line_height,
10709                            em_width,
10710                            context_menu_layout,
10711                            window,
10712                            cx,
10713                        );
10714
10715                        self.layout_blame_popover(&snapshot, &hitbox, line_height, window, cx);
10716                    }
10717
10718                    let mouse_context_menu = self.layout_mouse_context_menu(
10719                        &snapshot,
10720                        start_row..end_row,
10721                        content_origin,
10722                        window,
10723                        cx,
10724                    );
10725
10726                    window.with_element_namespace("crease_toggles", |window| {
10727                        self.prepaint_crease_toggles(
10728                            &mut crease_toggles,
10729                            line_height,
10730                            &gutter_dimensions,
10731                            gutter_settings,
10732                            scroll_pixel_position,
10733                            &gutter_hitbox,
10734                            window,
10735                            cx,
10736                        )
10737                    });
10738
10739                    window.with_element_namespace("expand_toggles", |window| {
10740                        self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
10741                    });
10742
10743                    let wrap_guides = self.layout_wrap_guides(
10744                        em_advance,
10745                        scroll_position,
10746                        content_origin,
10747                        scrollbars_layout.as_ref(),
10748                        vertical_scrollbar_width,
10749                        &hitbox,
10750                        window,
10751                        cx,
10752                    );
10753
10754                    let minimap = window.with_element_namespace("minimap", |window| {
10755                        self.layout_minimap(
10756                            &snapshot,
10757                            minimap_width,
10758                            scroll_position,
10759                            &scrollbar_layout_information,
10760                            scrollbars_layout.as_ref(),
10761                            window,
10762                            cx,
10763                        )
10764                    });
10765
10766                    let invisible_symbol_font_size = font_size / 2.;
10767                    let whitespace_map = &self
10768                        .editor
10769                        .read(cx)
10770                        .buffer
10771                        .read(cx)
10772                        .language_settings(cx)
10773                        .whitespace_map;
10774
10775                    let tab_char = whitespace_map.tab.clone();
10776                    let tab_len = tab_char.len();
10777                    let tab_invisible = window.text_system().shape_line(
10778                        tab_char,
10779                        invisible_symbol_font_size,
10780                        &[TextRun {
10781                            len: tab_len,
10782                            font: self.style.text.font(),
10783                            color: cx.theme().colors().editor_invisible,
10784                            ..Default::default()
10785                        }],
10786                        None,
10787                    );
10788
10789                    let space_char = whitespace_map.space.clone();
10790                    let space_len = space_char.len();
10791                    let space_invisible = window.text_system().shape_line(
10792                        space_char,
10793                        invisible_symbol_font_size,
10794                        &[TextRun {
10795                            len: space_len,
10796                            font: self.style.text.font(),
10797                            color: cx.theme().colors().editor_invisible,
10798                            ..Default::default()
10799                        }],
10800                        None,
10801                    );
10802
10803                    let mode = snapshot.mode.clone();
10804
10805                    let sticky_scroll_header_height = sticky_headers
10806                        .as_ref()
10807                        .and_then(|headers| headers.lines.last())
10808                        .map_or(Pixels::ZERO, |last| last.offset + line_height);
10809
10810                    let has_sticky_buffer_header =
10811                        sticky_buffer_header.is_some() || sticky_header_excerpt_id.is_some();
10812                    let sticky_header_height = if has_sticky_buffer_header {
10813                        let full_height = FILE_HEADER_HEIGHT as f32 * line_height;
10814                        let display_row = blocks
10815                            .iter()
10816                            .filter(|block| block.is_buffer_header)
10817                            .find_map(|block| {
10818                                block.row.filter(|row| row.0 > scroll_position.y as u32)
10819                            });
10820                        let offset = match display_row {
10821                            Some(display_row) => {
10822                                let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
10823                                let offset = (scroll_position.y - max_row as f64).max(0.0);
10824                                let slide_up =
10825                                    Pixels::from(offset * ScrollPixelOffset::from(line_height));
10826
10827                                (full_height - slide_up).max(Pixels::ZERO)
10828                            }
10829                            None => full_height,
10830                        };
10831                        let header_bottom_padding =
10832                            BUFFER_HEADER_PADDING.to_pixels(window.rem_size());
10833                        sticky_scroll_header_height + offset - header_bottom_padding
10834                    } else {
10835                        sticky_scroll_header_height
10836                    };
10837
10838                    let (diff_hunk_controls, diff_hunk_control_bounds) =
10839                        if is_read_only && !self.editor.read(cx).delegate_stage_and_restore {
10840                            (vec![], vec![])
10841                        } else {
10842                            self.layout_diff_hunk_controls(
10843                                start_row..end_row,
10844                                &row_infos,
10845                                &text_hitbox,
10846                                current_selection_head,
10847                                line_height,
10848                                right_margin,
10849                                scroll_pixel_position,
10850                                sticky_header_height,
10851                                &display_hunks,
10852                                &highlighted_rows,
10853                                self.editor.clone(),
10854                                window,
10855                                cx,
10856                            )
10857                        };
10858
10859                    let position_map = Rc::new(PositionMap {
10860                        size: bounds.size,
10861                        visible_row_range,
10862                        scroll_position,
10863                        scroll_pixel_position,
10864                        scroll_max,
10865                        line_layouts,
10866                        line_height,
10867                        em_width,
10868                        em_advance,
10869                        em_layout_width,
10870                        snapshot,
10871                        text_align: self.style.text.text_align,
10872                        content_width: text_hitbox.size.width,
10873                        gutter_hitbox: gutter_hitbox.clone(),
10874                        text_hitbox: text_hitbox.clone(),
10875                        inline_blame_bounds: inline_blame_layout
10876                            .as_ref()
10877                            .map(|layout| (layout.bounds, layout.buffer_id, layout.entry.clone())),
10878                        display_hunks: display_hunks.clone(),
10879                        diff_hunk_control_bounds,
10880                    });
10881
10882                    self.editor.update(cx, |editor, _| {
10883                        editor.last_position_map = Some(position_map.clone())
10884                    });
10885
10886                    EditorLayout {
10887                        mode,
10888                        position_map,
10889                        visible_display_row_range: start_row..end_row,
10890                        wrap_guides,
10891                        indent_guides,
10892                        hitbox,
10893                        gutter_hitbox,
10894                        display_hunks,
10895                        content_origin,
10896                        scrollbars_layout,
10897                        minimap,
10898                        active_rows,
10899                        highlighted_rows,
10900                        highlighted_ranges,
10901                        highlighted_gutter_ranges,
10902                        redacted_ranges,
10903                        document_colors,
10904                        line_elements,
10905                        line_numbers,
10906                        blamed_display_rows,
10907                        inline_diagnostics,
10908                        inline_blame_layout,
10909                        inline_code_actions,
10910                        blocks,
10911                        cursors,
10912                        visible_cursors,
10913                        selections,
10914                        edit_prediction_popover,
10915                        diff_hunk_controls,
10916                        mouse_context_menu,
10917                        test_indicators,
10918                        breakpoints,
10919                        diff_review_button,
10920                        crease_toggles,
10921                        crease_trailers,
10922                        tab_invisible,
10923                        space_invisible,
10924                        sticky_buffer_header,
10925                        sticky_headers,
10926                        expand_toggles,
10927                        text_align: self.style.text.text_align,
10928                        content_width: text_hitbox.size.width,
10929                    }
10930                })
10931            })
10932        })
10933    }
10934
10935    fn paint(
10936        &mut self,
10937        _: Option<&GlobalElementId>,
10938        _inspector_id: Option<&gpui::InspectorElementId>,
10939        bounds: Bounds<gpui::Pixels>,
10940        _: &mut Self::RequestLayoutState,
10941        layout: &mut Self::PrepaintState,
10942        window: &mut Window,
10943        cx: &mut App,
10944    ) {
10945        if !layout.mode.is_minimap() {
10946            let focus_handle = self.editor.focus_handle(cx);
10947            let key_context = self
10948                .editor
10949                .update(cx, |editor, cx| editor.key_context(window, cx));
10950
10951            window.set_key_context(key_context);
10952            window.handle_input(
10953                &focus_handle,
10954                ElementInputHandler::new(bounds, self.editor.clone()),
10955                cx,
10956            );
10957            self.register_actions(window, cx);
10958            self.register_key_listeners(window, cx, layout);
10959        }
10960
10961        let text_style = TextStyleRefinement {
10962            font_size: Some(self.style.text.font_size),
10963            line_height: Some(self.style.text.line_height),
10964            ..Default::default()
10965        };
10966        let rem_size = self.rem_size(cx);
10967        window.with_rem_size(rem_size, |window| {
10968            window.with_text_style(Some(text_style), |window| {
10969                window.with_content_mask(Some(ContentMask { bounds }), |window| {
10970                    self.paint_mouse_listeners(layout, window, cx);
10971                    self.paint_background(layout, window, cx);
10972                    self.paint_indent_guides(layout, window, cx);
10973
10974                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
10975                        self.paint_blamed_display_rows(layout, window, cx);
10976                        self.paint_line_numbers(layout, window, cx);
10977                    }
10978
10979                    self.paint_text(layout, window, cx);
10980
10981                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
10982                        self.paint_gutter_highlights(layout, window, cx);
10983                        self.paint_gutter_indicators(layout, window, cx);
10984                    }
10985
10986                    if !layout.blocks.is_empty() {
10987                        window.with_element_namespace("blocks", |window| {
10988                            self.paint_blocks(layout, window, cx);
10989                        });
10990                    }
10991
10992                    window.with_element_namespace("blocks", |window| {
10993                        if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
10994                            sticky_header.paint(window, cx)
10995                        }
10996                    });
10997
10998                    self.paint_sticky_headers(layout, window, cx);
10999                    self.paint_minimap(layout, window, cx);
11000                    self.paint_scrollbars(layout, window, cx);
11001                    self.paint_edit_prediction_popover(layout, window, cx);
11002                    self.paint_mouse_context_menu(layout, window, cx);
11003                });
11004            })
11005        })
11006    }
11007}
11008
11009pub(super) fn gutter_bounds(
11010    editor_bounds: Bounds<Pixels>,
11011    gutter_dimensions: GutterDimensions,
11012) -> Bounds<Pixels> {
11013    Bounds {
11014        origin: editor_bounds.origin,
11015        size: size(gutter_dimensions.width, editor_bounds.size.height),
11016    }
11017}
11018
11019#[derive(Clone, Copy)]
11020struct ContextMenuLayout {
11021    y_flipped: bool,
11022    bounds: Bounds<Pixels>,
11023}
11024
11025/// Holds information required for layouting the editor scrollbars.
11026struct ScrollbarLayoutInformation {
11027    /// The bounds of the editor area (excluding the content offset).
11028    editor_bounds: Bounds<Pixels>,
11029    /// The available range to scroll within the document.
11030    scroll_range: Size<Pixels>,
11031    /// The space available for one glyph in the editor.
11032    glyph_grid_cell: Size<Pixels>,
11033}
11034
11035impl ScrollbarLayoutInformation {
11036    pub fn new(
11037        editor_bounds: Bounds<Pixels>,
11038        glyph_grid_cell: Size<Pixels>,
11039        document_size: Size<Pixels>,
11040        longest_line_blame_width: Pixels,
11041        settings: &EditorSettings,
11042    ) -> Self {
11043        let vertical_overscroll = match settings.scroll_beyond_last_line {
11044            ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
11045            ScrollBeyondLastLine::Off => glyph_grid_cell.height,
11046            ScrollBeyondLastLine::VerticalScrollMargin => {
11047                (1.0 + settings.vertical_scroll_margin) as f32 * glyph_grid_cell.height
11048            }
11049        };
11050
11051        let overscroll = size(longest_line_blame_width, vertical_overscroll);
11052
11053        ScrollbarLayoutInformation {
11054            editor_bounds,
11055            scroll_range: document_size + overscroll,
11056            glyph_grid_cell,
11057        }
11058    }
11059}
11060
11061impl IntoElement for EditorElement {
11062    type Element = Self;
11063
11064    fn into_element(self) -> Self::Element {
11065        self
11066    }
11067}
11068
11069pub struct EditorLayout {
11070    position_map: Rc<PositionMap>,
11071    hitbox: Hitbox,
11072    gutter_hitbox: Hitbox,
11073    content_origin: gpui::Point<Pixels>,
11074    scrollbars_layout: Option<EditorScrollbars>,
11075    minimap: Option<MinimapLayout>,
11076    mode: EditorMode,
11077    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
11078    indent_guides: Option<Vec<IndentGuideLayout>>,
11079    visible_display_row_range: Range<DisplayRow>,
11080    active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
11081    highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
11082    line_elements: SmallVec<[AnyElement; 1]>,
11083    line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
11084    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
11085    blamed_display_rows: Option<Vec<AnyElement>>,
11086    inline_diagnostics: HashMap<DisplayRow, AnyElement>,
11087    inline_blame_layout: Option<InlineBlameLayout>,
11088    inline_code_actions: Option<AnyElement>,
11089    blocks: Vec<BlockLayout>,
11090    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
11091    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
11092    redacted_ranges: Vec<Range<DisplayPoint>>,
11093    cursors: Vec<(DisplayPoint, Hsla)>,
11094    visible_cursors: Vec<CursorLayout>,
11095    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
11096    test_indicators: Vec<AnyElement>,
11097    breakpoints: Vec<AnyElement>,
11098    diff_review_button: Option<AnyElement>,
11099    crease_toggles: Vec<Option<AnyElement>>,
11100    expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
11101    diff_hunk_controls: Vec<AnyElement>,
11102    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
11103    edit_prediction_popover: Option<AnyElement>,
11104    mouse_context_menu: Option<AnyElement>,
11105    tab_invisible: ShapedLine,
11106    space_invisible: ShapedLine,
11107    sticky_buffer_header: Option<AnyElement>,
11108    sticky_headers: Option<StickyHeaders>,
11109    document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
11110    text_align: TextAlign,
11111    content_width: Pixels,
11112}
11113
11114struct StickyHeaders {
11115    lines: Vec<StickyHeaderLine>,
11116    gutter_background: Hsla,
11117    content_background: Hsla,
11118    gutter_right_padding: Pixels,
11119}
11120
11121struct StickyHeaderLine {
11122    row: DisplayRow,
11123    offset: Pixels,
11124    line: LineWithInvisibles,
11125    line_number: Option<ShapedLine>,
11126    elements: SmallVec<[AnyElement; 1]>,
11127    available_text_width: Pixels,
11128    target_anchor: Anchor,
11129    hitbox: Hitbox,
11130}
11131
11132impl EditorLayout {
11133    fn line_end_overshoot(&self) -> Pixels {
11134        0.15 * self.position_map.line_height
11135    }
11136}
11137
11138impl StickyHeaders {
11139    fn paint(
11140        &mut self,
11141        layout: &mut EditorLayout,
11142        whitespace_setting: ShowWhitespaceSetting,
11143        window: &mut Window,
11144        cx: &mut App,
11145    ) {
11146        let line_height = layout.position_map.line_height;
11147
11148        for line in self.lines.iter_mut().rev() {
11149            window.paint_layer(
11150                Bounds::new(
11151                    layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
11152                    size(line.hitbox.size.width, line_height),
11153                ),
11154                |window| {
11155                    let gutter_bounds = Bounds::new(
11156                        layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
11157                        size(layout.gutter_hitbox.size.width, line_height),
11158                    );
11159                    window.paint_quad(fill(gutter_bounds, self.gutter_background));
11160
11161                    let text_bounds = Bounds::new(
11162                        layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset),
11163                        size(line.available_text_width, line_height),
11164                    );
11165                    window.paint_quad(fill(text_bounds, self.content_background));
11166
11167                    if line.hitbox.is_hovered(window) {
11168                        let hover_overlay = cx.theme().colors().panel_overlay_hover;
11169                        window.paint_quad(fill(gutter_bounds, hover_overlay));
11170                        window.paint_quad(fill(text_bounds, hover_overlay));
11171                    }
11172
11173                    line.paint(
11174                        layout,
11175                        self.gutter_right_padding,
11176                        line.available_text_width,
11177                        layout.content_origin,
11178                        line_height,
11179                        whitespace_setting,
11180                        window,
11181                        cx,
11182                    );
11183                },
11184            );
11185
11186            window.set_cursor_style(CursorStyle::PointingHand, &line.hitbox);
11187        }
11188    }
11189}
11190
11191impl StickyHeaderLine {
11192    fn new(
11193        row: DisplayRow,
11194        offset: Pixels,
11195        mut line: LineWithInvisibles,
11196        line_number: Option<ShapedLine>,
11197        target_anchor: Anchor,
11198        line_height: Pixels,
11199        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11200        content_origin: gpui::Point<Pixels>,
11201        gutter_hitbox: &Hitbox,
11202        text_hitbox: &Hitbox,
11203        window: &mut Window,
11204        cx: &mut App,
11205    ) -> Self {
11206        let mut elements = SmallVec::<[AnyElement; 1]>::new();
11207        line.prepaint_with_custom_offset(
11208            line_height,
11209            scroll_pixel_position,
11210            content_origin,
11211            offset,
11212            &mut elements,
11213            window,
11214            cx,
11215        );
11216
11217        let hitbox_bounds = Bounds::new(
11218            gutter_hitbox.origin + point(Pixels::ZERO, offset),
11219            size(text_hitbox.right() - gutter_hitbox.left(), line_height),
11220        );
11221        let available_text_width =
11222            (hitbox_bounds.size.width - gutter_hitbox.size.width).max(Pixels::ZERO);
11223
11224        Self {
11225            row,
11226            offset,
11227            line,
11228            line_number,
11229            elements,
11230            available_text_width,
11231            target_anchor,
11232            hitbox: window.insert_hitbox(hitbox_bounds, HitboxBehavior::BlockMouseExceptScroll),
11233        }
11234    }
11235
11236    fn paint(
11237        &mut self,
11238        layout: &EditorLayout,
11239        gutter_right_padding: Pixels,
11240        available_text_width: Pixels,
11241        content_origin: gpui::Point<Pixels>,
11242        line_height: Pixels,
11243        whitespace_setting: ShowWhitespaceSetting,
11244        window: &mut Window,
11245        cx: &mut App,
11246    ) {
11247        window.with_content_mask(
11248            Some(ContentMask {
11249                bounds: Bounds::new(
11250                    layout.position_map.text_hitbox.bounds.origin
11251                        + point(Pixels::ZERO, self.offset),
11252                    size(available_text_width, line_height),
11253                ),
11254            }),
11255            |window| {
11256                self.line.draw_with_custom_offset(
11257                    layout,
11258                    self.row,
11259                    content_origin,
11260                    self.offset,
11261                    whitespace_setting,
11262                    &[],
11263                    window,
11264                    cx,
11265                );
11266                for element in &mut self.elements {
11267                    element.paint(window, cx);
11268                }
11269            },
11270        );
11271
11272        if let Some(line_number) = &self.line_number {
11273            let gutter_origin = layout.gutter_hitbox.origin + point(Pixels::ZERO, self.offset);
11274            let gutter_width = layout.gutter_hitbox.size.width;
11275            let origin = point(
11276                gutter_origin.x + gutter_width - gutter_right_padding - line_number.width,
11277                gutter_origin.y,
11278            );
11279            line_number
11280                .paint(origin, line_height, TextAlign::Left, None, window, cx)
11281                .log_err();
11282        }
11283    }
11284}
11285
11286#[derive(Debug)]
11287struct LineNumberSegment {
11288    shaped_line: ShapedLine,
11289    hitbox: Option<Hitbox>,
11290}
11291
11292#[derive(Debug)]
11293struct LineNumberLayout {
11294    segments: SmallVec<[LineNumberSegment; 1]>,
11295}
11296
11297struct ColoredRange<T> {
11298    start: T,
11299    end: T,
11300    color: Hsla,
11301}
11302
11303impl Along for ScrollbarAxes {
11304    type Unit = bool;
11305
11306    fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
11307        match axis {
11308            ScrollbarAxis::Horizontal => self.horizontal,
11309            ScrollbarAxis::Vertical => self.vertical,
11310        }
11311    }
11312
11313    fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
11314        match axis {
11315            ScrollbarAxis::Horizontal => ScrollbarAxes {
11316                horizontal: f(self.horizontal),
11317                vertical: self.vertical,
11318            },
11319            ScrollbarAxis::Vertical => ScrollbarAxes {
11320                horizontal: self.horizontal,
11321                vertical: f(self.vertical),
11322            },
11323        }
11324    }
11325}
11326
11327#[derive(Clone)]
11328struct EditorScrollbars {
11329    pub vertical: Option<ScrollbarLayout>,
11330    pub horizontal: Option<ScrollbarLayout>,
11331    pub visible: bool,
11332}
11333
11334impl EditorScrollbars {
11335    pub fn from_scrollbar_axes(
11336        show_scrollbar: ScrollbarAxes,
11337        layout_information: &ScrollbarLayoutInformation,
11338        content_offset: gpui::Point<Pixels>,
11339        scroll_position: gpui::Point<f64>,
11340        scrollbar_width: Pixels,
11341        right_margin: Pixels,
11342        editor_width: Pixels,
11343        show_scrollbars: bool,
11344        scrollbar_state: Option<&ActiveScrollbarState>,
11345        window: &mut Window,
11346    ) -> Self {
11347        let ScrollbarLayoutInformation {
11348            editor_bounds,
11349            scroll_range,
11350            glyph_grid_cell,
11351        } = layout_information;
11352
11353        let viewport_size = size(editor_width, editor_bounds.size.height);
11354
11355        let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
11356            ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
11357                Corner::BottomLeft,
11358                editor_bounds.bottom_left(),
11359                size(
11360                    // The horizontal viewport size differs from the space available for the
11361                    // horizontal scrollbar, so we have to manually stitch it together here.
11362                    editor_bounds.size.width - right_margin,
11363                    scrollbar_width,
11364                ),
11365            ),
11366            ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
11367                Corner::TopRight,
11368                editor_bounds.top_right(),
11369                size(scrollbar_width, viewport_size.height),
11370            ),
11371        };
11372
11373        let mut create_scrollbar_layout = |axis| {
11374            let viewport_size = viewport_size.along(axis);
11375            let scroll_range = scroll_range.along(axis);
11376
11377            // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
11378            (show_scrollbar.along(axis)
11379                && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
11380                .then(|| {
11381                    ScrollbarLayout::new(
11382                        window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
11383                        viewport_size,
11384                        scroll_range,
11385                        glyph_grid_cell.along(axis),
11386                        content_offset.along(axis),
11387                        scroll_position.along(axis),
11388                        show_scrollbars,
11389                        axis,
11390                    )
11391                    .with_thumb_state(
11392                        scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
11393                    )
11394                })
11395        };
11396
11397        Self {
11398            vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
11399            horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
11400            visible: show_scrollbars,
11401        }
11402    }
11403
11404    pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
11405        [
11406            (&self.vertical, ScrollbarAxis::Vertical),
11407            (&self.horizontal, ScrollbarAxis::Horizontal),
11408        ]
11409        .into_iter()
11410        .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
11411    }
11412
11413    /// Returns the currently hovered scrollbar axis, if any.
11414    pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
11415        self.iter_scrollbars()
11416            .find(|s| s.0.hitbox.is_hovered(window))
11417    }
11418}
11419
11420#[derive(Clone)]
11421struct ScrollbarLayout {
11422    hitbox: Hitbox,
11423    visible_range: Range<ScrollOffset>,
11424    text_unit_size: Pixels,
11425    thumb_bounds: Option<Bounds<Pixels>>,
11426    thumb_state: ScrollbarThumbState,
11427}
11428
11429impl ScrollbarLayout {
11430    const BORDER_WIDTH: Pixels = px(1.0);
11431    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
11432    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
11433    const MIN_THUMB_SIZE: Pixels = px(25.0);
11434
11435    fn new(
11436        scrollbar_track_hitbox: Hitbox,
11437        viewport_size: Pixels,
11438        scroll_range: Pixels,
11439        glyph_space: Pixels,
11440        content_offset: Pixels,
11441        scroll_position: ScrollOffset,
11442        show_thumb: bool,
11443        axis: ScrollbarAxis,
11444    ) -> Self {
11445        let track_bounds = scrollbar_track_hitbox.bounds;
11446        // The length of the track available to the scrollbar thumb. We deliberately
11447        // exclude the content size here so that the thumb aligns with the content.
11448        let track_length = track_bounds.size.along(axis) - content_offset;
11449
11450        Self::new_with_hitbox_and_track_length(
11451            scrollbar_track_hitbox,
11452            track_length,
11453            viewport_size,
11454            scroll_range.into(),
11455            glyph_space,
11456            content_offset.into(),
11457            scroll_position,
11458            show_thumb,
11459            axis,
11460        )
11461    }
11462
11463    fn for_minimap(
11464        minimap_track_hitbox: Hitbox,
11465        visible_lines: f64,
11466        total_editor_lines: f64,
11467        minimap_line_height: Pixels,
11468        scroll_position: ScrollOffset,
11469        minimap_scroll_top: ScrollOffset,
11470        show_thumb: bool,
11471    ) -> Self {
11472        // The scrollbar thumb size is calculated as
11473        // (visible_content/total_content) Γ— scrollbar_track_length.
11474        //
11475        // For the minimap's thumb layout, we leverage this by setting the
11476        // scrollbar track length to the entire document size (using minimap line
11477        // height). This creates a thumb that exactly represents the editor
11478        // viewport scaled to minimap proportions.
11479        //
11480        // We adjust the thumb position relative to `minimap_scroll_top` to
11481        // accommodate for the deliberately oversized track.
11482        //
11483        // This approach ensures that the minimap thumb accurately reflects the
11484        // editor's current scroll position whilst nicely synchronizing the minimap
11485        // thumb and scrollbar thumb.
11486        let scroll_range = total_editor_lines * f64::from(minimap_line_height);
11487        let viewport_size = visible_lines * f64::from(minimap_line_height);
11488
11489        let track_top_offset = -minimap_scroll_top * f64::from(minimap_line_height);
11490
11491        Self::new_with_hitbox_and_track_length(
11492            minimap_track_hitbox,
11493            Pixels::from(scroll_range),
11494            Pixels::from(viewport_size),
11495            scroll_range,
11496            minimap_line_height,
11497            track_top_offset,
11498            scroll_position,
11499            show_thumb,
11500            ScrollbarAxis::Vertical,
11501        )
11502    }
11503
11504    fn new_with_hitbox_and_track_length(
11505        scrollbar_track_hitbox: Hitbox,
11506        track_length: Pixels,
11507        viewport_size: Pixels,
11508        scroll_range: f64,
11509        glyph_space: Pixels,
11510        content_offset: ScrollOffset,
11511        scroll_position: ScrollOffset,
11512        show_thumb: bool,
11513        axis: ScrollbarAxis,
11514    ) -> Self {
11515        let text_units_per_page = viewport_size.to_f64() / glyph_space.to_f64();
11516        let visible_range = scroll_position..scroll_position + text_units_per_page;
11517        let total_text_units = scroll_range / glyph_space.to_f64();
11518
11519        let thumb_percentage = text_units_per_page / total_text_units;
11520        let thumb_size = Pixels::from(ScrollOffset::from(track_length) * thumb_percentage)
11521            .max(ScrollbarLayout::MIN_THUMB_SIZE)
11522            .min(track_length);
11523
11524        let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
11525
11526        let content_larger_than_viewport = text_unit_divisor > 0.;
11527
11528        let text_unit_size = if content_larger_than_viewport {
11529            Pixels::from(ScrollOffset::from(track_length - thumb_size) / text_unit_divisor)
11530        } else {
11531            glyph_space
11532        };
11533
11534        let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
11535            Self::thumb_bounds(
11536                &scrollbar_track_hitbox,
11537                content_offset,
11538                visible_range.start,
11539                text_unit_size,
11540                thumb_size,
11541                axis,
11542            )
11543        });
11544
11545        ScrollbarLayout {
11546            hitbox: scrollbar_track_hitbox,
11547            visible_range,
11548            text_unit_size,
11549            thumb_bounds,
11550            thumb_state: Default::default(),
11551        }
11552    }
11553
11554    fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
11555        if let Some(thumb_state) = thumb_state {
11556            Self {
11557                thumb_state,
11558                ..self
11559            }
11560        } else {
11561            self
11562        }
11563    }
11564
11565    fn thumb_bounds(
11566        scrollbar_track: &Hitbox,
11567        content_offset: f64,
11568        visible_range_start: f64,
11569        text_unit_size: Pixels,
11570        thumb_size: Pixels,
11571        axis: ScrollbarAxis,
11572    ) -> Bounds<Pixels> {
11573        let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
11574            origin
11575                + Pixels::from(
11576                    content_offset + visible_range_start * ScrollOffset::from(text_unit_size),
11577                )
11578        });
11579        Bounds::new(
11580            thumb_origin,
11581            scrollbar_track.size.apply_along(axis, |_| thumb_size),
11582        )
11583    }
11584
11585    fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
11586        self.thumb_bounds
11587            .is_some_and(|bounds| bounds.contains(position))
11588    }
11589
11590    fn marker_quads_for_ranges(
11591        &self,
11592        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
11593        column: Option<usize>,
11594    ) -> Vec<PaintQuad> {
11595        struct MinMax {
11596            min: Pixels,
11597            max: Pixels,
11598        }
11599        let (x_range, height_limit) = if let Some(column) = column {
11600            let column_width = ((self.hitbox.size.width - Self::BORDER_WIDTH) / 3.0).floor();
11601            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
11602            let end = start + column_width;
11603            (
11604                Range { start, end },
11605                MinMax {
11606                    min: Self::MIN_MARKER_HEIGHT,
11607                    max: px(f32::MAX),
11608                },
11609            )
11610        } else {
11611            (
11612                Range {
11613                    start: Self::BORDER_WIDTH,
11614                    end: self.hitbox.size.width,
11615                },
11616                MinMax {
11617                    min: Self::LINE_MARKER_HEIGHT,
11618                    max: Self::LINE_MARKER_HEIGHT,
11619                },
11620            )
11621        };
11622
11623        let row_to_y = |row: DisplayRow| row.as_f64() as f32 * self.text_unit_size;
11624        let mut pixel_ranges = row_ranges
11625            .into_iter()
11626            .map(|range| {
11627                let start_y = row_to_y(range.start);
11628                let end_y = row_to_y(range.end)
11629                    + self
11630                        .text_unit_size
11631                        .max(height_limit.min)
11632                        .min(height_limit.max);
11633                ColoredRange {
11634                    start: start_y,
11635                    end: end_y,
11636                    color: range.color,
11637                }
11638            })
11639            .peekable();
11640
11641        let mut quads = Vec::new();
11642        while let Some(mut pixel_range) = pixel_ranges.next() {
11643            while let Some(next_pixel_range) = pixel_ranges.peek() {
11644                if pixel_range.end >= next_pixel_range.start - px(1.0)
11645                    && pixel_range.color == next_pixel_range.color
11646                {
11647                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
11648                    pixel_ranges.next();
11649                } else {
11650                    break;
11651                }
11652            }
11653
11654            let bounds = Bounds::from_corners(
11655                point(x_range.start, pixel_range.start),
11656                point(x_range.end, pixel_range.end),
11657            );
11658            quads.push(quad(
11659                bounds,
11660                Corners::default(),
11661                pixel_range.color,
11662                Edges::default(),
11663                Hsla::transparent_black(),
11664                BorderStyle::default(),
11665            ));
11666        }
11667
11668        quads
11669    }
11670}
11671
11672struct MinimapLayout {
11673    pub minimap: AnyElement,
11674    pub thumb_layout: ScrollbarLayout,
11675    pub minimap_scroll_top: ScrollOffset,
11676    pub minimap_line_height: Pixels,
11677    pub thumb_border_style: MinimapThumbBorder,
11678    pub max_scroll_top: ScrollOffset,
11679}
11680
11681impl MinimapLayout {
11682    /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
11683    const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
11684    /// The minimap width as a percentage of the editor width.
11685    const MINIMAP_WIDTH_PCT: f32 = 0.15;
11686    /// Calculates the scroll top offset the minimap editor has to have based on the
11687    /// current scroll progress.
11688    fn calculate_minimap_top_offset(
11689        document_lines: f64,
11690        visible_editor_lines: f64,
11691        visible_minimap_lines: f64,
11692        scroll_position: f64,
11693    ) -> ScrollOffset {
11694        let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
11695        if non_visible_document_lines == 0. {
11696            0.
11697        } else {
11698            let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
11699            scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
11700        }
11701    }
11702}
11703
11704struct CreaseTrailerLayout {
11705    element: AnyElement,
11706    bounds: Bounds<Pixels>,
11707}
11708
11709pub(crate) struct PositionMap {
11710    pub size: Size<Pixels>,
11711    pub line_height: Pixels,
11712    pub scroll_position: gpui::Point<ScrollOffset>,
11713    pub scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11714    pub scroll_max: gpui::Point<ScrollOffset>,
11715    pub em_width: Pixels,
11716    pub em_advance: Pixels,
11717    pub em_layout_width: Pixels,
11718    pub visible_row_range: Range<DisplayRow>,
11719    pub line_layouts: Vec<LineWithInvisibles>,
11720    pub snapshot: EditorSnapshot,
11721    pub text_align: TextAlign,
11722    pub content_width: Pixels,
11723    pub text_hitbox: Hitbox,
11724    pub gutter_hitbox: Hitbox,
11725    pub inline_blame_bounds: Option<(Bounds<Pixels>, BufferId, BlameEntry)>,
11726    pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
11727    pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
11728}
11729
11730#[derive(Debug, Copy, Clone)]
11731pub struct PointForPosition {
11732    pub previous_valid: DisplayPoint,
11733    pub next_valid: DisplayPoint,
11734    pub exact_unclipped: DisplayPoint,
11735    pub column_overshoot_after_line_end: u32,
11736}
11737
11738impl PointForPosition {
11739    pub fn as_valid(&self) -> Option<DisplayPoint> {
11740        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
11741            Some(self.previous_valid)
11742        } else {
11743            None
11744        }
11745    }
11746
11747    pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
11748        let Some(valid_point) = self.as_valid() else {
11749            return false;
11750        };
11751        let range = selection.range();
11752
11753        let candidate_row = valid_point.row();
11754        let candidate_col = valid_point.column();
11755
11756        let start_row = range.start.row();
11757        let start_col = range.start.column();
11758        let end_row = range.end.row();
11759        let end_col = range.end.column();
11760
11761        if candidate_row < start_row || candidate_row > end_row {
11762            false
11763        } else if start_row == end_row {
11764            candidate_col >= start_col && candidate_col < end_col
11765        } else if candidate_row == start_row {
11766            candidate_col >= start_col
11767        } else if candidate_row == end_row {
11768            candidate_col < end_col
11769        } else {
11770            true
11771        }
11772    }
11773}
11774
11775impl PositionMap {
11776    pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
11777        let text_bounds = self.text_hitbox.bounds;
11778        let scroll_position = self.snapshot.scroll_position();
11779        let position = position - text_bounds.origin;
11780        let y = position.y.max(px(0.)).min(self.size.height);
11781        let x = position.x + (scroll_position.x as f32 * self.em_layout_width);
11782        let row = ((y / self.line_height) as f64 + scroll_position.y) as u32;
11783
11784        let (column, x_overshoot_after_line_end) = if let Some(line) = self
11785            .line_layouts
11786            .get(row as usize - scroll_position.y as usize)
11787        {
11788            let alignment_offset = line.alignment_offset(self.text_align, self.content_width);
11789            let x_relative_to_text = x - alignment_offset;
11790            if let Some(ix) = line.index_for_x(x_relative_to_text) {
11791                (ix as u32, px(0.))
11792            } else {
11793                (line.len as u32, px(0.).max(x_relative_to_text - line.width))
11794            }
11795        } else {
11796            (0, x)
11797        };
11798
11799        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
11800        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
11801        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
11802
11803        let column_overshoot_after_line_end =
11804            (x_overshoot_after_line_end / self.em_layout_width) as u32;
11805        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
11806        PointForPosition {
11807            previous_valid,
11808            next_valid,
11809            exact_unclipped,
11810            column_overshoot_after_line_end,
11811        }
11812    }
11813}
11814
11815pub(crate) struct BlockLayout {
11816    pub(crate) id: BlockId,
11817    pub(crate) x_offset: Pixels,
11818    pub(crate) row: Option<DisplayRow>,
11819    pub(crate) element: AnyElement,
11820    pub(crate) available_space: Size<AvailableSpace>,
11821    pub(crate) style: BlockStyle,
11822    pub(crate) overlaps_gutter: bool,
11823    pub(crate) is_buffer_header: bool,
11824}
11825
11826pub fn layout_line(
11827    row: DisplayRow,
11828    snapshot: &EditorSnapshot,
11829    style: &EditorStyle,
11830    text_width: Pixels,
11831    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
11832    window: &mut Window,
11833    cx: &mut App,
11834) -> LineWithInvisibles {
11835    let use_tree_sitter =
11836        !snapshot.semantic_tokens_enabled || snapshot.use_tree_sitter_for_syntax(row, cx);
11837    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), use_tree_sitter, style);
11838    LineWithInvisibles::from_chunks(
11839        chunks,
11840        style,
11841        MAX_LINE_LEN,
11842        1,
11843        &snapshot.mode,
11844        text_width,
11845        is_row_soft_wrapped,
11846        &[],
11847        window,
11848        cx,
11849    )
11850    .pop()
11851    .unwrap()
11852}
11853
11854#[derive(Debug)]
11855pub struct IndentGuideLayout {
11856    origin: gpui::Point<Pixels>,
11857    length: Pixels,
11858    single_indent_width: Pixels,
11859    depth: u32,
11860    active: bool,
11861    settings: IndentGuideSettings,
11862}
11863
11864pub struct CursorLayout {
11865    origin: gpui::Point<Pixels>,
11866    block_width: Pixels,
11867    line_height: Pixels,
11868    color: Hsla,
11869    shape: CursorShape,
11870    block_text: Option<ShapedLine>,
11871    cursor_name: Option<AnyElement>,
11872}
11873
11874#[derive(Debug)]
11875pub struct CursorName {
11876    string: SharedString,
11877    color: Hsla,
11878    is_top_row: bool,
11879}
11880
11881impl CursorLayout {
11882    pub fn new(
11883        origin: gpui::Point<Pixels>,
11884        block_width: Pixels,
11885        line_height: Pixels,
11886        color: Hsla,
11887        shape: CursorShape,
11888        block_text: Option<ShapedLine>,
11889    ) -> CursorLayout {
11890        CursorLayout {
11891            origin,
11892            block_width,
11893            line_height,
11894            color,
11895            shape,
11896            block_text,
11897            cursor_name: None,
11898        }
11899    }
11900
11901    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
11902        Bounds {
11903            origin: self.origin + origin,
11904            size: size(self.block_width, self.line_height),
11905        }
11906    }
11907
11908    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
11909        match self.shape {
11910            CursorShape::Bar => Bounds {
11911                origin: self.origin + origin,
11912                size: size(px(2.0), self.line_height),
11913            },
11914            CursorShape::Block | CursorShape::Hollow => Bounds {
11915                origin: self.origin + origin,
11916                size: size(self.block_width, self.line_height),
11917            },
11918            CursorShape::Underline => Bounds {
11919                origin: self.origin
11920                    + origin
11921                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
11922                size: size(self.block_width, px(2.0)),
11923            },
11924        }
11925    }
11926
11927    pub fn layout(
11928        &mut self,
11929        origin: gpui::Point<Pixels>,
11930        cursor_name: Option<CursorName>,
11931        window: &mut Window,
11932        cx: &mut App,
11933    ) {
11934        if let Some(cursor_name) = cursor_name {
11935            let bounds = self.bounds(origin);
11936            let text_size = self.line_height / 1.5;
11937
11938            let name_origin = if cursor_name.is_top_row {
11939                point(bounds.right() - px(1.), bounds.top())
11940            } else {
11941                match self.shape {
11942                    CursorShape::Bar => point(
11943                        bounds.right() - px(2.),
11944                        bounds.top() - text_size / 2. - px(1.),
11945                    ),
11946                    _ => point(
11947                        bounds.right() - px(1.),
11948                        bounds.top() - text_size / 2. - px(1.),
11949                    ),
11950                }
11951            };
11952            let mut name_element = div()
11953                .bg(self.color)
11954                .text_size(text_size)
11955                .px_0p5()
11956                .line_height(text_size + px(2.))
11957                .text_color(cursor_name.color)
11958                .child(cursor_name.string)
11959                .into_any_element();
11960
11961            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
11962
11963            self.cursor_name = Some(name_element);
11964        }
11965    }
11966
11967    pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
11968        let bounds = self.bounds(origin);
11969
11970        //Draw background or border quad
11971        let cursor = if matches!(self.shape, CursorShape::Hollow) {
11972            outline(bounds, self.color, BorderStyle::Solid)
11973        } else {
11974            fill(bounds, self.color)
11975        };
11976
11977        if let Some(name) = &mut self.cursor_name {
11978            name.paint(window, cx);
11979        }
11980
11981        window.paint_quad(cursor);
11982
11983        if let Some(block_text) = &self.block_text {
11984            block_text
11985                .paint(
11986                    self.origin + origin,
11987                    self.line_height,
11988                    TextAlign::Left,
11989                    None,
11990                    window,
11991                    cx,
11992                )
11993                .log_err();
11994        }
11995    }
11996
11997    pub fn shape(&self) -> CursorShape {
11998        self.shape
11999    }
12000}
12001
12002#[derive(Debug)]
12003pub struct HighlightedRange {
12004    pub start_y: Pixels,
12005    pub line_height: Pixels,
12006    pub lines: Vec<HighlightedRangeLine>,
12007    pub color: Hsla,
12008    pub corner_radius: Pixels,
12009}
12010
12011#[derive(Debug)]
12012pub struct HighlightedRangeLine {
12013    pub start_x: Pixels,
12014    pub end_x: Pixels,
12015}
12016
12017impl HighlightedRange {
12018    pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
12019        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
12020            self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
12021            self.paint_lines(
12022                self.start_y + self.line_height,
12023                &self.lines[1..],
12024                fill,
12025                bounds,
12026                window,
12027            );
12028        } else {
12029            self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
12030        }
12031    }
12032
12033    fn paint_lines(
12034        &self,
12035        start_y: Pixels,
12036        lines: &[HighlightedRangeLine],
12037        fill: bool,
12038        _bounds: Bounds<Pixels>,
12039        window: &mut Window,
12040    ) {
12041        if lines.is_empty() {
12042            return;
12043        }
12044
12045        let first_line = lines.first().unwrap();
12046        let last_line = lines.last().unwrap();
12047
12048        let first_top_left = point(first_line.start_x, start_y);
12049        let first_top_right = point(first_line.end_x, start_y);
12050
12051        let curve_height = point(Pixels::ZERO, self.corner_radius);
12052        let curve_width = |start_x: Pixels, end_x: Pixels| {
12053            let max = (end_x - start_x) / 2.;
12054            let width = if max < self.corner_radius {
12055                max
12056            } else {
12057                self.corner_radius
12058            };
12059
12060            point(width, Pixels::ZERO)
12061        };
12062
12063        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
12064        let mut builder = if fill {
12065            gpui::PathBuilder::fill()
12066        } else {
12067            gpui::PathBuilder::stroke(px(1.))
12068        };
12069        builder.move_to(first_top_right - top_curve_width);
12070        builder.curve_to(first_top_right + curve_height, first_top_right);
12071
12072        let mut iter = lines.iter().enumerate().peekable();
12073        while let Some((ix, line)) = iter.next() {
12074            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
12075
12076            if let Some((_, next_line)) = iter.peek() {
12077                let next_top_right = point(next_line.end_x, bottom_right.y);
12078
12079                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
12080                    Ordering::Equal => {
12081                        builder.line_to(bottom_right);
12082                    }
12083                    Ordering::Less => {
12084                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
12085                        builder.line_to(bottom_right - curve_height);
12086                        if self.corner_radius > Pixels::ZERO {
12087                            builder.curve_to(bottom_right - curve_width, bottom_right);
12088                        }
12089                        builder.line_to(next_top_right + curve_width);
12090                        if self.corner_radius > Pixels::ZERO {
12091                            builder.curve_to(next_top_right + curve_height, next_top_right);
12092                        }
12093                    }
12094                    Ordering::Greater => {
12095                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
12096                        builder.line_to(bottom_right - curve_height);
12097                        if self.corner_radius > Pixels::ZERO {
12098                            builder.curve_to(bottom_right + curve_width, bottom_right);
12099                        }
12100                        builder.line_to(next_top_right - curve_width);
12101                        if self.corner_radius > Pixels::ZERO {
12102                            builder.curve_to(next_top_right + curve_height, next_top_right);
12103                        }
12104                    }
12105                }
12106            } else {
12107                let curve_width = curve_width(line.start_x, line.end_x);
12108                builder.line_to(bottom_right - curve_height);
12109                if self.corner_radius > Pixels::ZERO {
12110                    builder.curve_to(bottom_right - curve_width, bottom_right);
12111                }
12112
12113                let bottom_left = point(line.start_x, bottom_right.y);
12114                builder.line_to(bottom_left + curve_width);
12115                if self.corner_radius > Pixels::ZERO {
12116                    builder.curve_to(bottom_left - curve_height, bottom_left);
12117                }
12118            }
12119        }
12120
12121        if first_line.start_x > last_line.start_x {
12122            let curve_width = curve_width(last_line.start_x, first_line.start_x);
12123            let second_top_left = point(last_line.start_x, start_y + self.line_height);
12124            builder.line_to(second_top_left + curve_height);
12125            if self.corner_radius > Pixels::ZERO {
12126                builder.curve_to(second_top_left + curve_width, second_top_left);
12127            }
12128            let first_bottom_left = point(first_line.start_x, second_top_left.y);
12129            builder.line_to(first_bottom_left - curve_width);
12130            if self.corner_radius > Pixels::ZERO {
12131                builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
12132            }
12133        }
12134
12135        builder.line_to(first_top_left + curve_height);
12136        if self.corner_radius > Pixels::ZERO {
12137            builder.curve_to(first_top_left + top_curve_width, first_top_left);
12138        }
12139        builder.line_to(first_top_right - top_curve_width);
12140
12141        if let Ok(path) = builder.build() {
12142            window.paint_path(path, self.color);
12143        }
12144    }
12145}
12146
12147pub(crate) struct StickyHeader {
12148    pub item: language::OutlineItem<Anchor>,
12149    pub sticky_row: DisplayRow,
12150    pub start_point: Point,
12151    pub offset: ScrollOffset,
12152}
12153
12154enum CursorPopoverType {
12155    CodeContextMenu,
12156    EditPrediction,
12157}
12158
12159pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12160    (delta.pow(1.2) / 100.0).min(px(3.0)).into()
12161}
12162
12163fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12164    (delta.pow(1.2) / 300.0).into()
12165}
12166
12167pub fn register_action<T: Action>(
12168    editor: &Entity<Editor>,
12169    window: &mut Window,
12170    listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
12171) {
12172    let editor = editor.clone();
12173    window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
12174        let action = action.downcast_ref().unwrap();
12175        if phase == DispatchPhase::Bubble {
12176            editor.update(cx, |editor, cx| {
12177                listener(editor, action, window, cx);
12178            })
12179        }
12180    })
12181}
12182
12183/// Shared between `prepaint` and `compute_auto_height_layout` to ensure
12184/// both full and auto-height editors compute wrap widths consistently.
12185fn calculate_wrap_width(
12186    soft_wrap: SoftWrap,
12187    editor_width: Pixels,
12188    em_width: Pixels,
12189) -> Option<Pixels> {
12190    let wrap_width_for = |column: u32| (column as f32 * em_width).ceil();
12191
12192    match soft_wrap {
12193        SoftWrap::GitDiff => None,
12194        SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
12195        SoftWrap::EditorWidth => Some(editor_width),
12196        SoftWrap::Column(column) => Some(wrap_width_for(column)),
12197        SoftWrap::Bounded(column) => Some(editor_width.min(wrap_width_for(column))),
12198    }
12199}
12200
12201fn compute_auto_height_layout(
12202    editor: &mut Editor,
12203    min_lines: usize,
12204    max_lines: Option<usize>,
12205    known_dimensions: Size<Option<Pixels>>,
12206    available_width: AvailableSpace,
12207    window: &mut Window,
12208    cx: &mut Context<Editor>,
12209) -> Option<Size<Pixels>> {
12210    let width = known_dimensions.width.or({
12211        if let AvailableSpace::Definite(available_width) = available_width {
12212            Some(available_width)
12213        } else {
12214            None
12215        }
12216    })?;
12217    if let Some(height) = known_dimensions.height {
12218        return Some(size(width, height));
12219    }
12220
12221    let style = editor.style.as_ref().unwrap();
12222    let font_id = window.text_system().resolve_font(&style.text.font());
12223    let font_size = style.text.font_size.to_pixels(window.rem_size());
12224    let line_height = style.text.line_height_in_pixels(window.rem_size());
12225    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
12226
12227    let mut snapshot = editor.snapshot(window, cx);
12228    let gutter_dimensions = snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
12229
12230    editor.gutter_dimensions = gutter_dimensions;
12231    let text_width = width - gutter_dimensions.width;
12232    let overscroll = size(em_width, px(0.));
12233
12234    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
12235    let wrap_width = calculate_wrap_width(editor.soft_wrap_mode(cx), editor_width, em_width);
12236    if wrap_width.is_some() && editor.set_wrap_width(wrap_width, cx) {
12237        snapshot = editor.snapshot(window, cx);
12238    }
12239
12240    let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
12241
12242    let min_height = line_height * min_lines as f32;
12243    let content_height = scroll_height.max(min_height);
12244
12245    let final_height = if let Some(max_lines) = max_lines {
12246        let max_height = line_height * max_lines as f32;
12247        content_height.min(max_height)
12248    } else {
12249        content_height
12250    };
12251
12252    Some(size(width, final_height))
12253}
12254
12255#[cfg(test)]
12256mod tests {
12257    use super::*;
12258    use crate::{
12259        Editor, MultiBuffer, SelectionEffects,
12260        display_map::{BlockPlacement, BlockProperties},
12261        editor_tests::{init_test, update_test_language_settings},
12262    };
12263    use gpui::{TestAppContext, VisualTestContext};
12264    use language::{Buffer, language_settings, tree_sitter_python};
12265    use log::info;
12266    use rand::{RngCore, rngs::StdRng};
12267    use std::num::NonZeroU32;
12268    use util::test::sample_text;
12269
12270    #[gpui::test]
12271    async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
12272        init_test(cx, |_| {});
12273        let window = cx.add_window(|window, cx| {
12274            let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12275            let mut editor = Editor::new(
12276                EditorMode::AutoHeight {
12277                    min_lines: 1,
12278                    max_lines: None,
12279                },
12280                buffer,
12281                None,
12282                window,
12283                cx,
12284            );
12285            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12286            editor
12287        });
12288        let cx = &mut VisualTestContext::from_window(*window, cx);
12289        let editor = window.root(cx).unwrap();
12290        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12291
12292        for x in 1..=100 {
12293            let (_, state) = cx.draw(
12294                Default::default(),
12295                size(px(200. + 0.13 * x as f32), px(500.)),
12296                |_, _| EditorElement::new(&editor, style.clone()),
12297            );
12298
12299            assert!(
12300                state.position_map.scroll_max.x == 0.,
12301                "Soft wrapped editor should have no horizontal scrolling!"
12302            );
12303        }
12304    }
12305
12306    #[gpui::test]
12307    async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
12308        init_test(cx, |_| {});
12309        let window = cx.add_window(|window, cx| {
12310            let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12311            let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
12312            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12313            editor
12314        });
12315        let cx = &mut VisualTestContext::from_window(*window, cx);
12316        let editor = window.root(cx).unwrap();
12317        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12318
12319        for x in 1..=100 {
12320            let (_, state) = cx.draw(
12321                Default::default(),
12322                size(px(200. + 0.13 * x as f32), px(500.)),
12323                |_, _| EditorElement::new(&editor, style.clone()),
12324            );
12325
12326            assert!(
12327                state.position_map.scroll_max.x == 0.,
12328                "Soft wrapped editor should have no horizontal scrolling!"
12329            );
12330        }
12331    }
12332
12333    #[gpui::test]
12334    fn test_layout_line_numbers(cx: &mut TestAppContext) {
12335        init_test(cx, |_| {});
12336        let window = cx.add_window(|window, cx| {
12337            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12338            Editor::new(EditorMode::full(), buffer, None, window, cx)
12339        });
12340
12341        let editor = window.root(cx).unwrap();
12342        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12343        let line_height = window
12344            .update(cx, |_, window, _| {
12345                style.text.line_height_in_pixels(window.rem_size())
12346            })
12347            .unwrap();
12348        let element = EditorElement::new(&editor, style);
12349        let snapshot = window
12350            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12351            .unwrap();
12352
12353        let layouts = cx
12354            .update_window(*window, |_, window, cx| {
12355                element.layout_line_numbers(
12356                    None,
12357                    GutterDimensions {
12358                        left_padding: Pixels::ZERO,
12359                        right_padding: Pixels::ZERO,
12360                        width: px(30.0),
12361                        margin: Pixels::ZERO,
12362                        git_blame_entries_width: None,
12363                    },
12364                    line_height,
12365                    gpui::Point::default(),
12366                    DisplayRow(0)..DisplayRow(6),
12367                    &(0..6)
12368                        .map(|row| RowInfo {
12369                            buffer_row: Some(row),
12370                            ..Default::default()
12371                        })
12372                        .collect::<Vec<_>>(),
12373                    &BTreeMap::default(),
12374                    Some(DisplayRow(0)),
12375                    &snapshot,
12376                    window,
12377                    cx,
12378                )
12379            })
12380            .unwrap();
12381        assert_eq!(layouts.len(), 6);
12382
12383        let relative_rows = window
12384            .update(cx, |editor, window, cx| {
12385                let snapshot = editor.snapshot(window, cx);
12386                snapshot.calculate_relative_line_numbers(
12387                    &(DisplayRow(0)..DisplayRow(6)),
12388                    DisplayRow(3),
12389                    false,
12390                )
12391            })
12392            .unwrap();
12393        assert_eq!(relative_rows[&DisplayRow(0)], 3);
12394        assert_eq!(relative_rows[&DisplayRow(1)], 2);
12395        assert_eq!(relative_rows[&DisplayRow(2)], 1);
12396        // current line has no relative number
12397        assert!(!relative_rows.contains_key(&DisplayRow(3)));
12398        assert_eq!(relative_rows[&DisplayRow(4)], 1);
12399        assert_eq!(relative_rows[&DisplayRow(5)], 2);
12400
12401        // works if cursor is before screen
12402        let relative_rows = window
12403            .update(cx, |editor, window, cx| {
12404                let snapshot = editor.snapshot(window, cx);
12405                snapshot.calculate_relative_line_numbers(
12406                    &(DisplayRow(3)..DisplayRow(6)),
12407                    DisplayRow(1),
12408                    false,
12409                )
12410            })
12411            .unwrap();
12412        assert_eq!(relative_rows.len(), 3);
12413        assert_eq!(relative_rows[&DisplayRow(3)], 2);
12414        assert_eq!(relative_rows[&DisplayRow(4)], 3);
12415        assert_eq!(relative_rows[&DisplayRow(5)], 4);
12416
12417        // works if cursor is after screen
12418        let relative_rows = window
12419            .update(cx, |editor, window, cx| {
12420                let snapshot = editor.snapshot(window, cx);
12421                snapshot.calculate_relative_line_numbers(
12422                    &(DisplayRow(0)..DisplayRow(3)),
12423                    DisplayRow(6),
12424                    false,
12425                )
12426            })
12427            .unwrap();
12428        assert_eq!(relative_rows.len(), 3);
12429        assert_eq!(relative_rows[&DisplayRow(0)], 5);
12430        assert_eq!(relative_rows[&DisplayRow(1)], 4);
12431        assert_eq!(relative_rows[&DisplayRow(2)], 3);
12432
12433        const DELETED_LINE: u32 = 3;
12434        let layouts = cx
12435            .update_window(*window, |_, window, cx| {
12436                element.layout_line_numbers(
12437                    None,
12438                    GutterDimensions {
12439                        left_padding: Pixels::ZERO,
12440                        right_padding: Pixels::ZERO,
12441                        width: px(30.0),
12442                        margin: Pixels::ZERO,
12443                        git_blame_entries_width: None,
12444                    },
12445                    line_height,
12446                    gpui::Point::default(),
12447                    DisplayRow(0)..DisplayRow(6),
12448                    &(0..6)
12449                        .map(|row| RowInfo {
12450                            buffer_row: Some(row),
12451                            diff_status: (row == DELETED_LINE).then(|| {
12452                                DiffHunkStatus::deleted(
12453                                    buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12454                                )
12455                            }),
12456                            ..Default::default()
12457                        })
12458                        .collect::<Vec<_>>(),
12459                    &BTreeMap::default(),
12460                    Some(DisplayRow(0)),
12461                    &snapshot,
12462                    window,
12463                    cx,
12464                )
12465            })
12466            .unwrap();
12467        assert_eq!(layouts.len(), 5,);
12468        assert!(
12469            layouts.get(&MultiBufferRow(DELETED_LINE)).is_none(),
12470            "Deleted line should not have a line number"
12471        );
12472    }
12473
12474    #[gpui::test]
12475    async fn test_layout_line_numbers_with_folded_lines(cx: &mut TestAppContext) {
12476        init_test(cx, |_| {});
12477
12478        let python_lang = languages::language("python", tree_sitter_python::LANGUAGE.into());
12479
12480        let window = cx.add_window(|window, cx| {
12481            let buffer = cx.new(|cx| {
12482                Buffer::local(
12483                    indoc::indoc! {"
12484                        fn test() -> int {
12485                            return 2;
12486                        }
12487
12488                        fn another_test() -> int {
12489                            # This is a very peculiar method that is hard to grasp.
12490                            return 4;
12491                        }
12492                    "},
12493                    cx,
12494                )
12495                .with_language(python_lang, cx)
12496            });
12497
12498            let buffer = MultiBuffer::build_from_buffer(buffer, cx);
12499            Editor::new(EditorMode::full(), buffer, None, window, cx)
12500        });
12501
12502        let editor = window.root(cx).unwrap();
12503        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12504        let line_height = window
12505            .update(cx, |_, window, _| {
12506                style.text.line_height_in_pixels(window.rem_size())
12507            })
12508            .unwrap();
12509        let element = EditorElement::new(&editor, style);
12510        let snapshot = window
12511            .update(cx, |editor, window, cx| {
12512                editor.fold_at(MultiBufferRow(0), window, cx);
12513                editor.snapshot(window, cx)
12514            })
12515            .unwrap();
12516
12517        let layouts = cx
12518            .update_window(*window, |_, window, cx| {
12519                element.layout_line_numbers(
12520                    None,
12521                    GutterDimensions {
12522                        left_padding: Pixels::ZERO,
12523                        right_padding: Pixels::ZERO,
12524                        width: px(30.0),
12525                        margin: Pixels::ZERO,
12526                        git_blame_entries_width: None,
12527                    },
12528                    line_height,
12529                    gpui::Point::default(),
12530                    DisplayRow(0)..DisplayRow(6),
12531                    &(0..6)
12532                        .map(|row| RowInfo {
12533                            buffer_row: Some(row),
12534                            ..Default::default()
12535                        })
12536                        .collect::<Vec<_>>(),
12537                    &BTreeMap::default(),
12538                    Some(DisplayRow(3)),
12539                    &snapshot,
12540                    window,
12541                    cx,
12542                )
12543            })
12544            .unwrap();
12545        assert_eq!(layouts.len(), 6);
12546
12547        let relative_rows = window
12548            .update(cx, |editor, window, cx| {
12549                let snapshot = editor.snapshot(window, cx);
12550                snapshot.calculate_relative_line_numbers(
12551                    &(DisplayRow(0)..DisplayRow(6)),
12552                    DisplayRow(3),
12553                    false,
12554                )
12555            })
12556            .unwrap();
12557        assert_eq!(relative_rows[&DisplayRow(0)], 3);
12558        assert_eq!(relative_rows[&DisplayRow(1)], 2);
12559        assert_eq!(relative_rows[&DisplayRow(2)], 1);
12560        // current line has no relative number
12561        assert!(!relative_rows.contains_key(&DisplayRow(3)));
12562        assert_eq!(relative_rows[&DisplayRow(4)], 1);
12563        assert_eq!(relative_rows[&DisplayRow(5)], 2);
12564    }
12565
12566    #[gpui::test]
12567    fn test_layout_line_numbers_wrapping(cx: &mut TestAppContext) {
12568        init_test(cx, |_| {});
12569        let window = cx.add_window(|window, cx| {
12570            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12571            Editor::new(EditorMode::full(), buffer, None, window, cx)
12572        });
12573
12574        update_test_language_settings(cx, &|s| {
12575            s.defaults.preferred_line_length = Some(5_u32);
12576            s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
12577        });
12578
12579        let editor = window.root(cx).unwrap();
12580        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12581        let line_height = window
12582            .update(cx, |_, window, _| {
12583                style.text.line_height_in_pixels(window.rem_size())
12584            })
12585            .unwrap();
12586        let element = EditorElement::new(&editor, style);
12587        let snapshot = window
12588            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12589            .unwrap();
12590
12591        let layouts = cx
12592            .update_window(*window, |_, window, cx| {
12593                element.layout_line_numbers(
12594                    None,
12595                    GutterDimensions {
12596                        left_padding: Pixels::ZERO,
12597                        right_padding: Pixels::ZERO,
12598                        width: px(30.0),
12599                        margin: Pixels::ZERO,
12600                        git_blame_entries_width: None,
12601                    },
12602                    line_height,
12603                    gpui::Point::default(),
12604                    DisplayRow(0)..DisplayRow(6),
12605                    &(0..6)
12606                        .map(|row| RowInfo {
12607                            buffer_row: Some(row),
12608                            ..Default::default()
12609                        })
12610                        .collect::<Vec<_>>(),
12611                    &BTreeMap::default(),
12612                    Some(DisplayRow(0)),
12613                    &snapshot,
12614                    window,
12615                    cx,
12616                )
12617            })
12618            .unwrap();
12619        assert_eq!(layouts.len(), 3);
12620
12621        let relative_rows = window
12622            .update(cx, |editor, window, cx| {
12623                let snapshot = editor.snapshot(window, cx);
12624                snapshot.calculate_relative_line_numbers(
12625                    &(DisplayRow(0)..DisplayRow(6)),
12626                    DisplayRow(3),
12627                    true,
12628                )
12629            })
12630            .unwrap();
12631
12632        assert_eq!(relative_rows[&DisplayRow(0)], 3);
12633        assert_eq!(relative_rows[&DisplayRow(1)], 2);
12634        assert_eq!(relative_rows[&DisplayRow(2)], 1);
12635        // current line has no relative number
12636        assert!(!relative_rows.contains_key(&DisplayRow(3)));
12637        assert_eq!(relative_rows[&DisplayRow(4)], 1);
12638        assert_eq!(relative_rows[&DisplayRow(5)], 2);
12639
12640        let layouts = cx
12641            .update_window(*window, |_, window, cx| {
12642                element.layout_line_numbers(
12643                    None,
12644                    GutterDimensions {
12645                        left_padding: Pixels::ZERO,
12646                        right_padding: Pixels::ZERO,
12647                        width: px(30.0),
12648                        margin: Pixels::ZERO,
12649                        git_blame_entries_width: None,
12650                    },
12651                    line_height,
12652                    gpui::Point::default(),
12653                    DisplayRow(0)..DisplayRow(6),
12654                    &(0..6)
12655                        .map(|row| RowInfo {
12656                            buffer_row: Some(row),
12657                            diff_status: Some(DiffHunkStatus::deleted(
12658                                buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12659                            )),
12660                            ..Default::default()
12661                        })
12662                        .collect::<Vec<_>>(),
12663                    &BTreeMap::from_iter([(DisplayRow(0), LineHighlightSpec::default())]),
12664                    Some(DisplayRow(0)),
12665                    &snapshot,
12666                    window,
12667                    cx,
12668                )
12669            })
12670            .unwrap();
12671        assert!(
12672            layouts.is_empty(),
12673            "Deleted lines should have no line number"
12674        );
12675
12676        let relative_rows = window
12677            .update(cx, |editor, window, cx| {
12678                let snapshot = editor.snapshot(window, cx);
12679                snapshot.calculate_relative_line_numbers(
12680                    &(DisplayRow(0)..DisplayRow(6)),
12681                    DisplayRow(3),
12682                    true,
12683                )
12684            })
12685            .unwrap();
12686
12687        // Deleted lines should still have relative numbers
12688        assert_eq!(relative_rows[&DisplayRow(0)], 3);
12689        assert_eq!(relative_rows[&DisplayRow(1)], 2);
12690        assert_eq!(relative_rows[&DisplayRow(2)], 1);
12691        // current line, even if deleted, has no relative number
12692        assert!(!relative_rows.contains_key(&DisplayRow(3)));
12693        assert_eq!(relative_rows[&DisplayRow(4)], 1);
12694        assert_eq!(relative_rows[&DisplayRow(5)], 2);
12695    }
12696
12697    #[gpui::test]
12698    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
12699        init_test(cx, |_| {});
12700
12701        let window = cx.add_window(|window, cx| {
12702            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
12703            Editor::new(EditorMode::full(), buffer, None, window, cx)
12704        });
12705        let cx = &mut VisualTestContext::from_window(*window, cx);
12706        let editor = window.root(cx).unwrap();
12707        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12708
12709        window
12710            .update(cx, |editor, window, cx| {
12711                editor.cursor_offset_on_selection = true;
12712                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
12713                    s.select_ranges([
12714                        Point::new(0, 0)..Point::new(1, 0),
12715                        Point::new(3, 2)..Point::new(3, 3),
12716                        Point::new(5, 6)..Point::new(6, 0),
12717                    ]);
12718                });
12719            })
12720            .unwrap();
12721
12722        let (_, state) = cx.draw(
12723            point(px(500.), px(500.)),
12724            size(px(500.), px(500.)),
12725            |_, _| EditorElement::new(&editor, style),
12726        );
12727
12728        assert_eq!(state.selections.len(), 1);
12729        let local_selections = &state.selections[0].1;
12730        assert_eq!(local_selections.len(), 3);
12731        // moves cursor back one line
12732        assert_eq!(
12733            local_selections[0].head,
12734            DisplayPoint::new(DisplayRow(0), 6)
12735        );
12736        assert_eq!(
12737            local_selections[0].range,
12738            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
12739        );
12740
12741        // moves cursor back one column
12742        assert_eq!(
12743            local_selections[1].range,
12744            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
12745        );
12746        assert_eq!(
12747            local_selections[1].head,
12748            DisplayPoint::new(DisplayRow(3), 2)
12749        );
12750
12751        // leaves cursor on the max point
12752        assert_eq!(
12753            local_selections[2].range,
12754            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
12755        );
12756        assert_eq!(
12757            local_selections[2].head,
12758            DisplayPoint::new(DisplayRow(6), 0)
12759        );
12760
12761        // active lines does not include 1 (even though the range of the selection does)
12762        assert_eq!(
12763            state.active_rows.keys().cloned().collect::<Vec<_>>(),
12764            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
12765        );
12766    }
12767
12768    #[gpui::test]
12769    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
12770        init_test(cx, |_| {});
12771
12772        let window = cx.add_window(|window, cx| {
12773            let buffer = MultiBuffer::build_simple("", cx);
12774            Editor::new(EditorMode::full(), buffer, None, window, cx)
12775        });
12776        let cx = &mut VisualTestContext::from_window(*window, cx);
12777        let editor = window.root(cx).unwrap();
12778        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12779        window
12780            .update(cx, |editor, window, cx| {
12781                editor.set_placeholder_text("hello", window, cx);
12782                editor.insert_blocks(
12783                    [BlockProperties {
12784                        style: BlockStyle::Fixed,
12785                        placement: BlockPlacement::Above(Anchor::min()),
12786                        height: Some(3),
12787                        render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
12788                        priority: 0,
12789                    }],
12790                    None,
12791                    cx,
12792                );
12793
12794                // Blur the editor so that it displays placeholder text.
12795                window.blur();
12796            })
12797            .unwrap();
12798
12799        let (_, state) = cx.draw(
12800            point(px(500.), px(500.)),
12801            size(px(500.), px(500.)),
12802            |_, _| EditorElement::new(&editor, style),
12803        );
12804        assert_eq!(state.position_map.line_layouts.len(), 4);
12805        assert_eq!(state.line_numbers.len(), 1);
12806        assert_eq!(
12807            state
12808                .line_numbers
12809                .get(&MultiBufferRow(0))
12810                .map(|line_number| line_number
12811                    .segments
12812                    .first()
12813                    .unwrap()
12814                    .shaped_line
12815                    .text
12816                    .as_ref()),
12817            Some("1")
12818        );
12819    }
12820
12821    #[gpui::test]
12822    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
12823        const TAB_SIZE: u32 = 4;
12824
12825        let input_text = "\t \t|\t| a b";
12826        let expected_invisibles = vec![
12827            Invisible::Tab {
12828                line_start_offset: 0,
12829                line_end_offset: TAB_SIZE as usize,
12830            },
12831            Invisible::Whitespace {
12832                line_offset: TAB_SIZE as usize,
12833            },
12834            Invisible::Tab {
12835                line_start_offset: TAB_SIZE as usize + 1,
12836                line_end_offset: TAB_SIZE as usize * 2,
12837            },
12838            Invisible::Tab {
12839                line_start_offset: TAB_SIZE as usize * 2 + 1,
12840                line_end_offset: TAB_SIZE as usize * 3,
12841            },
12842            Invisible::Whitespace {
12843                line_offset: TAB_SIZE as usize * 3 + 1,
12844            },
12845            Invisible::Whitespace {
12846                line_offset: TAB_SIZE as usize * 3 + 3,
12847            },
12848        ];
12849        assert_eq!(
12850            expected_invisibles.len(),
12851            input_text
12852                .chars()
12853                .filter(|initial_char| initial_char.is_whitespace())
12854                .count(),
12855            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
12856        );
12857
12858        for show_line_numbers in [true, false] {
12859            init_test(cx, |s| {
12860                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12861                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
12862            });
12863
12864            let actual_invisibles = collect_invisibles_from_new_editor(
12865                cx,
12866                EditorMode::full(),
12867                input_text,
12868                px(500.0),
12869                show_line_numbers,
12870            );
12871
12872            assert_eq!(expected_invisibles, actual_invisibles);
12873        }
12874    }
12875
12876    #[gpui::test]
12877    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
12878        init_test(cx, |s| {
12879            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12880            s.defaults.tab_size = NonZeroU32::new(4);
12881        });
12882
12883        for editor_mode_without_invisibles in [
12884            EditorMode::SingleLine,
12885            EditorMode::AutoHeight {
12886                min_lines: 1,
12887                max_lines: Some(100),
12888            },
12889        ] {
12890            for show_line_numbers in [true, false] {
12891                let invisibles = collect_invisibles_from_new_editor(
12892                    cx,
12893                    editor_mode_without_invisibles.clone(),
12894                    "\t\t\t| | a b",
12895                    px(500.0),
12896                    show_line_numbers,
12897                );
12898                assert!(
12899                    invisibles.is_empty(),
12900                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
12901                );
12902            }
12903        }
12904    }
12905
12906    #[gpui::test]
12907    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
12908        let tab_size = 4;
12909        let input_text = "a\tbcd     ".repeat(9);
12910        let repeated_invisibles = [
12911            Invisible::Tab {
12912                line_start_offset: 1,
12913                line_end_offset: tab_size as usize,
12914            },
12915            Invisible::Whitespace {
12916                line_offset: tab_size as usize + 3,
12917            },
12918            Invisible::Whitespace {
12919                line_offset: tab_size as usize + 4,
12920            },
12921            Invisible::Whitespace {
12922                line_offset: tab_size as usize + 5,
12923            },
12924            Invisible::Whitespace {
12925                line_offset: tab_size as usize + 6,
12926            },
12927            Invisible::Whitespace {
12928                line_offset: tab_size as usize + 7,
12929            },
12930        ];
12931        let expected_invisibles = std::iter::once(repeated_invisibles)
12932            .cycle()
12933            .take(9)
12934            .flatten()
12935            .collect::<Vec<_>>();
12936        assert_eq!(
12937            expected_invisibles.len(),
12938            input_text
12939                .chars()
12940                .filter(|initial_char| initial_char.is_whitespace())
12941                .count(),
12942            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
12943        );
12944        info!("Expected invisibles: {expected_invisibles:?}");
12945
12946        init_test(cx, |_| {});
12947
12948        // Put the same string with repeating whitespace pattern into editors of various size,
12949        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
12950        let resize_step = 10.0;
12951        let mut editor_width = 200.0;
12952        while editor_width <= 1000.0 {
12953            for show_line_numbers in [true, false] {
12954                update_test_language_settings(cx, &|s| {
12955                    s.defaults.tab_size = NonZeroU32::new(tab_size);
12956                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12957                    s.defaults.preferred_line_length = Some(editor_width as u32);
12958                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
12959                });
12960
12961                let actual_invisibles = collect_invisibles_from_new_editor(
12962                    cx,
12963                    EditorMode::full(),
12964                    &input_text,
12965                    px(editor_width),
12966                    show_line_numbers,
12967                );
12968
12969                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
12970                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
12971                let mut i = 0;
12972                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
12973                    i = actual_index;
12974                    match expected_invisibles.get(i) {
12975                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
12976                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
12977                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
12978                            _ => {
12979                                panic!(
12980                                    "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
12981                                )
12982                            }
12983                        },
12984                        None => {
12985                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
12986                        }
12987                    }
12988                }
12989                let missing_expected_invisibles = &expected_invisibles[i + 1..];
12990                assert!(
12991                    missing_expected_invisibles.is_empty(),
12992                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
12993                );
12994
12995                editor_width += resize_step;
12996            }
12997        }
12998    }
12999
13000    fn collect_invisibles_from_new_editor(
13001        cx: &mut TestAppContext,
13002        editor_mode: EditorMode,
13003        input_text: &str,
13004        editor_width: Pixels,
13005        show_line_numbers: bool,
13006    ) -> Vec<Invisible> {
13007        info!(
13008            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
13009            f32::from(editor_width)
13010        );
13011        let window = cx.add_window(|window, cx| {
13012            let buffer = MultiBuffer::build_simple(input_text, cx);
13013            Editor::new(editor_mode, buffer, None, window, cx)
13014        });
13015        let cx = &mut VisualTestContext::from_window(*window, cx);
13016        let editor = window.root(cx).unwrap();
13017
13018        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
13019        window
13020            .update(cx, |editor, _, cx| {
13021                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
13022                editor.set_wrap_width(Some(editor_width), cx);
13023                editor.set_show_line_numbers(show_line_numbers, cx);
13024            })
13025            .unwrap();
13026        let (_, state) = cx.draw(
13027            point(px(500.), px(500.)),
13028            size(px(500.), px(500.)),
13029            |_, _| EditorElement::new(&editor, style),
13030        );
13031        state
13032            .position_map
13033            .line_layouts
13034            .iter()
13035            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
13036            .cloned()
13037            .collect()
13038    }
13039
13040    #[gpui::test]
13041    fn test_merge_overlapping_ranges() {
13042        let base_bg = Hsla::white();
13043        let color1 = Hsla {
13044            h: 0.0,
13045            s: 0.5,
13046            l: 0.5,
13047            a: 0.5,
13048        };
13049        let color2 = Hsla {
13050            h: 120.0,
13051            s: 0.5,
13052            l: 0.5,
13053            a: 0.5,
13054        };
13055
13056        let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
13057        let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
13058            v.iter()
13059                .map(|(r, _)| (r.start.column(), r.end.column()))
13060                .collect()
13061        };
13062
13063        // Test overlapping ranges blend colors
13064        let overlapping = vec![
13065            (display_point(5)..display_point(15), color1),
13066            (display_point(10)..display_point(20), color2),
13067        ];
13068        let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
13069        assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
13070
13071        // Test middle segment should have blended color
13072        let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
13073        assert_eq!(result[1].1, blended);
13074
13075        // Test adjacent same-color ranges merge
13076        let adjacent_same = vec![
13077            (display_point(5)..display_point(10), color1),
13078            (display_point(10)..display_point(15), color1),
13079        ];
13080        let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
13081        assert_eq!(cols(&result), vec![(5, 15)]);
13082
13083        // Test contained range splits
13084        let contained = vec![
13085            (display_point(5)..display_point(20), color1),
13086            (display_point(10)..display_point(15), color2),
13087        ];
13088        let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
13089        assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
13090
13091        // Test multiple overlaps split at every boundary
13092        let color3 = Hsla {
13093            h: 240.0,
13094            s: 0.5,
13095            l: 0.5,
13096            a: 0.5,
13097        };
13098        let complex = vec![
13099            (display_point(5)..display_point(12), color1),
13100            (display_point(8)..display_point(16), color2),
13101            (display_point(10)..display_point(14), color3),
13102        ];
13103        let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
13104        assert_eq!(
13105            cols(&result),
13106            vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
13107        );
13108    }
13109
13110    #[gpui::test]
13111    fn test_bg_segments_per_row() {
13112        let base_bg = Hsla::white();
13113
13114        // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
13115        {
13116            let selection_color = Hsla {
13117                h: 200.0,
13118                s: 0.5,
13119                l: 0.5,
13120                a: 0.5,
13121            };
13122            let player_color = PlayerColor {
13123                cursor: selection_color,
13124                background: selection_color,
13125                selection: selection_color,
13126            };
13127
13128            let spanning_selection = SelectionLayout {
13129                head: DisplayPoint::new(DisplayRow(3), 7),
13130                cursor_shape: CursorShape::Bar,
13131                is_newest: true,
13132                is_local: true,
13133                range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
13134                active_rows: DisplayRow(1)..DisplayRow(4),
13135                user_name: None,
13136            };
13137
13138            let selections = vec![(player_color, vec![spanning_selection])];
13139            let result = EditorElement::bg_segments_per_row(
13140                DisplayRow(0)..DisplayRow(5),
13141                &selections,
13142                &[],
13143                base_bg,
13144            );
13145
13146            assert_eq!(result.len(), 5);
13147            assert!(result[0].is_empty());
13148            assert_eq!(result[1].len(), 1);
13149            assert_eq!(result[2].len(), 1);
13150            assert_eq!(result[3].len(), 1);
13151            assert!(result[4].is_empty());
13152
13153            assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13154            assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13155            assert_eq!(result[1][0].0.end.column(), u32::MAX);
13156            assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13157            assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13158            assert_eq!(result[2][0].0.end.column(), u32::MAX);
13159            assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
13160            assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
13161        }
13162
13163        // Case B: selection ends exactly at the start of row 3, excluding row 3
13164        {
13165            let selection_color = Hsla {
13166                h: 120.0,
13167                s: 0.5,
13168                l: 0.5,
13169                a: 0.5,
13170            };
13171            let player_color = PlayerColor {
13172                cursor: selection_color,
13173                background: selection_color,
13174                selection: selection_color,
13175            };
13176
13177            let selection = SelectionLayout {
13178                head: DisplayPoint::new(DisplayRow(2), 0),
13179                cursor_shape: CursorShape::Bar,
13180                is_newest: true,
13181                is_local: true,
13182                range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
13183                active_rows: DisplayRow(1)..DisplayRow(3),
13184                user_name: None,
13185            };
13186
13187            let selections = vec![(player_color, vec![selection])];
13188            let result = EditorElement::bg_segments_per_row(
13189                DisplayRow(0)..DisplayRow(4),
13190                &selections,
13191                &[],
13192                base_bg,
13193            );
13194
13195            assert_eq!(result.len(), 4);
13196            assert!(result[0].is_empty());
13197            assert_eq!(result[1].len(), 1);
13198            assert_eq!(result[2].len(), 1);
13199            assert!(result[3].is_empty());
13200
13201            assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13202            assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13203            assert_eq!(result[1][0].0.end.column(), u32::MAX);
13204            assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13205            assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13206            assert_eq!(result[2][0].0.end.column(), u32::MAX);
13207        }
13208    }
13209
13210    #[cfg(test)]
13211    fn generate_test_run(len: usize, color: Hsla) -> TextRun {
13212        TextRun {
13213            len,
13214            color,
13215            ..Default::default()
13216        }
13217    }
13218
13219    #[gpui::test]
13220    fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
13221        init_test(cx, |_| {});
13222
13223        let dx = |start: u32, end: u32| {
13224            DisplayPoint::new(DisplayRow(0), start)..DisplayPoint::new(DisplayRow(0), end)
13225        };
13226
13227        let text_color = Hsla {
13228            h: 210.0,
13229            s: 0.1,
13230            l: 0.4,
13231            a: 1.0,
13232        };
13233        let bg_1 = Hsla {
13234            h: 30.0,
13235            s: 0.6,
13236            l: 0.8,
13237            a: 1.0,
13238        };
13239        let bg_2 = Hsla {
13240            h: 200.0,
13241            s: 0.6,
13242            l: 0.2,
13243            a: 1.0,
13244        };
13245        let min_contrast = 45.0;
13246        let adjusted_bg1 = ensure_minimum_contrast(text_color, bg_1, min_contrast);
13247        let adjusted_bg2 = ensure_minimum_contrast(text_color, bg_2, min_contrast);
13248
13249        // Case A: single run; disjoint segments inside the run
13250        {
13251            let runs = vec![generate_test_run(20, text_color)];
13252            let segs = vec![(dx(5, 10), bg_1), (dx(12, 16), bg_2)];
13253            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13254            // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
13255            assert_eq!(
13256                out.iter().map(|r| r.len).collect::<Vec<_>>(),
13257                vec![5, 5, 2, 4, 4]
13258            );
13259            assert_eq!(out[0].color, text_color);
13260            assert_eq!(out[1].color, adjusted_bg1);
13261            assert_eq!(out[2].color, text_color);
13262            assert_eq!(out[3].color, adjusted_bg2);
13263            assert_eq!(out[4].color, text_color);
13264        }
13265
13266        // Case B: multiple runs; segment extends to end of line (u32::MAX)
13267        {
13268            let runs = vec![
13269                generate_test_run(8, text_color),
13270                generate_test_run(7, text_color),
13271            ];
13272            let segs = vec![(dx(6, u32::MAX), bg_1)];
13273            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13274            // Expected slices across runs: [0,6) [6,8) | [0,7)
13275            assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
13276            assert_eq!(out[0].color, text_color);
13277            assert_eq!(out[1].color, adjusted_bg1);
13278            assert_eq!(out[2].color, adjusted_bg1);
13279        }
13280
13281        // Case C: multi-byte characters
13282        {
13283            // for text: "Hello 🌍 δΈ–η•Œ!"
13284            let runs = vec![
13285                generate_test_run(5, text_color), // "Hello"
13286                generate_test_run(6, text_color), // " 🌍 "
13287                generate_test_run(6, text_color), // "δΈ–η•Œ"
13288                generate_test_run(1, text_color), // "!"
13289            ];
13290            // selecting "🌍 δΈ–"
13291            let segs = vec![(dx(6, 14), bg_1)];
13292            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13293            // "Hello" | " " | "🌍 " | "δΈ–" | "η•Œ" | "!"
13294            assert_eq!(
13295                out.iter().map(|r| r.len).collect::<Vec<_>>(),
13296                vec![5, 1, 5, 3, 3, 1]
13297            );
13298            assert_eq!(out[0].color, text_color); // "Hello"
13299            assert_eq!(out[2].color, adjusted_bg1); // "🌍 "
13300            assert_eq!(out[3].color, adjusted_bg1); // "δΈ–"
13301            assert_eq!(out[4].color, text_color); // "η•Œ"
13302            assert_eq!(out[5].color, text_color); // "!"
13303        }
13304
13305        // Case D: split multiple consecutive text runs with segments
13306        {
13307            let segs = vec![
13308                (dx(2, 4), bg_1),   // selecting "cd"
13309                (dx(4, 8), bg_2),   // selecting "efgh"
13310                (dx(9, 11), bg_1),  // selecting "jk"
13311                (dx(12, 16), bg_2), // selecting "mnop"
13312                (dx(18, 19), bg_1), // selecting "s"
13313            ];
13314
13315            // for text: "abcdef"
13316            let runs = vec![
13317                generate_test_run(2, text_color), // ab
13318                generate_test_run(4, text_color), // cdef
13319            ];
13320            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13321            // new splits "ab", "cd", "ef"
13322            assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![2, 2, 2]);
13323            assert_eq!(out[0].color, text_color);
13324            assert_eq!(out[1].color, adjusted_bg1);
13325            assert_eq!(out[2].color, adjusted_bg2);
13326
13327            // for text: "ghijklmn"
13328            let runs = vec![
13329                generate_test_run(3, text_color), // ghi
13330                generate_test_run(2, text_color), // jk
13331                generate_test_run(3, text_color), // lmn
13332            ];
13333            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 6); // 2 + 4 from first run
13334            // new splits "gh", "i", "jk", "l", "mn"
13335            assert_eq!(
13336                out.iter().map(|r| r.len).collect::<Vec<_>>(),
13337                vec![2, 1, 2, 1, 2]
13338            );
13339            assert_eq!(out[0].color, adjusted_bg2);
13340            assert_eq!(out[1].color, text_color);
13341            assert_eq!(out[2].color, adjusted_bg1);
13342            assert_eq!(out[3].color, text_color);
13343            assert_eq!(out[4].color, adjusted_bg2);
13344
13345            // for text: "opqrs"
13346            let runs = vec![
13347                generate_test_run(1, text_color), // o
13348                generate_test_run(4, text_color), // pqrs
13349            ];
13350            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 14); // 6 + 3 + 2 + 3 from first two runs
13351            // new splits "o", "p", "qr", "s"
13352            assert_eq!(
13353                out.iter().map(|r| r.len).collect::<Vec<_>>(),
13354                vec![1, 1, 2, 1]
13355            );
13356            assert_eq!(out[0].color, adjusted_bg2);
13357            assert_eq!(out[1].color, adjusted_bg2);
13358            assert_eq!(out[2].color, text_color);
13359            assert_eq!(out[3].color, adjusted_bg1);
13360        }
13361    }
13362
13363    #[test]
13364    fn test_checkerboard_size() {
13365        // line height is smaller than target height, so we just return half the line height
13366        assert_eq!(EditorElement::checkerboard_size(10.0, 20.0), 5.0);
13367
13368        // line height is exactly half the target height, perfect match
13369        assert_eq!(EditorElement::checkerboard_size(20.0, 10.0), 10.0);
13370
13371        // line height is close to half the target height
13372        assert_eq!(EditorElement::checkerboard_size(20.0, 9.0), 10.0);
13373
13374        // line height is close to 1/4 the target height
13375        assert_eq!(EditorElement::checkerboard_size(20.0, 4.8), 5.0);
13376    }
13377
13378    #[gpui::test(iterations = 100)]
13379    fn test_random_checkerboard_size(mut rng: StdRng) {
13380        let line_height = rng.next_u32() as f32;
13381        let target_height = rng.next_u32() as f32;
13382
13383        let result = EditorElement::checkerboard_size(line_height, target_height);
13384
13385        let k = line_height / result;
13386        assert!(k - k.round() < 0.0000001); // approximately integer
13387        assert!((k.round() as u32).is_multiple_of(2));
13388    }
13389
13390    #[test]
13391    fn test_calculate_wrap_width() {
13392        let editor_width = px(800.0);
13393        let em_width = px(8.0);
13394
13395        assert_eq!(
13396            calculate_wrap_width(SoftWrap::GitDiff, editor_width, em_width),
13397            None,
13398        );
13399
13400        assert_eq!(
13401            calculate_wrap_width(SoftWrap::None, editor_width, em_width),
13402            Some(px((MAX_LINE_LEN as f32 / 2.0 * 8.0).ceil())),
13403        );
13404
13405        assert_eq!(
13406            calculate_wrap_width(SoftWrap::EditorWidth, editor_width, em_width),
13407            Some(px(800.0)),
13408        );
13409
13410        assert_eq!(
13411            calculate_wrap_width(SoftWrap::Column(72), editor_width, em_width),
13412            Some(px((72.0 * 8.0_f32).ceil())),
13413        );
13414
13415        assert_eq!(
13416            calculate_wrap_width(SoftWrap::Bounded(72), editor_width, em_width),
13417            Some(px((72.0 * 8.0_f32).ceil())),
13418        );
13419        assert_eq!(
13420            calculate_wrap_width(SoftWrap::Bounded(200), px(400.0), em_width),
13421            Some(px(400.0)),
13422        );
13423    }
13424}