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