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