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