element.rs

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