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