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