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