element.rs

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