element.rs

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