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