element.rs

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