element.rs

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