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