element.rs

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