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, MINIMAP_FONT_SIZE, MULTI_BUFFER_EXCERPT_HEADER_HEIGHT, OpenExcerpts, PageDown,
   10    PageUp, PhantomBreakpointIndicator, Point, RowExt, RowRangeExt, SelectPhase,
   11    SelectedTextHighlight, Selection, SelectionDragState, SoftWrap, StickyHeaderExcerpt, ToPoint,
   12    ToggleFold,
   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, HighlightKey,
   16        HighlightedChunk, 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
 2830                    >= EditorSettings::get_global(cx).gutter.min_line_number_digits as u32
 2831                    && row_info
 2832                        .buffer_row
 2833                        .is_some_and(|row| (row + 1).ilog10() + 1 == max_line_number_length)
 2834                    || gutter_dimensions.right_padding == px(0.);
 2835
 2836                let width = if is_wide {
 2837                    available_width - px(2.)
 2838                } else {
 2839                    available_width + em_width - px(2.)
 2840                };
 2841
 2842                let toggle = IconButton::new(("expand", ix), icon_name)
 2843                    .icon_color(Color::Custom(cx.theme().colors().editor_line_number))
 2844                    .selected_icon_color(Color::Custom(cx.theme().colors().editor_foreground))
 2845                    .icon_size(IconSize::Custom(rems(editor_font_size / window.rem_size())))
 2846                    .width(width.into())
 2847                    .on_click(move |_, window, cx| {
 2848                        editor.update(cx, |editor, cx| {
 2849                            editor.expand_excerpt(excerpt_id, direction, window, cx);
 2850                        });
 2851                    })
 2852                    .tooltip(Tooltip::for_action_title(
 2853                        "Expand Excerpt",
 2854                        &crate::actions::ExpandExcerpts::default(),
 2855                    ))
 2856                    .into_any_element();
 2857
 2858                let position = point(
 2859                    git_gutter_width + px(1.),
 2860                    ix as f32 * line_height - (scroll_top % line_height) + px(1.),
 2861                );
 2862                let origin = gutter_hitbox.origin + position;
 2863
 2864                Some((toggle, origin))
 2865            })
 2866            .collect();
 2867
 2868        elements
 2869    }
 2870
 2871    fn calculate_relative_line_numbers(
 2872        &self,
 2873        snapshot: &EditorSnapshot,
 2874        rows: &Range<DisplayRow>,
 2875        relative_to: Option<DisplayRow>,
 2876    ) -> HashMap<DisplayRow, DisplayRowDelta> {
 2877        let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
 2878        let Some(relative_to) = relative_to else {
 2879            return relative_rows;
 2880        };
 2881
 2882        let start = rows.start.min(relative_to);
 2883        let end = rows.end.max(relative_to);
 2884
 2885        let buffer_rows = snapshot
 2886            .row_infos(start)
 2887            .take(1 + end.minus(start) as usize)
 2888            .collect::<Vec<_>>();
 2889
 2890        let head_idx = relative_to.minus(start);
 2891        let mut delta = 1;
 2892        let mut i = head_idx + 1;
 2893        while i < buffer_rows.len() as u32 {
 2894            if buffer_rows[i as usize].buffer_row.is_some() {
 2895                if rows.contains(&DisplayRow(i + start.0)) {
 2896                    relative_rows.insert(DisplayRow(i + start.0), delta);
 2897                }
 2898                delta += 1;
 2899            }
 2900            i += 1;
 2901        }
 2902        delta = 1;
 2903        i = head_idx.min(buffer_rows.len() as u32 - 1);
 2904        while i > 0 && buffer_rows[i as usize].buffer_row.is_none() {
 2905            i -= 1;
 2906        }
 2907
 2908        while i > 0 {
 2909            i -= 1;
 2910            if buffer_rows[i as usize].buffer_row.is_some() {
 2911                if rows.contains(&DisplayRow(i + start.0)) {
 2912                    relative_rows.insert(DisplayRow(i + start.0), delta);
 2913                }
 2914                delta += 1;
 2915            }
 2916        }
 2917
 2918        relative_rows
 2919    }
 2920
 2921    fn layout_line_numbers(
 2922        &self,
 2923        gutter_hitbox: Option<&Hitbox>,
 2924        gutter_dimensions: GutterDimensions,
 2925        line_height: Pixels,
 2926        scroll_position: gpui::Point<f32>,
 2927        rows: Range<DisplayRow>,
 2928        buffer_rows: &[RowInfo],
 2929        active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
 2930        newest_selection_head: Option<DisplayPoint>,
 2931        snapshot: &EditorSnapshot,
 2932        window: &mut Window,
 2933        cx: &mut App,
 2934    ) -> Arc<HashMap<MultiBufferRow, LineNumberLayout>> {
 2935        let include_line_numbers = snapshot.show_line_numbers.unwrap_or_else(|| {
 2936            EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode.is_full()
 2937        });
 2938        if !include_line_numbers {
 2939            return Arc::default();
 2940        }
 2941
 2942        let (newest_selection_head, is_relative) = self.editor.update(cx, |editor, cx| {
 2943            let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
 2944                let newest = editor.selections.newest::<Point>(cx);
 2945                SelectionLayout::new(
 2946                    newest,
 2947                    editor.selections.line_mode,
 2948                    editor.cursor_shape,
 2949                    &snapshot.display_snapshot,
 2950                    true,
 2951                    true,
 2952                    None,
 2953                )
 2954                .head
 2955            });
 2956            let is_relative = editor.should_use_relative_line_numbers(cx);
 2957            (newest_selection_head, is_relative)
 2958        });
 2959
 2960        let relative_to = if is_relative {
 2961            Some(newest_selection_head.row())
 2962        } else {
 2963            None
 2964        };
 2965        let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
 2966        let mut line_number = String::new();
 2967        let line_numbers = buffer_rows
 2968            .into_iter()
 2969            .enumerate()
 2970            .flat_map(|(ix, row_info)| {
 2971                let display_row = DisplayRow(rows.start.0 + ix as u32);
 2972                line_number.clear();
 2973                let non_relative_number = row_info.buffer_row? + 1;
 2974                let number = relative_rows
 2975                    .get(&display_row)
 2976                    .unwrap_or(&non_relative_number);
 2977                write!(&mut line_number, "{number}").unwrap();
 2978                if row_info
 2979                    .diff_status
 2980                    .is_some_and(|status| status.is_deleted())
 2981                {
 2982                    return None;
 2983                }
 2984
 2985                let color = active_rows
 2986                    .get(&display_row)
 2987                    .map(|spec| {
 2988                        if spec.breakpoint {
 2989                            cx.theme().colors().debugger_accent
 2990                        } else {
 2991                            cx.theme().colors().editor_active_line_number
 2992                        }
 2993                    })
 2994                    .unwrap_or_else(|| cx.theme().colors().editor_line_number);
 2995                let shaped_line =
 2996                    self.shape_line_number(SharedString::from(&line_number), color, window);
 2997                let scroll_top = scroll_position.y * line_height;
 2998                let line_origin = gutter_hitbox.map(|hitbox| {
 2999                    hitbox.origin
 3000                        + point(
 3001                            hitbox.size.width - shaped_line.width - gutter_dimensions.right_padding,
 3002                            ix as f32 * line_height - (scroll_top % line_height),
 3003                        )
 3004                });
 3005
 3006                #[cfg(not(test))]
 3007                let hitbox = line_origin.map(|line_origin| {
 3008                    window.insert_hitbox(
 3009                        Bounds::new(line_origin, size(shaped_line.width, line_height)),
 3010                        HitboxBehavior::Normal,
 3011                    )
 3012                });
 3013                #[cfg(test)]
 3014                let hitbox = {
 3015                    let _ = line_origin;
 3016                    None
 3017                };
 3018
 3019                let multi_buffer_row = DisplayPoint::new(display_row, 0).to_point(snapshot).row;
 3020                let multi_buffer_row = MultiBufferRow(multi_buffer_row);
 3021                let line_number = LineNumberLayout {
 3022                    shaped_line,
 3023                    hitbox,
 3024                };
 3025                Some((multi_buffer_row, line_number))
 3026            })
 3027            .collect();
 3028        Arc::new(line_numbers)
 3029    }
 3030
 3031    fn layout_crease_toggles(
 3032        &self,
 3033        rows: Range<DisplayRow>,
 3034        row_infos: &[RowInfo],
 3035        active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
 3036        snapshot: &EditorSnapshot,
 3037        window: &mut Window,
 3038        cx: &mut App,
 3039    ) -> Vec<Option<AnyElement>> {
 3040        let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
 3041            && snapshot.mode.is_full()
 3042            && self.editor.read(cx).is_singleton(cx);
 3043        if include_fold_statuses {
 3044            row_infos
 3045                .into_iter()
 3046                .enumerate()
 3047                .map(|(ix, info)| {
 3048                    if info.expand_info.is_some() {
 3049                        return None;
 3050                    }
 3051                    let row = info.multibuffer_row?;
 3052                    let display_row = DisplayRow(rows.start.0 + ix as u32);
 3053                    let active = active_rows.contains_key(&display_row);
 3054
 3055                    snapshot.render_crease_toggle(row, active, self.editor.clone(), window, cx)
 3056                })
 3057                .collect()
 3058        } else {
 3059            Vec::new()
 3060        }
 3061    }
 3062
 3063    fn layout_crease_trailers(
 3064        &self,
 3065        buffer_rows: impl IntoIterator<Item = RowInfo>,
 3066        snapshot: &EditorSnapshot,
 3067        window: &mut Window,
 3068        cx: &mut App,
 3069    ) -> Vec<Option<AnyElement>> {
 3070        buffer_rows
 3071            .into_iter()
 3072            .map(|row_info| {
 3073                if row_info.expand_info.is_some() {
 3074                    return None;
 3075                }
 3076                if let Some(row) = row_info.multibuffer_row {
 3077                    snapshot.render_crease_trailer(row, window, cx)
 3078                } else {
 3079                    None
 3080                }
 3081            })
 3082            .collect()
 3083    }
 3084
 3085    fn layout_lines(
 3086        rows: Range<DisplayRow>,
 3087        snapshot: &EditorSnapshot,
 3088        style: &EditorStyle,
 3089        editor_width: Pixels,
 3090        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 3091        window: &mut Window,
 3092        cx: &mut App,
 3093    ) -> Vec<LineWithInvisibles> {
 3094        if rows.start >= rows.end {
 3095            return Vec::new();
 3096        }
 3097
 3098        // Show the placeholder when the editor is empty
 3099        if snapshot.is_empty() {
 3100            let font_size = style.text.font_size.to_pixels(window.rem_size());
 3101            let placeholder_color = cx.theme().colors().text_placeholder;
 3102            let placeholder_text = snapshot.placeholder_text();
 3103
 3104            let placeholder_lines = placeholder_text
 3105                .as_ref()
 3106                .map_or("", AsRef::as_ref)
 3107                .split('\n')
 3108                .skip(rows.start.0 as usize)
 3109                .chain(iter::repeat(""))
 3110                .take(rows.len());
 3111            placeholder_lines
 3112                .map(move |line| {
 3113                    let run = TextRun {
 3114                        len: line.len(),
 3115                        font: style.text.font(),
 3116                        color: placeholder_color,
 3117                        background_color: None,
 3118                        underline: None,
 3119                        strikethrough: None,
 3120                    };
 3121                    let line =
 3122                        window
 3123                            .text_system()
 3124                            .shape_line(line.to_string().into(), font_size, &[run]);
 3125                    LineWithInvisibles {
 3126                        width: line.width,
 3127                        len: line.len,
 3128                        fragments: smallvec![LineFragment::Text(line)],
 3129                        invisibles: Vec::new(),
 3130                        font_size,
 3131                    }
 3132                })
 3133                .collect()
 3134        } else {
 3135            let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
 3136            LineWithInvisibles::from_chunks(
 3137                chunks,
 3138                &style,
 3139                MAX_LINE_LEN,
 3140                rows.len(),
 3141                &snapshot.mode,
 3142                editor_width,
 3143                is_row_soft_wrapped,
 3144                window,
 3145                cx,
 3146            )
 3147        }
 3148    }
 3149
 3150    fn prepaint_lines(
 3151        &self,
 3152        start_row: DisplayRow,
 3153        line_layouts: &mut [LineWithInvisibles],
 3154        line_height: Pixels,
 3155        scroll_pixel_position: gpui::Point<Pixels>,
 3156        content_origin: gpui::Point<Pixels>,
 3157        window: &mut Window,
 3158        cx: &mut App,
 3159    ) -> SmallVec<[AnyElement; 1]> {
 3160        let mut line_elements = SmallVec::new();
 3161        for (ix, line) in line_layouts.iter_mut().enumerate() {
 3162            let row = start_row + DisplayRow(ix as u32);
 3163            line.prepaint(
 3164                line_height,
 3165                scroll_pixel_position,
 3166                row,
 3167                content_origin,
 3168                &mut line_elements,
 3169                window,
 3170                cx,
 3171            );
 3172        }
 3173        line_elements
 3174    }
 3175
 3176    fn render_block(
 3177        &self,
 3178        block: &Block,
 3179        available_width: AvailableSpace,
 3180        block_id: BlockId,
 3181        block_row_start: DisplayRow,
 3182        snapshot: &EditorSnapshot,
 3183        text_x: Pixels,
 3184        rows: &Range<DisplayRow>,
 3185        line_layouts: &[LineWithInvisibles],
 3186        editor_margins: &EditorMargins,
 3187        line_height: Pixels,
 3188        em_width: Pixels,
 3189        text_hitbox: &Hitbox,
 3190        editor_width: Pixels,
 3191        scroll_width: &mut Pixels,
 3192        resized_blocks: &mut HashMap<CustomBlockId, u32>,
 3193        row_block_types: &mut HashMap<DisplayRow, bool>,
 3194        selections: &[Selection<Point>],
 3195        selected_buffer_ids: &Vec<BufferId>,
 3196        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 3197        sticky_header_excerpt_id: Option<ExcerptId>,
 3198        window: &mut Window,
 3199        cx: &mut App,
 3200    ) -> Option<(AnyElement, Size<Pixels>, DisplayRow, Pixels)> {
 3201        let mut x_position = None;
 3202        let mut element = match block {
 3203            Block::Custom(custom) => {
 3204                let block_start = custom.start().to_point(&snapshot.buffer_snapshot);
 3205                let block_end = custom.end().to_point(&snapshot.buffer_snapshot);
 3206                if block.place_near() && snapshot.is_line_folded(MultiBufferRow(block_start.row)) {
 3207                    return None;
 3208                }
 3209                let align_to = block_start.to_display_point(snapshot);
 3210                let x_and_width = |layout: &LineWithInvisibles| {
 3211                    Some((
 3212                        text_x + layout.x_for_index(align_to.column() as usize),
 3213                        text_x + layout.width,
 3214                    ))
 3215                };
 3216                let line_ix = align_to.row().0.checked_sub(rows.start.0);
 3217                x_position =
 3218                    if let Some(layout) = line_ix.and_then(|ix| line_layouts.get(ix as usize)) {
 3219                        x_and_width(&layout)
 3220                    } else {
 3221                        x_and_width(&layout_line(
 3222                            align_to.row(),
 3223                            snapshot,
 3224                            &self.style,
 3225                            editor_width,
 3226                            is_row_soft_wrapped,
 3227                            window,
 3228                            cx,
 3229                        ))
 3230                    };
 3231
 3232                let anchor_x = x_position.unwrap().0;
 3233
 3234                let selected = selections
 3235                    .binary_search_by(|selection| {
 3236                        if selection.end <= block_start {
 3237                            Ordering::Less
 3238                        } else if selection.start >= block_end {
 3239                            Ordering::Greater
 3240                        } else {
 3241                            Ordering::Equal
 3242                        }
 3243                    })
 3244                    .is_ok();
 3245
 3246                div()
 3247                    .size_full()
 3248                    .children(
 3249                        (!snapshot.mode.is_minimap() || custom.render_in_minimap).then(|| {
 3250                            custom.render(&mut BlockContext {
 3251                                window,
 3252                                app: cx,
 3253                                anchor_x,
 3254                                margins: editor_margins,
 3255                                line_height,
 3256                                em_width,
 3257                                block_id,
 3258                                selected,
 3259                                max_width: text_hitbox.size.width.max(*scroll_width),
 3260                                editor_style: &self.style,
 3261                            })
 3262                        }),
 3263                    )
 3264                    .into_any()
 3265            }
 3266
 3267            Block::FoldedBuffer {
 3268                first_excerpt,
 3269                height,
 3270                ..
 3271            } => {
 3272                let selected = selected_buffer_ids.contains(&first_excerpt.buffer_id);
 3273                let result = v_flex().id(block_id).w_full().pr(editor_margins.right);
 3274
 3275                let jump_data = header_jump_data(snapshot, block_row_start, *height, first_excerpt);
 3276                result
 3277                    .child(self.render_buffer_header(
 3278                        first_excerpt,
 3279                        true,
 3280                        selected,
 3281                        false,
 3282                        jump_data,
 3283                        window,
 3284                        cx,
 3285                    ))
 3286                    .into_any_element()
 3287            }
 3288
 3289            Block::ExcerptBoundary {
 3290                excerpt,
 3291                height,
 3292                starts_new_buffer,
 3293                ..
 3294            } => {
 3295                let color = cx.theme().colors().clone();
 3296                let mut result = v_flex().id(block_id).w_full();
 3297
 3298                let jump_data = header_jump_data(snapshot, block_row_start, *height, excerpt);
 3299
 3300                if *starts_new_buffer {
 3301                    if sticky_header_excerpt_id != Some(excerpt.id) {
 3302                        let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
 3303
 3304                        result = result.child(div().pr(editor_margins.right).child(
 3305                            self.render_buffer_header(
 3306                                excerpt, false, selected, false, jump_data, window, cx,
 3307                            ),
 3308                        ));
 3309                    } else {
 3310                        result =
 3311                            result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
 3312                    }
 3313                } else {
 3314                    result = result.child(
 3315                        h_flex().relative().child(
 3316                            div()
 3317                                .top(line_height / 2.)
 3318                                .absolute()
 3319                                .w_full()
 3320                                .h_px()
 3321                                .bg(color.border_variant),
 3322                        ),
 3323                    );
 3324                };
 3325
 3326                result.into_any()
 3327            }
 3328        };
 3329
 3330        // Discover the element's content height, then round up to the nearest multiple of line height.
 3331        let preliminary_size = element.layout_as_root(
 3332            size(available_width, AvailableSpace::MinContent),
 3333            window,
 3334            cx,
 3335        );
 3336        let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
 3337        let final_size = if preliminary_size.height == quantized_height {
 3338            preliminary_size
 3339        } else {
 3340            element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
 3341        };
 3342        let mut element_height_in_lines = ((final_size.height / line_height).ceil() as u32).max(1);
 3343
 3344        let mut row = block_row_start;
 3345        let mut x_offset = px(0.);
 3346        let mut is_block = true;
 3347
 3348        if let BlockId::Custom(custom_block_id) = block_id {
 3349            if block.has_height() {
 3350                if block.place_near() {
 3351                    if let Some((x_target, line_width)) = x_position {
 3352                        let margin = em_width * 2;
 3353                        if line_width + final_size.width + margin
 3354                            < editor_width + editor_margins.gutter.full_width()
 3355                            && !row_block_types.contains_key(&(row - 1))
 3356                            && element_height_in_lines == 1
 3357                        {
 3358                            x_offset = line_width + margin;
 3359                            row = row - 1;
 3360                            is_block = false;
 3361                            element_height_in_lines = 0;
 3362                            row_block_types.insert(row, is_block);
 3363                        } else {
 3364                            let max_offset = editor_width + editor_margins.gutter.full_width()
 3365                                - final_size.width;
 3366                            let min_offset = (x_target + em_width - final_size.width)
 3367                                .max(editor_margins.gutter.full_width());
 3368                            x_offset = x_target.min(max_offset).max(min_offset);
 3369                        }
 3370                    }
 3371                };
 3372                if element_height_in_lines != block.height() {
 3373                    resized_blocks.insert(custom_block_id, element_height_in_lines);
 3374                }
 3375            }
 3376        }
 3377        for i in 0..element_height_in_lines {
 3378            row_block_types.insert(row + i, is_block);
 3379        }
 3380
 3381        Some((element, final_size, row, x_offset))
 3382    }
 3383
 3384    fn render_buffer_header(
 3385        &self,
 3386        for_excerpt: &ExcerptInfo,
 3387        is_folded: bool,
 3388        is_selected: bool,
 3389        is_sticky: bool,
 3390        jump_data: JumpData,
 3391        window: &mut Window,
 3392        cx: &mut App,
 3393    ) -> Div {
 3394        let editor = self.editor.read(cx);
 3395        let file_status = editor
 3396            .buffer
 3397            .read(cx)
 3398            .all_diff_hunks_expanded()
 3399            .then(|| {
 3400                editor
 3401                    .project
 3402                    .as_ref()?
 3403                    .read(cx)
 3404                    .status_for_buffer_id(for_excerpt.buffer_id, cx)
 3405            })
 3406            .flatten();
 3407
 3408        let include_root = editor
 3409            .project
 3410            .as_ref()
 3411            .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 3412            .unwrap_or_default();
 3413        let can_open_excerpts = Editor::can_open_excerpts_in_file(for_excerpt.buffer.file());
 3414        let path = for_excerpt.buffer.resolve_file_path(cx, include_root);
 3415        let filename = path
 3416            .as_ref()
 3417            .and_then(|path| Some(path.file_name()?.to_string_lossy().to_string()));
 3418        let parent_path = path.as_ref().and_then(|path| {
 3419            Some(path.parent()?.to_string_lossy().to_string() + std::path::MAIN_SEPARATOR_STR)
 3420        });
 3421        let focus_handle = editor.focus_handle(cx);
 3422        let colors = cx.theme().colors();
 3423
 3424        div()
 3425            .p_1()
 3426            .w_full()
 3427            .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
 3428            .child(
 3429                h_flex()
 3430                    .size_full()
 3431                    .gap_2()
 3432                    .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
 3433                    .pl_0p5()
 3434                    .pr_5()
 3435                    .rounded_sm()
 3436                    .when(is_sticky, |el| el.shadow_md())
 3437                    .border_1()
 3438                    .map(|div| {
 3439                        let border_color = if is_selected
 3440                            && is_folded
 3441                            && focus_handle.contains_focused(window, cx)
 3442                        {
 3443                            colors.border_focused
 3444                        } else {
 3445                            colors.border
 3446                        };
 3447                        div.border_color(border_color)
 3448                    })
 3449                    .bg(colors.editor_subheader_background)
 3450                    .hover(|style| style.bg(colors.element_hover))
 3451                    .map(|header| {
 3452                        let editor = self.editor.clone();
 3453                        let buffer_id = for_excerpt.buffer_id;
 3454                        let toggle_chevron_icon =
 3455                            FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
 3456                        header.child(
 3457                            div()
 3458                                .hover(|style| style.bg(colors.element_selected))
 3459                                .rounded_xs()
 3460                                .child(
 3461                                    ButtonLike::new("toggle-buffer-fold")
 3462                                        .style(ui::ButtonStyle::Transparent)
 3463                                        .height(px(28.).into())
 3464                                        .width(px(28.).into())
 3465                                        .children(toggle_chevron_icon)
 3466                                        .tooltip({
 3467                                            let focus_handle = focus_handle.clone();
 3468                                            move |window, cx| {
 3469                                                Tooltip::for_action_in(
 3470                                                    "Toggle Excerpt Fold",
 3471                                                    &ToggleFold,
 3472                                                    &focus_handle,
 3473                                                    window,
 3474                                                    cx,
 3475                                                )
 3476                                            }
 3477                                        })
 3478                                        .on_click(move |_, _, cx| {
 3479                                            if is_folded {
 3480                                                editor.update(cx, |editor, cx| {
 3481                                                    editor.unfold_buffer(buffer_id, cx);
 3482                                                });
 3483                                            } else {
 3484                                                editor.update(cx, |editor, cx| {
 3485                                                    editor.fold_buffer(buffer_id, cx);
 3486                                                });
 3487                                            }
 3488                                        }),
 3489                                ),
 3490                        )
 3491                    })
 3492                    .children(
 3493                        editor
 3494                            .addons
 3495                            .values()
 3496                            .filter_map(|addon| {
 3497                                addon.render_buffer_header_controls(for_excerpt, window, cx)
 3498                            })
 3499                            .take(1),
 3500                    )
 3501                    .child(
 3502                        h_flex()
 3503                            .cursor_pointer()
 3504                            .id("path header block")
 3505                            .size_full()
 3506                            .justify_between()
 3507                            .child(
 3508                                h_flex()
 3509                                    .gap_2()
 3510                                    .child(
 3511                                        Label::new(
 3512                                            filename
 3513                                                .map(SharedString::from)
 3514                                                .unwrap_or_else(|| "untitled".into()),
 3515                                        )
 3516                                        .single_line()
 3517                                        .when_some(
 3518                                            file_status,
 3519                                            |el, status| {
 3520                                                el.color(if status.is_conflicted() {
 3521                                                    Color::Conflict
 3522                                                } else if status.is_modified() {
 3523                                                    Color::Modified
 3524                                                } else if status.is_deleted() {
 3525                                                    Color::Disabled
 3526                                                } else {
 3527                                                    Color::Created
 3528                                                })
 3529                                                .when(status.is_deleted(), |el| el.strikethrough())
 3530                                            },
 3531                                        ),
 3532                                    )
 3533                                    .when_some(parent_path, |then, path| {
 3534                                        then.child(div().child(path).text_color(
 3535                                            if file_status.is_some_and(FileStatus::is_deleted) {
 3536                                                colors.text_disabled
 3537                                            } else {
 3538                                                colors.text_muted
 3539                                            },
 3540                                        ))
 3541                                    }),
 3542                            )
 3543                            .when(can_open_excerpts && is_selected && path.is_some(), |el| {
 3544                                el.child(
 3545                                    h_flex()
 3546                                        .id("jump-to-file-button")
 3547                                        .gap_2p5()
 3548                                        .child(Label::new("Jump To File"))
 3549                                        .children(
 3550                                            KeyBinding::for_action_in(
 3551                                                &OpenExcerpts,
 3552                                                &focus_handle,
 3553                                                window,
 3554                                                cx,
 3555                                            )
 3556                                            .map(|binding| binding.into_any_element()),
 3557                                        ),
 3558                                )
 3559                            })
 3560                            .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 3561                            .on_click(window.listener_for(&self.editor, {
 3562                                move |editor, e: &ClickEvent, window, cx| {
 3563                                    editor.open_excerpts_common(
 3564                                        Some(jump_data.clone()),
 3565                                        e.down.modifiers.secondary(),
 3566                                        window,
 3567                                        cx,
 3568                                    );
 3569                                }
 3570                            })),
 3571                    ),
 3572            )
 3573    }
 3574
 3575    fn render_blocks(
 3576        &self,
 3577        rows: Range<DisplayRow>,
 3578        snapshot: &EditorSnapshot,
 3579        hitbox: &Hitbox,
 3580        text_hitbox: &Hitbox,
 3581        editor_width: Pixels,
 3582        scroll_width: &mut Pixels,
 3583        editor_margins: &EditorMargins,
 3584        em_width: Pixels,
 3585        text_x: Pixels,
 3586        line_height: Pixels,
 3587        line_layouts: &mut [LineWithInvisibles],
 3588        selections: &[Selection<Point>],
 3589        selected_buffer_ids: &Vec<BufferId>,
 3590        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 3591        sticky_header_excerpt_id: Option<ExcerptId>,
 3592        window: &mut Window,
 3593        cx: &mut App,
 3594    ) -> Result<(Vec<BlockLayout>, HashMap<DisplayRow, bool>), HashMap<CustomBlockId, u32>> {
 3595        let (fixed_blocks, non_fixed_blocks) = snapshot
 3596            .blocks_in_range(rows.clone())
 3597            .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
 3598
 3599        let mut focused_block = self
 3600            .editor
 3601            .update(cx, |editor, _| editor.take_focused_block());
 3602        let mut fixed_block_max_width = Pixels::ZERO;
 3603        let mut blocks = Vec::new();
 3604        let mut resized_blocks = HashMap::default();
 3605        let mut row_block_types = HashMap::default();
 3606
 3607        for (row, block) in fixed_blocks {
 3608            let block_id = block.id();
 3609
 3610            if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
 3611                focused_block = None;
 3612            }
 3613
 3614            if let Some((element, element_size, row, x_offset)) = self.render_block(
 3615                block,
 3616                AvailableSpace::MinContent,
 3617                block_id,
 3618                row,
 3619                snapshot,
 3620                text_x,
 3621                &rows,
 3622                line_layouts,
 3623                editor_margins,
 3624                line_height,
 3625                em_width,
 3626                text_hitbox,
 3627                editor_width,
 3628                scroll_width,
 3629                &mut resized_blocks,
 3630                &mut row_block_types,
 3631                selections,
 3632                selected_buffer_ids,
 3633                is_row_soft_wrapped,
 3634                sticky_header_excerpt_id,
 3635                window,
 3636                cx,
 3637            ) {
 3638                fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
 3639                blocks.push(BlockLayout {
 3640                    id: block_id,
 3641                    x_offset,
 3642                    row: Some(row),
 3643                    element,
 3644                    available_space: size(AvailableSpace::MinContent, element_size.height.into()),
 3645                    style: BlockStyle::Fixed,
 3646                    overlaps_gutter: true,
 3647                    is_buffer_header: block.is_buffer_header(),
 3648                });
 3649            }
 3650        }
 3651
 3652        for (row, block) in non_fixed_blocks {
 3653            let style = block.style();
 3654            let width = match (style, block.place_near()) {
 3655                (_, true) => AvailableSpace::MinContent,
 3656                (BlockStyle::Sticky, _) => hitbox.size.width.into(),
 3657                (BlockStyle::Flex, _) => hitbox
 3658                    .size
 3659                    .width
 3660                    .max(fixed_block_max_width)
 3661                    .max(editor_margins.gutter.width + *scroll_width)
 3662                    .into(),
 3663                (BlockStyle::Fixed, _) => unreachable!(),
 3664            };
 3665            let block_id = block.id();
 3666
 3667            if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
 3668                focused_block = None;
 3669            }
 3670
 3671            if let Some((element, element_size, row, x_offset)) = self.render_block(
 3672                block,
 3673                width,
 3674                block_id,
 3675                row,
 3676                snapshot,
 3677                text_x,
 3678                &rows,
 3679                line_layouts,
 3680                editor_margins,
 3681                line_height,
 3682                em_width,
 3683                text_hitbox,
 3684                editor_width,
 3685                scroll_width,
 3686                &mut resized_blocks,
 3687                &mut row_block_types,
 3688                selections,
 3689                selected_buffer_ids,
 3690                is_row_soft_wrapped,
 3691                sticky_header_excerpt_id,
 3692                window,
 3693                cx,
 3694            ) {
 3695                blocks.push(BlockLayout {
 3696                    id: block_id,
 3697                    x_offset,
 3698                    row: Some(row),
 3699                    element,
 3700                    available_space: size(width, element_size.height.into()),
 3701                    style,
 3702                    overlaps_gutter: !block.place_near(),
 3703                    is_buffer_header: block.is_buffer_header(),
 3704                });
 3705            }
 3706        }
 3707
 3708        if let Some(focused_block) = focused_block {
 3709            if let Some(focus_handle) = focused_block.focus_handle.upgrade() {
 3710                if focus_handle.is_focused(window) {
 3711                    if let Some(block) = snapshot.block_for_id(focused_block.id) {
 3712                        let style = block.style();
 3713                        let width = match style {
 3714                            BlockStyle::Fixed => AvailableSpace::MinContent,
 3715                            BlockStyle::Flex => AvailableSpace::Definite(
 3716                                hitbox
 3717                                    .size
 3718                                    .width
 3719                                    .max(fixed_block_max_width)
 3720                                    .max(editor_margins.gutter.width + *scroll_width),
 3721                            ),
 3722                            BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
 3723                        };
 3724
 3725                        if let Some((element, element_size, _, x_offset)) = self.render_block(
 3726                            &block,
 3727                            width,
 3728                            focused_block.id,
 3729                            rows.end,
 3730                            snapshot,
 3731                            text_x,
 3732                            &rows,
 3733                            line_layouts,
 3734                            editor_margins,
 3735                            line_height,
 3736                            em_width,
 3737                            text_hitbox,
 3738                            editor_width,
 3739                            scroll_width,
 3740                            &mut resized_blocks,
 3741                            &mut row_block_types,
 3742                            selections,
 3743                            selected_buffer_ids,
 3744                            is_row_soft_wrapped,
 3745                            sticky_header_excerpt_id,
 3746                            window,
 3747                            cx,
 3748                        ) {
 3749                            blocks.push(BlockLayout {
 3750                                id: block.id(),
 3751                                x_offset,
 3752                                row: None,
 3753                                element,
 3754                                available_space: size(width, element_size.height.into()),
 3755                                style,
 3756                                overlaps_gutter: true,
 3757                                is_buffer_header: block.is_buffer_header(),
 3758                            });
 3759                        }
 3760                    }
 3761                }
 3762            }
 3763        }
 3764
 3765        if resized_blocks.is_empty() {
 3766            *scroll_width =
 3767                (*scroll_width).max(fixed_block_max_width - editor_margins.gutter.width);
 3768            Ok((blocks, row_block_types))
 3769        } else {
 3770            Err(resized_blocks)
 3771        }
 3772    }
 3773
 3774    fn layout_blocks(
 3775        &self,
 3776        blocks: &mut Vec<BlockLayout>,
 3777        hitbox: &Hitbox,
 3778        line_height: Pixels,
 3779        scroll_pixel_position: gpui::Point<Pixels>,
 3780        window: &mut Window,
 3781        cx: &mut App,
 3782    ) {
 3783        for block in blocks {
 3784            let mut origin = if let Some(row) = block.row {
 3785                hitbox.origin
 3786                    + point(
 3787                        block.x_offset,
 3788                        row.as_f32() * line_height - scroll_pixel_position.y,
 3789                    )
 3790            } else {
 3791                // Position the block outside the visible area
 3792                hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
 3793            };
 3794
 3795            if !matches!(block.style, BlockStyle::Sticky) {
 3796                origin += point(-scroll_pixel_position.x, Pixels::ZERO);
 3797            }
 3798
 3799            let focus_handle =
 3800                block
 3801                    .element
 3802                    .prepaint_as_root(origin, block.available_space, window, cx);
 3803
 3804            if let Some(focus_handle) = focus_handle {
 3805                self.editor.update(cx, |editor, _cx| {
 3806                    editor.set_focused_block(FocusedBlock {
 3807                        id: block.id,
 3808                        focus_handle: focus_handle.downgrade(),
 3809                    });
 3810                });
 3811            }
 3812        }
 3813    }
 3814
 3815    fn layout_sticky_buffer_header(
 3816        &self,
 3817        StickyHeaderExcerpt { excerpt }: StickyHeaderExcerpt<'_>,
 3818        scroll_position: f32,
 3819        line_height: Pixels,
 3820        right_margin: Pixels,
 3821        snapshot: &EditorSnapshot,
 3822        hitbox: &Hitbox,
 3823        selected_buffer_ids: &Vec<BufferId>,
 3824        blocks: &[BlockLayout],
 3825        window: &mut Window,
 3826        cx: &mut App,
 3827    ) -> AnyElement {
 3828        let jump_data = header_jump_data(
 3829            snapshot,
 3830            DisplayRow(scroll_position as u32),
 3831            FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 3832            excerpt,
 3833        );
 3834
 3835        let editor_bg_color = cx.theme().colors().editor_background;
 3836
 3837        let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
 3838
 3839        let available_width = hitbox.bounds.size.width - right_margin;
 3840
 3841        let mut header = v_flex()
 3842            .relative()
 3843            .child(
 3844                div()
 3845                    .w(available_width)
 3846                    .h(FILE_HEADER_HEIGHT as f32 * line_height)
 3847                    .bg(linear_gradient(
 3848                        0.,
 3849                        linear_color_stop(editor_bg_color.opacity(0.), 0.),
 3850                        linear_color_stop(editor_bg_color, 0.6),
 3851                    ))
 3852                    .absolute()
 3853                    .top_0(),
 3854            )
 3855            .child(
 3856                self.render_buffer_header(excerpt, false, selected, true, jump_data, window, cx)
 3857                    .into_any_element(),
 3858            )
 3859            .into_any_element();
 3860
 3861        let mut origin = hitbox.origin;
 3862        // Move floating header up to avoid colliding with the next buffer header.
 3863        for block in blocks.iter() {
 3864            if !block.is_buffer_header {
 3865                continue;
 3866            }
 3867
 3868            let Some(display_row) = block.row.filter(|row| row.0 > scroll_position as u32) else {
 3869                continue;
 3870            };
 3871
 3872            let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
 3873            let offset = scroll_position - max_row as f32;
 3874
 3875            if offset > 0.0 {
 3876                origin.y -= offset * line_height;
 3877            }
 3878            break;
 3879        }
 3880
 3881        let size = size(
 3882            AvailableSpace::Definite(available_width),
 3883            AvailableSpace::MinContent,
 3884        );
 3885
 3886        header.prepaint_as_root(origin, size, window, cx);
 3887
 3888        header
 3889    }
 3890
 3891    fn layout_cursor_popovers(
 3892        &self,
 3893        line_height: Pixels,
 3894        text_hitbox: &Hitbox,
 3895        content_origin: gpui::Point<Pixels>,
 3896        right_margin: Pixels,
 3897        start_row: DisplayRow,
 3898        scroll_pixel_position: gpui::Point<Pixels>,
 3899        line_layouts: &[LineWithInvisibles],
 3900        cursor: DisplayPoint,
 3901        cursor_point: Point,
 3902        style: &EditorStyle,
 3903        window: &mut Window,
 3904        cx: &mut App,
 3905    ) -> Option<ContextMenuLayout> {
 3906        let mut min_menu_height = Pixels::ZERO;
 3907        let mut max_menu_height = Pixels::ZERO;
 3908        let mut height_above_menu = Pixels::ZERO;
 3909        let height_below_menu = Pixels::ZERO;
 3910        let mut edit_prediction_popover_visible = false;
 3911        let mut context_menu_visible = false;
 3912        let context_menu_placement;
 3913
 3914        {
 3915            let editor = self.editor.read(cx);
 3916            if editor
 3917                .edit_prediction_visible_in_cursor_popover(editor.has_active_inline_completion())
 3918            {
 3919                height_above_menu +=
 3920                    editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
 3921                edit_prediction_popover_visible = true;
 3922            }
 3923
 3924            if editor.context_menu_visible() {
 3925                if let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin() {
 3926                    let (min_height_in_lines, max_height_in_lines) = editor
 3927                        .context_menu_options
 3928                        .as_ref()
 3929                        .map_or((3, 12), |options| {
 3930                            (options.min_entries_visible, options.max_entries_visible)
 3931                        });
 3932
 3933                    min_menu_height += line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
 3934                    max_menu_height += line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
 3935                    context_menu_visible = true;
 3936                }
 3937            }
 3938            context_menu_placement = editor
 3939                .context_menu_options
 3940                .as_ref()
 3941                .and_then(|options| options.placement.clone());
 3942        }
 3943
 3944        let visible = edit_prediction_popover_visible || context_menu_visible;
 3945        if !visible {
 3946            return None;
 3947        }
 3948
 3949        let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
 3950        let target_position = content_origin
 3951            + gpui::Point {
 3952                x: cmp::max(
 3953                    px(0.),
 3954                    cursor_row_layout.x_for_index(cursor.column() as usize)
 3955                        - scroll_pixel_position.x,
 3956                ),
 3957                y: cmp::max(
 3958                    px(0.),
 3959                    cursor.row().next_row().as_f32() * line_height - scroll_pixel_position.y,
 3960                ),
 3961            };
 3962
 3963        let viewport_bounds =
 3964            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 3965                right: -right_margin - MENU_GAP,
 3966                ..Default::default()
 3967            });
 3968
 3969        let min_height = height_above_menu + min_menu_height + height_below_menu;
 3970        let max_height = height_above_menu + max_menu_height + height_below_menu;
 3971        let (laid_out_popovers, y_flipped) = self.layout_popovers_above_or_below_line(
 3972            target_position,
 3973            line_height,
 3974            min_height,
 3975            max_height,
 3976            context_menu_placement,
 3977            text_hitbox,
 3978            viewport_bounds,
 3979            window,
 3980            cx,
 3981            |height, max_width_for_stable_x, y_flipped, window, cx| {
 3982                // First layout the menu to get its size - others can be at least this wide.
 3983                let context_menu = if context_menu_visible {
 3984                    let menu_height = if y_flipped {
 3985                        height - height_below_menu
 3986                    } else {
 3987                        height - height_above_menu
 3988                    };
 3989                    let mut element = self
 3990                        .render_context_menu(line_height, menu_height, window, cx)
 3991                        .expect("Visible context menu should always render.");
 3992                    let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 3993                    Some((CursorPopoverType::CodeContextMenu, element, size))
 3994                } else {
 3995                    None
 3996                };
 3997                let min_width = context_menu
 3998                    .as_ref()
 3999                    .map_or(px(0.), |(_, _, size)| size.width);
 4000                let max_width = max_width_for_stable_x.max(
 4001                    context_menu
 4002                        .as_ref()
 4003                        .map_or(px(0.), |(_, _, size)| size.width),
 4004                );
 4005
 4006                let edit_prediction = if edit_prediction_popover_visible {
 4007                    self.editor.update(cx, move |editor, cx| {
 4008                        let accept_binding =
 4009                            editor.accept_edit_prediction_keybind(false, window, cx);
 4010                        let mut element = editor.render_edit_prediction_cursor_popover(
 4011                            min_width,
 4012                            max_width,
 4013                            cursor_point,
 4014                            style,
 4015                            accept_binding.keystroke(),
 4016                            window,
 4017                            cx,
 4018                        )?;
 4019                        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 4020                        Some((CursorPopoverType::EditPrediction, element, size))
 4021                    })
 4022                } else {
 4023                    None
 4024                };
 4025                vec![edit_prediction, context_menu]
 4026                    .into_iter()
 4027                    .flatten()
 4028                    .collect::<Vec<_>>()
 4029            },
 4030        )?;
 4031
 4032        let (menu_ix, (_, menu_bounds)) = laid_out_popovers
 4033            .iter()
 4034            .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))?;
 4035        let last_ix = laid_out_popovers.len() - 1;
 4036        let menu_is_last = menu_ix == last_ix;
 4037        let first_popover_bounds = laid_out_popovers[0].1;
 4038        let last_popover_bounds = laid_out_popovers[last_ix].1;
 4039
 4040        // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
 4041        // right, and otherwise it goes below or to the right.
 4042        let mut target_bounds = Bounds::from_corners(
 4043            first_popover_bounds.origin,
 4044            last_popover_bounds.bottom_right(),
 4045        );
 4046        target_bounds.size.width = menu_bounds.size.width;
 4047
 4048        // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
 4049        // based on this is preferred for layout stability.
 4050        let mut max_target_bounds = target_bounds;
 4051        max_target_bounds.size.height = max_height;
 4052        if y_flipped {
 4053            max_target_bounds.origin.y -= max_height - target_bounds.size.height;
 4054        }
 4055
 4056        // Add spacing around `target_bounds` and `max_target_bounds`.
 4057        let mut extend_amount = Edges::all(MENU_GAP);
 4058        if y_flipped {
 4059            extend_amount.bottom = line_height;
 4060        } else {
 4061            extend_amount.top = line_height;
 4062        }
 4063        let target_bounds = target_bounds.extend(extend_amount);
 4064        let max_target_bounds = max_target_bounds.extend(extend_amount);
 4065
 4066        let must_place_above_or_below =
 4067            if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
 4068                laid_out_popovers[menu_ix + 1..]
 4069                    .iter()
 4070                    .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
 4071            } else {
 4072                false
 4073            };
 4074
 4075        let aside_bounds = self.layout_context_menu_aside(
 4076            y_flipped,
 4077            *menu_bounds,
 4078            target_bounds,
 4079            max_target_bounds,
 4080            max_menu_height,
 4081            must_place_above_or_below,
 4082            text_hitbox,
 4083            viewport_bounds,
 4084            window,
 4085            cx,
 4086        );
 4087
 4088        if let Some(menu_bounds) = laid_out_popovers.iter().find_map(|(popover_type, bounds)| {
 4089            if matches!(popover_type, CursorPopoverType::CodeContextMenu) {
 4090                Some(*bounds)
 4091            } else {
 4092                None
 4093            }
 4094        }) {
 4095            let bounds = if let Some(aside_bounds) = aside_bounds {
 4096                menu_bounds.union(&aside_bounds)
 4097            } else {
 4098                menu_bounds
 4099            };
 4100            return Some(ContextMenuLayout { y_flipped, bounds });
 4101        }
 4102
 4103        None
 4104    }
 4105
 4106    fn layout_gutter_menu(
 4107        &self,
 4108        line_height: Pixels,
 4109        text_hitbox: &Hitbox,
 4110        content_origin: gpui::Point<Pixels>,
 4111        right_margin: Pixels,
 4112        scroll_pixel_position: gpui::Point<Pixels>,
 4113        gutter_overshoot: Pixels,
 4114        window: &mut Window,
 4115        cx: &mut App,
 4116    ) {
 4117        let editor = self.editor.read(cx);
 4118        if !editor.context_menu_visible() {
 4119            return;
 4120        }
 4121        let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
 4122            editor.context_menu_origin()
 4123        else {
 4124            return;
 4125        };
 4126        // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
 4127        // indicator than just a plain first column of the text field.
 4128        let target_position = content_origin
 4129            + gpui::Point {
 4130                x: -gutter_overshoot,
 4131                y: gutter_row.next_row().as_f32() * line_height - scroll_pixel_position.y,
 4132            };
 4133
 4134        let (min_height_in_lines, max_height_in_lines) = editor
 4135            .context_menu_options
 4136            .as_ref()
 4137            .map_or((3, 12), |options| {
 4138                (options.min_entries_visible, options.max_entries_visible)
 4139            });
 4140
 4141        let min_height = line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
 4142        let max_height = line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
 4143        let viewport_bounds =
 4144            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 4145                right: -right_margin - MENU_GAP,
 4146                ..Default::default()
 4147            });
 4148        self.layout_popovers_above_or_below_line(
 4149            target_position,
 4150            line_height,
 4151            min_height,
 4152            max_height,
 4153            editor
 4154                .context_menu_options
 4155                .as_ref()
 4156                .and_then(|options| options.placement.clone()),
 4157            text_hitbox,
 4158            viewport_bounds,
 4159            window,
 4160            cx,
 4161            move |height, _max_width_for_stable_x, _, window, cx| {
 4162                let mut element = self
 4163                    .render_context_menu(line_height, height, window, cx)
 4164                    .expect("Visible context menu should always render.");
 4165                let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 4166                vec![(CursorPopoverType::CodeContextMenu, element, size)]
 4167            },
 4168        );
 4169    }
 4170
 4171    fn layout_popovers_above_or_below_line(
 4172        &self,
 4173        target_position: gpui::Point<Pixels>,
 4174        line_height: Pixels,
 4175        min_height: Pixels,
 4176        max_height: Pixels,
 4177        placement: Option<ContextMenuPlacement>,
 4178        text_hitbox: &Hitbox,
 4179        viewport_bounds: Bounds<Pixels>,
 4180        window: &mut Window,
 4181        cx: &mut App,
 4182        make_sized_popovers: impl FnOnce(
 4183            Pixels,
 4184            Pixels,
 4185            bool,
 4186            &mut Window,
 4187            &mut App,
 4188        ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
 4189    ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
 4190        let text_style = TextStyleRefinement {
 4191            line_height: Some(DefiniteLength::Fraction(
 4192                BufferLineHeight::Comfortable.value(),
 4193            )),
 4194            ..Default::default()
 4195        };
 4196        window.with_text_style(Some(text_style), |window| {
 4197            // If the max height won't fit below and there is more space above, put it above the line.
 4198            let bottom_y_when_flipped = target_position.y - line_height;
 4199            let available_above = bottom_y_when_flipped - text_hitbox.top();
 4200            let available_below = text_hitbox.bottom() - target_position.y;
 4201            let y_overflows_below = max_height > available_below;
 4202            let mut y_flipped = match placement {
 4203                Some(ContextMenuPlacement::Above) => true,
 4204                Some(ContextMenuPlacement::Below) => false,
 4205                None => y_overflows_below && available_above > available_below,
 4206            };
 4207            let mut height = cmp::min(
 4208                max_height,
 4209                if y_flipped {
 4210                    available_above
 4211                } else {
 4212                    available_below
 4213                },
 4214            );
 4215
 4216            // If the min height doesn't fit within text bounds, instead fit within the window.
 4217            if height < min_height {
 4218                let available_above = bottom_y_when_flipped;
 4219                let available_below = viewport_bounds.bottom() - target_position.y;
 4220                let (y_flipped_override, height_override) = match placement {
 4221                    Some(ContextMenuPlacement::Above) => {
 4222                        (true, cmp::min(available_above, min_height))
 4223                    }
 4224                    Some(ContextMenuPlacement::Below) => {
 4225                        (false, cmp::min(available_below, min_height))
 4226                    }
 4227                    None => {
 4228                        if available_below > min_height {
 4229                            (false, min_height)
 4230                        } else if available_above > min_height {
 4231                            (true, min_height)
 4232                        } else if available_above > available_below {
 4233                            (true, available_above)
 4234                        } else {
 4235                            (false, available_below)
 4236                        }
 4237                    }
 4238                };
 4239                y_flipped = y_flipped_override;
 4240                height = height_override;
 4241            }
 4242
 4243            let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
 4244
 4245            // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
 4246            // for very narrow windows.
 4247            let popovers =
 4248                make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
 4249            if popovers.is_empty() {
 4250                return None;
 4251            }
 4252
 4253            let max_width = popovers
 4254                .iter()
 4255                .map(|(_, _, size)| size.width)
 4256                .max()
 4257                .unwrap_or_default();
 4258
 4259            let mut current_position = gpui::Point {
 4260                // Snap the right edge of the list to the right edge of the window if its horizontal bounds
 4261                // overflow. Include space for the scrollbar.
 4262                x: target_position
 4263                    .x
 4264                    .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
 4265                y: if y_flipped {
 4266                    bottom_y_when_flipped
 4267                } else {
 4268                    target_position.y
 4269                },
 4270            };
 4271
 4272            let mut laid_out_popovers = popovers
 4273                .into_iter()
 4274                .map(|(popover_type, element, size)| {
 4275                    if y_flipped {
 4276                        current_position.y -= size.height;
 4277                    }
 4278                    let position = current_position;
 4279                    window.defer_draw(element, current_position, 1);
 4280                    if !y_flipped {
 4281                        current_position.y += size.height + MENU_GAP;
 4282                    } else {
 4283                        current_position.y -= MENU_GAP;
 4284                    }
 4285                    (popover_type, Bounds::new(position, size))
 4286                })
 4287                .collect::<Vec<_>>();
 4288
 4289            if y_flipped {
 4290                laid_out_popovers.reverse();
 4291            }
 4292
 4293            Some((laid_out_popovers, y_flipped))
 4294        })
 4295    }
 4296
 4297    fn layout_context_menu_aside(
 4298        &self,
 4299        y_flipped: bool,
 4300        menu_bounds: Bounds<Pixels>,
 4301        target_bounds: Bounds<Pixels>,
 4302        max_target_bounds: Bounds<Pixels>,
 4303        max_height: Pixels,
 4304        must_place_above_or_below: bool,
 4305        text_hitbox: &Hitbox,
 4306        viewport_bounds: Bounds<Pixels>,
 4307        window: &mut Window,
 4308        cx: &mut App,
 4309    ) -> Option<Bounds<Pixels>> {
 4310        let available_within_viewport = target_bounds.space_within(&viewport_bounds);
 4311        let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
 4312            && !must_place_above_or_below
 4313        {
 4314            let max_width = cmp::min(
 4315                available_within_viewport.right - px(1.),
 4316                MENU_ASIDE_MAX_WIDTH,
 4317            );
 4318            let mut aside = self.render_context_menu_aside(
 4319                size(max_width, max_height - POPOVER_Y_PADDING),
 4320                window,
 4321                cx,
 4322            )?;
 4323            let size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
 4324            let right_position = point(target_bounds.right(), menu_bounds.origin.y);
 4325            Some((aside, right_position, size))
 4326        } else {
 4327            let max_size = size(
 4328                // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
 4329                // won't be needed here.
 4330                cmp::min(
 4331                    cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
 4332                    viewport_bounds.right(),
 4333                ),
 4334                cmp::min(
 4335                    max_height,
 4336                    cmp::max(
 4337                        available_within_viewport.top,
 4338                        available_within_viewport.bottom,
 4339                    ),
 4340                ) - POPOVER_Y_PADDING,
 4341            );
 4342            let mut aside = self.render_context_menu_aside(max_size, window, cx)?;
 4343            let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
 4344
 4345            let top_position = point(
 4346                menu_bounds.origin.x,
 4347                target_bounds.top() - actual_size.height,
 4348            );
 4349            let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
 4350
 4351            let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
 4352                // Prefer to fit on the same side of the line as the menu, then on the other side of
 4353                // the line.
 4354                if !y_flipped && wanted.height < available.bottom {
 4355                    Some(bottom_position)
 4356                } else if !y_flipped && wanted.height < available.top {
 4357                    Some(top_position)
 4358                } else if y_flipped && wanted.height < available.top {
 4359                    Some(top_position)
 4360                } else if y_flipped && wanted.height < available.bottom {
 4361                    Some(bottom_position)
 4362                } else {
 4363                    None
 4364                }
 4365            };
 4366
 4367            // Prefer choosing a direction using max sizes rather than actual size for stability.
 4368            let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
 4369            let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
 4370            let aside_position = fit_within(available_within_text, wanted)
 4371                // Fallback: fit max size in window.
 4372                .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
 4373                // Fallback: fit actual size in window.
 4374                .or_else(|| fit_within(available_within_viewport, actual_size));
 4375
 4376            aside_position.map(|position| (aside, position, actual_size))
 4377        };
 4378
 4379        // Skip drawing if it doesn't fit anywhere.
 4380        if let Some((aside, position, size)) = positioned_aside {
 4381            let aside_bounds = Bounds::new(position, size);
 4382            window.defer_draw(aside, position, 2);
 4383            return Some(aside_bounds);
 4384        }
 4385
 4386        None
 4387    }
 4388
 4389    fn render_context_menu(
 4390        &self,
 4391        line_height: Pixels,
 4392        height: Pixels,
 4393        window: &mut Window,
 4394        cx: &mut App,
 4395    ) -> Option<AnyElement> {
 4396        let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
 4397        self.editor.update(cx, |editor, cx| {
 4398            editor.render_context_menu(&self.style, max_height_in_lines, window, cx)
 4399        })
 4400    }
 4401
 4402    fn render_context_menu_aside(
 4403        &self,
 4404        max_size: Size<Pixels>,
 4405        window: &mut Window,
 4406        cx: &mut App,
 4407    ) -> Option<AnyElement> {
 4408        if max_size.width < px(100.) || max_size.height < px(12.) {
 4409            None
 4410        } else {
 4411            self.editor.update(cx, |editor, cx| {
 4412                editor.render_context_menu_aside(max_size, window, cx)
 4413            })
 4414        }
 4415    }
 4416
 4417    fn layout_mouse_context_menu(
 4418        &self,
 4419        editor_snapshot: &EditorSnapshot,
 4420        visible_range: Range<DisplayRow>,
 4421        content_origin: gpui::Point<Pixels>,
 4422        window: &mut Window,
 4423        cx: &mut App,
 4424    ) -> Option<AnyElement> {
 4425        let position = self.editor.update(cx, |editor, _cx| {
 4426            let visible_start_point = editor.display_to_pixel_point(
 4427                DisplayPoint::new(visible_range.start, 0),
 4428                editor_snapshot,
 4429                window,
 4430            )?;
 4431            let visible_end_point = editor.display_to_pixel_point(
 4432                DisplayPoint::new(visible_range.end, 0),
 4433                editor_snapshot,
 4434                window,
 4435            )?;
 4436
 4437            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
 4438            let (source_display_point, position) = match mouse_context_menu.position {
 4439                MenuPosition::PinnedToScreen(point) => (None, point),
 4440                MenuPosition::PinnedToEditor { source, offset } => {
 4441                    let source_display_point = source.to_display_point(editor_snapshot);
 4442                    let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
 4443                    let position = content_origin + source_point + offset;
 4444                    (Some(source_display_point), position)
 4445                }
 4446            };
 4447
 4448            let source_included = source_display_point.map_or(true, |source_display_point| {
 4449                visible_range
 4450                    .to_inclusive()
 4451                    .contains(&source_display_point.row())
 4452            });
 4453            let position_included =
 4454                visible_start_point.y <= position.y && position.y <= visible_end_point.y;
 4455            if !source_included && !position_included {
 4456                None
 4457            } else {
 4458                Some(position)
 4459            }
 4460        })?;
 4461
 4462        let text_style = TextStyleRefinement {
 4463            line_height: Some(DefiniteLength::Fraction(
 4464                BufferLineHeight::Comfortable.value(),
 4465            )),
 4466            ..Default::default()
 4467        };
 4468        window.with_text_style(Some(text_style), |window| {
 4469            let mut element = self.editor.read_with(cx, |editor, _| {
 4470                let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
 4471                let context_menu = mouse_context_menu.context_menu.clone();
 4472
 4473                Some(
 4474                    deferred(
 4475                        anchored()
 4476                            .position(position)
 4477                            .child(context_menu)
 4478                            .anchor(Corner::TopLeft)
 4479                            .snap_to_window_with_margin(px(8.)),
 4480                    )
 4481                    .with_priority(1)
 4482                    .into_any(),
 4483                )
 4484            })?;
 4485
 4486            element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
 4487            Some(element)
 4488        })
 4489    }
 4490
 4491    fn layout_hover_popovers(
 4492        &self,
 4493        snapshot: &EditorSnapshot,
 4494        hitbox: &Hitbox,
 4495        visible_display_row_range: Range<DisplayRow>,
 4496        content_origin: gpui::Point<Pixels>,
 4497        scroll_pixel_position: gpui::Point<Pixels>,
 4498        line_layouts: &[LineWithInvisibles],
 4499        line_height: Pixels,
 4500        em_width: Pixels,
 4501        context_menu_layout: Option<ContextMenuLayout>,
 4502        window: &mut Window,
 4503        cx: &mut App,
 4504    ) {
 4505        struct MeasuredHoverPopover {
 4506            element: AnyElement,
 4507            size: Size<Pixels>,
 4508            horizontal_offset: Pixels,
 4509        }
 4510
 4511        let max_size = size(
 4512            (120. * em_width) // Default size
 4513                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
 4514                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
 4515            (16. * line_height) // Default size
 4516                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
 4517                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
 4518        );
 4519
 4520        let hover_popovers = self.editor.update(cx, |editor, cx| {
 4521            editor.hover_state.render(
 4522                snapshot,
 4523                visible_display_row_range.clone(),
 4524                max_size,
 4525                window,
 4526                cx,
 4527            )
 4528        });
 4529        let Some((position, hover_popovers)) = hover_popovers else {
 4530            return;
 4531        };
 4532
 4533        // This is safe because we check on layout whether the required row is available
 4534        let hovered_row_layout =
 4535            &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
 4536
 4537        // Compute Hovered Point
 4538        let x =
 4539            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
 4540        let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
 4541        let hovered_point = content_origin + point(x, y);
 4542
 4543        let mut overall_height = Pixels::ZERO;
 4544        let mut measured_hover_popovers = Vec::new();
 4545        for (position, mut hover_popover) in hover_popovers.into_iter().with_position() {
 4546            let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
 4547            let horizontal_offset =
 4548                (hitbox.top_right().x - POPOVER_RIGHT_OFFSET - (hovered_point.x + size.width))
 4549                    .min(Pixels::ZERO);
 4550            match position {
 4551                itertools::Position::Middle | itertools::Position::Last => {
 4552                    overall_height += HOVER_POPOVER_GAP
 4553                }
 4554                _ => {}
 4555            }
 4556            overall_height += size.height;
 4557            measured_hover_popovers.push(MeasuredHoverPopover {
 4558                element: hover_popover,
 4559                size,
 4560                horizontal_offset,
 4561            });
 4562        }
 4563
 4564        fn draw_occluder(
 4565            width: Pixels,
 4566            origin: gpui::Point<Pixels>,
 4567            window: &mut Window,
 4568            cx: &mut App,
 4569        ) {
 4570            let mut occlusion = div()
 4571                .size_full()
 4572                .occlude()
 4573                .on_mouse_move(|_, _, cx| cx.stop_propagation())
 4574                .into_any_element();
 4575            occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
 4576            window.defer_draw(occlusion, origin, 2);
 4577        }
 4578
 4579        fn place_popovers_above(
 4580            hovered_point: gpui::Point<Pixels>,
 4581            measured_hover_popovers: Vec<MeasuredHoverPopover>,
 4582            window: &mut Window,
 4583            cx: &mut App,
 4584        ) {
 4585            let mut current_y = hovered_point.y;
 4586            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 4587                let size = popover.size;
 4588                let popover_origin = point(
 4589                    hovered_point.x + popover.horizontal_offset,
 4590                    current_y - size.height,
 4591                );
 4592
 4593                window.defer_draw(popover.element, popover_origin, 2);
 4594                if position != itertools::Position::Last {
 4595                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
 4596                    draw_occluder(size.width, origin, window, cx);
 4597                }
 4598
 4599                current_y = popover_origin.y - HOVER_POPOVER_GAP;
 4600            }
 4601        }
 4602
 4603        fn place_popovers_below(
 4604            hovered_point: gpui::Point<Pixels>,
 4605            measured_hover_popovers: Vec<MeasuredHoverPopover>,
 4606            line_height: Pixels,
 4607            window: &mut Window,
 4608            cx: &mut App,
 4609        ) {
 4610            let mut current_y = hovered_point.y + line_height;
 4611            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 4612                let size = popover.size;
 4613                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
 4614
 4615                window.defer_draw(popover.element, popover_origin, 2);
 4616                if position != itertools::Position::Last {
 4617                    let origin = point(popover_origin.x, popover_origin.y + size.height);
 4618                    draw_occluder(size.width, origin, window, cx);
 4619                }
 4620
 4621                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 4622            }
 4623        }
 4624
 4625        let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
 4626            context_menu_layout
 4627                .as_ref()
 4628                .map_or(false, |menu| bounds.intersects(&menu.bounds))
 4629        };
 4630
 4631        let can_place_above = {
 4632            let mut bounds_above = Vec::new();
 4633            let mut current_y = hovered_point.y;
 4634            for popover in &measured_hover_popovers {
 4635                let size = popover.size;
 4636                let popover_origin = point(
 4637                    hovered_point.x + popover.horizontal_offset,
 4638                    current_y - size.height,
 4639                );
 4640                bounds_above.push(Bounds::new(popover_origin, size));
 4641                current_y = popover_origin.y - HOVER_POPOVER_GAP;
 4642            }
 4643            bounds_above
 4644                .iter()
 4645                .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
 4646        };
 4647
 4648        let can_place_below = || {
 4649            let mut bounds_below = Vec::new();
 4650            let mut current_y = hovered_point.y + line_height;
 4651            for popover in &measured_hover_popovers {
 4652                let size = popover.size;
 4653                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
 4654                bounds_below.push(Bounds::new(popover_origin, size));
 4655                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 4656            }
 4657            bounds_below
 4658                .iter()
 4659                .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
 4660        };
 4661
 4662        if can_place_above {
 4663            // try placing above hovered point
 4664            place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
 4665        } else if can_place_below() {
 4666            // try placing below hovered point
 4667            place_popovers_below(
 4668                hovered_point,
 4669                measured_hover_popovers,
 4670                line_height,
 4671                window,
 4672                cx,
 4673            );
 4674        } else {
 4675            // try to place popovers around the context menu
 4676            let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
 4677                let total_width = measured_hover_popovers
 4678                    .iter()
 4679                    .map(|p| p.size.width)
 4680                    .max()
 4681                    .unwrap_or(Pixels::ZERO);
 4682                let y_for_horizontal_positioning = if menu.y_flipped {
 4683                    menu.bounds.bottom() - overall_height
 4684                } else {
 4685                    menu.bounds.top()
 4686                };
 4687                let possible_origins = vec![
 4688                    // left of context menu
 4689                    point(
 4690                        menu.bounds.left() - total_width - HOVER_POPOVER_GAP,
 4691                        y_for_horizontal_positioning,
 4692                    ),
 4693                    // right of context menu
 4694                    point(
 4695                        menu.bounds.right() + HOVER_POPOVER_GAP,
 4696                        y_for_horizontal_positioning,
 4697                    ),
 4698                    // top of context menu
 4699                    point(
 4700                        menu.bounds.left(),
 4701                        menu.bounds.top() - overall_height - HOVER_POPOVER_GAP,
 4702                    ),
 4703                    // bottom of context menu
 4704                    point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
 4705                ];
 4706                possible_origins.into_iter().find(|&origin| {
 4707                    Bounds::new(origin, size(total_width, overall_height))
 4708                        .is_contained_within(hitbox)
 4709                })
 4710            });
 4711            if let Some(origin) = origin_surrounding_menu {
 4712                let mut current_y = origin.y;
 4713                for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 4714                    let size = popover.size;
 4715                    let popover_origin = point(origin.x, current_y);
 4716
 4717                    window.defer_draw(popover.element, popover_origin, 2);
 4718                    if position != itertools::Position::Last {
 4719                        let origin = point(popover_origin.x, popover_origin.y + size.height);
 4720                        draw_occluder(size.width, origin, window, cx);
 4721                    }
 4722
 4723                    current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 4724                }
 4725            } else {
 4726                // fallback to existing above/below cursor logic
 4727                // this might overlap menu or overflow in rare case
 4728                if can_place_above {
 4729                    place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
 4730                } else {
 4731                    place_popovers_below(
 4732                        hovered_point,
 4733                        measured_hover_popovers,
 4734                        line_height,
 4735                        window,
 4736                        cx,
 4737                    );
 4738                }
 4739            }
 4740        }
 4741    }
 4742
 4743    fn layout_diff_hunk_controls(
 4744        &self,
 4745        row_range: Range<DisplayRow>,
 4746        row_infos: &[RowInfo],
 4747        text_hitbox: &Hitbox,
 4748        position_map: &PositionMap,
 4749        newest_cursor_position: Option<DisplayPoint>,
 4750        line_height: Pixels,
 4751        right_margin: Pixels,
 4752        scroll_pixel_position: gpui::Point<Pixels>,
 4753        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 4754        highlighted_rows: &BTreeMap<DisplayRow, LineHighlight>,
 4755        editor: Entity<Editor>,
 4756        window: &mut Window,
 4757        cx: &mut App,
 4758    ) -> Vec<AnyElement> {
 4759        let render_diff_hunk_controls = editor.read(cx).render_diff_hunk_controls.clone();
 4760        let point_for_position = position_map.point_for_position(window.mouse_position());
 4761
 4762        let mut controls = vec![];
 4763
 4764        let active_positions = [
 4765            Some(point_for_position.previous_valid),
 4766            newest_cursor_position,
 4767        ];
 4768
 4769        for (hunk, _) in display_hunks {
 4770            if let DisplayDiffHunk::Unfolded {
 4771                display_row_range,
 4772                multi_buffer_range,
 4773                status,
 4774                is_created_file,
 4775                ..
 4776            } = &hunk
 4777            {
 4778                if display_row_range.start < row_range.start
 4779                    || display_row_range.start >= row_range.end
 4780                {
 4781                    continue;
 4782                }
 4783                if highlighted_rows
 4784                    .get(&display_row_range.start)
 4785                    .and_then(|highlight| highlight.type_id)
 4786                    .is_some_and(|type_id| {
 4787                        [
 4788                            TypeId::of::<ConflictsOuter>(),
 4789                            TypeId::of::<ConflictsOursMarker>(),
 4790                            TypeId::of::<ConflictsOurs>(),
 4791                            TypeId::of::<ConflictsTheirs>(),
 4792                            TypeId::of::<ConflictsTheirsMarker>(),
 4793                        ]
 4794                        .contains(&type_id)
 4795                    })
 4796                {
 4797                    continue;
 4798                }
 4799                let row_ix = (display_row_range.start - row_range.start).0 as usize;
 4800                if row_infos[row_ix].diff_status.is_none() {
 4801                    continue;
 4802                }
 4803                if row_infos[row_ix]
 4804                    .diff_status
 4805                    .is_some_and(|status| status.is_added())
 4806                    && !status.is_added()
 4807                {
 4808                    continue;
 4809                }
 4810                if active_positions
 4811                    .iter()
 4812                    .any(|p| p.map_or(false, |p| display_row_range.contains(&p.row())))
 4813                {
 4814                    let y = display_row_range.start.as_f32() * line_height
 4815                        + text_hitbox.bounds.top()
 4816                        - scroll_pixel_position.y;
 4817
 4818                    let mut element = render_diff_hunk_controls(
 4819                        display_row_range.start.0,
 4820                        status,
 4821                        multi_buffer_range.clone(),
 4822                        *is_created_file,
 4823                        line_height,
 4824                        &editor,
 4825                        window,
 4826                        cx,
 4827                    );
 4828                    let size =
 4829                        element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
 4830
 4831                    let x = text_hitbox.bounds.right() - right_margin - px(10.) - size.width;
 4832
 4833                    window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
 4834                        element.prepaint(window, cx)
 4835                    });
 4836                    controls.push(element);
 4837                }
 4838            }
 4839        }
 4840
 4841        controls
 4842    }
 4843
 4844    fn layout_signature_help(
 4845        &self,
 4846        hitbox: &Hitbox,
 4847        content_origin: gpui::Point<Pixels>,
 4848        scroll_pixel_position: gpui::Point<Pixels>,
 4849        newest_selection_head: Option<DisplayPoint>,
 4850        start_row: DisplayRow,
 4851        line_layouts: &[LineWithInvisibles],
 4852        line_height: Pixels,
 4853        em_width: Pixels,
 4854        context_menu_layout: Option<ContextMenuLayout>,
 4855        window: &mut Window,
 4856        cx: &mut App,
 4857    ) {
 4858        if !self.editor.focus_handle(cx).is_focused(window) {
 4859            return;
 4860        }
 4861        let Some(newest_selection_head) = newest_selection_head else {
 4862            return;
 4863        };
 4864
 4865        let max_size = size(
 4866            (120. * em_width) // Default size
 4867                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
 4868                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
 4869            (16. * line_height) // Default size
 4870                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
 4871                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
 4872        );
 4873
 4874        let maybe_element = self.editor.update(cx, |editor, cx| {
 4875            if let Some(popover) = editor.signature_help_state.popover_mut() {
 4876                let element = popover.render(max_size, cx);
 4877                Some(element)
 4878            } else {
 4879                None
 4880            }
 4881        });
 4882        let Some(mut element) = maybe_element else {
 4883            return;
 4884        };
 4885
 4886        let selection_row = newest_selection_head.row();
 4887        let Some(cursor_row_layout) = (selection_row >= start_row)
 4888            .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
 4889            .flatten()
 4890        else {
 4891            return;
 4892        };
 4893
 4894        let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
 4895            - scroll_pixel_position.x;
 4896        let target_y = selection_row.as_f32() * line_height - scroll_pixel_position.y;
 4897        let target_point = content_origin + point(target_x, target_y);
 4898
 4899        let actual_size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
 4900
 4901        let (popover_bounds_above, popover_bounds_below) = {
 4902            let horizontal_offset = (hitbox.top_right().x
 4903                - POPOVER_RIGHT_OFFSET
 4904                - (target_point.x + actual_size.width))
 4905                .min(Pixels::ZERO);
 4906            let initial_x = target_point.x + horizontal_offset;
 4907            (
 4908                Bounds::new(
 4909                    point(initial_x, target_point.y - actual_size.height),
 4910                    actual_size,
 4911                ),
 4912                Bounds::new(
 4913                    point(initial_x, target_point.y + line_height + HOVER_POPOVER_GAP),
 4914                    actual_size,
 4915                ),
 4916            )
 4917        };
 4918
 4919        let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
 4920            context_menu_layout
 4921                .as_ref()
 4922                .map_or(false, |menu| bounds.intersects(&menu.bounds))
 4923        };
 4924
 4925        let final_origin = if popover_bounds_above.is_contained_within(hitbox)
 4926            && !intersects_menu(popover_bounds_above)
 4927        {
 4928            // try placing above cursor
 4929            popover_bounds_above.origin
 4930        } else if popover_bounds_below.is_contained_within(hitbox)
 4931            && !intersects_menu(popover_bounds_below)
 4932        {
 4933            // try placing below cursor
 4934            popover_bounds_below.origin
 4935        } else {
 4936            // try surrounding context menu if exists
 4937            let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
 4938                let y_for_horizontal_positioning = if menu.y_flipped {
 4939                    menu.bounds.bottom() - actual_size.height
 4940                } else {
 4941                    menu.bounds.top()
 4942                };
 4943                let possible_origins = vec![
 4944                    // left of context menu
 4945                    point(
 4946                        menu.bounds.left() - actual_size.width - HOVER_POPOVER_GAP,
 4947                        y_for_horizontal_positioning,
 4948                    ),
 4949                    // right of context menu
 4950                    point(
 4951                        menu.bounds.right() + HOVER_POPOVER_GAP,
 4952                        y_for_horizontal_positioning,
 4953                    ),
 4954                    // top of context menu
 4955                    point(
 4956                        menu.bounds.left(),
 4957                        menu.bounds.top() - actual_size.height - HOVER_POPOVER_GAP,
 4958                    ),
 4959                    // bottom of context menu
 4960                    point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
 4961                ];
 4962                possible_origins
 4963                    .into_iter()
 4964                    .find(|&origin| Bounds::new(origin, actual_size).is_contained_within(hitbox))
 4965            });
 4966            origin_surrounding_menu.unwrap_or_else(|| {
 4967                // fallback to existing above/below cursor logic
 4968                // this might overlap menu or overflow in rare case
 4969                if popover_bounds_above.is_contained_within(hitbox) {
 4970                    popover_bounds_above.origin
 4971                } else {
 4972                    popover_bounds_below.origin
 4973                }
 4974            })
 4975        };
 4976
 4977        window.defer_draw(element, final_origin, 2);
 4978    }
 4979
 4980    fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
 4981        window.paint_layer(layout.hitbox.bounds, |window| {
 4982            let scroll_top = layout.position_map.snapshot.scroll_position().y;
 4983            let gutter_bg = cx.theme().colors().editor_gutter_background;
 4984            window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
 4985            window.paint_quad(fill(
 4986                layout.position_map.text_hitbox.bounds,
 4987                self.style.background,
 4988            ));
 4989
 4990            if matches!(
 4991                layout.mode,
 4992                EditorMode::Full { .. } | EditorMode::Minimap { .. }
 4993            ) {
 4994                let show_active_line_background = match layout.mode {
 4995                    EditorMode::Full {
 4996                        show_active_line_background,
 4997                        ..
 4998                    } => show_active_line_background,
 4999                    EditorMode::Minimap { .. } => true,
 5000                    _ => false,
 5001                };
 5002                let mut active_rows = layout.active_rows.iter().peekable();
 5003                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
 5004                    let mut end_row = start_row.0;
 5005                    while active_rows
 5006                        .peek()
 5007                        .map_or(false, |(active_row, has_selection)| {
 5008                            active_row.0 == end_row + 1
 5009                                && has_selection.selection == contains_non_empty_selection.selection
 5010                        })
 5011                    {
 5012                        active_rows.next().unwrap();
 5013                        end_row += 1;
 5014                    }
 5015
 5016                    if show_active_line_background && !contains_non_empty_selection.selection {
 5017                        let highlight_h_range =
 5018                            match layout.position_map.snapshot.current_line_highlight {
 5019                                CurrentLineHighlight::Gutter => Some(Range {
 5020                                    start: layout.hitbox.left(),
 5021                                    end: layout.gutter_hitbox.right(),
 5022                                }),
 5023                                CurrentLineHighlight::Line => Some(Range {
 5024                                    start: layout.position_map.text_hitbox.bounds.left(),
 5025                                    end: layout.position_map.text_hitbox.bounds.right(),
 5026                                }),
 5027                                CurrentLineHighlight::All => Some(Range {
 5028                                    start: layout.hitbox.left(),
 5029                                    end: layout.hitbox.right(),
 5030                                }),
 5031                                CurrentLineHighlight::None => None,
 5032                            };
 5033                        if let Some(range) = highlight_h_range {
 5034                            let active_line_bg = cx.theme().colors().editor_active_line_background;
 5035                            let bounds = Bounds {
 5036                                origin: point(
 5037                                    range.start,
 5038                                    layout.hitbox.origin.y
 5039                                        + (start_row.as_f32() - scroll_top)
 5040                                            * layout.position_map.line_height,
 5041                                ),
 5042                                size: size(
 5043                                    range.end - range.start,
 5044                                    layout.position_map.line_height
 5045                                        * (end_row - start_row.0 + 1) as f32,
 5046                                ),
 5047                            };
 5048                            window.paint_quad(fill(bounds, active_line_bg));
 5049                        }
 5050                    }
 5051                }
 5052
 5053                let mut paint_highlight = |highlight_row_start: DisplayRow,
 5054                                           highlight_row_end: DisplayRow,
 5055                                           highlight: crate::LineHighlight,
 5056                                           edges| {
 5057                    let mut origin_x = layout.hitbox.left();
 5058                    let mut width = layout.hitbox.size.width;
 5059                    if !highlight.include_gutter {
 5060                        origin_x += layout.gutter_hitbox.size.width;
 5061                        width -= layout.gutter_hitbox.size.width;
 5062                    }
 5063
 5064                    let origin = point(
 5065                        origin_x,
 5066                        layout.hitbox.origin.y
 5067                            + (highlight_row_start.as_f32() - scroll_top)
 5068                                * layout.position_map.line_height,
 5069                    );
 5070                    let size = size(
 5071                        width,
 5072                        layout.position_map.line_height
 5073                            * highlight_row_end.next_row().minus(highlight_row_start) as f32,
 5074                    );
 5075                    let mut quad = fill(Bounds { origin, size }, highlight.background);
 5076                    if let Some(border_color) = highlight.border {
 5077                        quad.border_color = border_color;
 5078                        quad.border_widths = edges
 5079                    }
 5080                    window.paint_quad(quad);
 5081                };
 5082
 5083                let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
 5084                    None;
 5085                for (&new_row, &new_background) in &layout.highlighted_rows {
 5086                    match &mut current_paint {
 5087                        &mut Some((current_background, ref mut current_range, mut edges)) => {
 5088                            let new_range_started = current_background != new_background
 5089                                || current_range.end.next_row() != new_row;
 5090                            if new_range_started {
 5091                                if current_range.end.next_row() == new_row {
 5092                                    edges.bottom = px(0.);
 5093                                };
 5094                                paint_highlight(
 5095                                    current_range.start,
 5096                                    current_range.end,
 5097                                    current_background,
 5098                                    edges,
 5099                                );
 5100                                let edges = Edges {
 5101                                    top: if current_range.end.next_row() != new_row {
 5102                                        px(1.)
 5103                                    } else {
 5104                                        px(0.)
 5105                                    },
 5106                                    bottom: px(1.),
 5107                                    ..Default::default()
 5108                                };
 5109                                current_paint = Some((new_background, new_row..new_row, edges));
 5110                                continue;
 5111                            } else {
 5112                                current_range.end = current_range.end.next_row();
 5113                            }
 5114                        }
 5115                        None => {
 5116                            let edges = Edges {
 5117                                top: px(1.),
 5118                                bottom: px(1.),
 5119                                ..Default::default()
 5120                            };
 5121                            current_paint = Some((new_background, new_row..new_row, edges))
 5122                        }
 5123                    };
 5124                }
 5125                if let Some((color, range, edges)) = current_paint {
 5126                    paint_highlight(range.start, range.end, color, edges);
 5127                }
 5128
 5129                let scroll_left =
 5130                    layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
 5131
 5132                for (wrap_position, active) in layout.wrap_guides.iter() {
 5133                    let x = (layout.position_map.text_hitbox.origin.x
 5134                        + *wrap_position
 5135                        + layout.position_map.em_width / 2.)
 5136                        - scroll_left;
 5137
 5138                    let show_scrollbars = layout
 5139                        .scrollbars_layout
 5140                        .as_ref()
 5141                        .map_or(false, |layout| layout.visible);
 5142
 5143                    if x < layout.position_map.text_hitbox.origin.x
 5144                        || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
 5145                    {
 5146                        continue;
 5147                    }
 5148
 5149                    let color = if *active {
 5150                        cx.theme().colors().editor_active_wrap_guide
 5151                    } else {
 5152                        cx.theme().colors().editor_wrap_guide
 5153                    };
 5154                    window.paint_quad(fill(
 5155                        Bounds {
 5156                            origin: point(x, layout.position_map.text_hitbox.origin.y),
 5157                            size: size(px(1.), layout.position_map.text_hitbox.size.height),
 5158                        },
 5159                        color,
 5160                    ));
 5161                }
 5162            }
 5163        })
 5164    }
 5165
 5166    fn paint_indent_guides(
 5167        &mut self,
 5168        layout: &mut EditorLayout,
 5169        window: &mut Window,
 5170        cx: &mut App,
 5171    ) {
 5172        let Some(indent_guides) = &layout.indent_guides else {
 5173            return;
 5174        };
 5175
 5176        let faded_color = |color: Hsla, alpha: f32| {
 5177            let mut faded = color;
 5178            faded.a = alpha;
 5179            faded
 5180        };
 5181
 5182        for indent_guide in indent_guides {
 5183            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
 5184            let settings = indent_guide.settings;
 5185
 5186            // TODO fixed for now, expose them through themes later
 5187            const INDENT_AWARE_ALPHA: f32 = 0.2;
 5188            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
 5189            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
 5190            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
 5191
 5192            let line_color = match (settings.coloring, indent_guide.active) {
 5193                (IndentGuideColoring::Disabled, _) => None,
 5194                (IndentGuideColoring::Fixed, false) => {
 5195                    Some(cx.theme().colors().editor_indent_guide)
 5196                }
 5197                (IndentGuideColoring::Fixed, true) => {
 5198                    Some(cx.theme().colors().editor_indent_guide_active)
 5199                }
 5200                (IndentGuideColoring::IndentAware, false) => {
 5201                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
 5202                }
 5203                (IndentGuideColoring::IndentAware, true) => {
 5204                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
 5205                }
 5206            };
 5207
 5208            let background_color = match (settings.background_coloring, indent_guide.active) {
 5209                (IndentGuideBackgroundColoring::Disabled, _) => None,
 5210                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
 5211                    indent_accent_colors,
 5212                    INDENT_AWARE_BACKGROUND_ALPHA,
 5213                )),
 5214                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
 5215                    indent_accent_colors,
 5216                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
 5217                )),
 5218            };
 5219
 5220            let requested_line_width = if indent_guide.active {
 5221                settings.active_line_width
 5222            } else {
 5223                settings.line_width
 5224            }
 5225            .clamp(1, 10);
 5226            let mut line_indicator_width = 0.;
 5227            if let Some(color) = line_color {
 5228                window.paint_quad(fill(
 5229                    Bounds {
 5230                        origin: indent_guide.origin,
 5231                        size: size(px(requested_line_width as f32), indent_guide.length),
 5232                    },
 5233                    color,
 5234                ));
 5235                line_indicator_width = requested_line_width as f32;
 5236            }
 5237
 5238            if let Some(color) = background_color {
 5239                let width = indent_guide.single_indent_width - px(line_indicator_width);
 5240                window.paint_quad(fill(
 5241                    Bounds {
 5242                        origin: point(
 5243                            indent_guide.origin.x + px(line_indicator_width),
 5244                            indent_guide.origin.y,
 5245                        ),
 5246                        size: size(width, indent_guide.length),
 5247                    },
 5248                    color,
 5249                ));
 5250            }
 5251        }
 5252    }
 5253
 5254    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 5255        let is_singleton = self.editor.read(cx).is_singleton(cx);
 5256
 5257        let line_height = layout.position_map.line_height;
 5258        window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
 5259
 5260        for LineNumberLayout {
 5261            shaped_line,
 5262            hitbox,
 5263        } in layout.line_numbers.values()
 5264        {
 5265            let Some(hitbox) = hitbox else {
 5266                continue;
 5267            };
 5268
 5269            let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
 5270                let color = cx.theme().colors().editor_hover_line_number;
 5271
 5272                let line = self.shape_line_number(shaped_line.text.clone(), color, window);
 5273                line.paint(hitbox.origin, line_height, window, cx).log_err()
 5274            } else {
 5275                shaped_line
 5276                    .paint(hitbox.origin, line_height, window, cx)
 5277                    .log_err()
 5278            }) else {
 5279                continue;
 5280            };
 5281
 5282            // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
 5283            // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
 5284            if is_singleton {
 5285                window.set_cursor_style(CursorStyle::IBeam, &hitbox);
 5286            } else {
 5287                window.set_cursor_style(CursorStyle::PointingHand, &hitbox);
 5288            }
 5289        }
 5290    }
 5291
 5292    fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 5293        if layout.display_hunks.is_empty() {
 5294            return;
 5295        }
 5296
 5297        let line_height = layout.position_map.line_height;
 5298        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 5299            for (hunk, hitbox) in &layout.display_hunks {
 5300                let hunk_to_paint = match hunk {
 5301                    DisplayDiffHunk::Folded { .. } => {
 5302                        let hunk_bounds = Self::diff_hunk_bounds(
 5303                            &layout.position_map.snapshot,
 5304                            line_height,
 5305                            layout.gutter_hitbox.bounds,
 5306                            &hunk,
 5307                        );
 5308                        Some((
 5309                            hunk_bounds,
 5310                            cx.theme().colors().version_control_modified,
 5311                            Corners::all(px(0.)),
 5312                            DiffHunkStatus::modified_none(),
 5313                        ))
 5314                    }
 5315                    DisplayDiffHunk::Unfolded {
 5316                        status,
 5317                        display_row_range,
 5318                        ..
 5319                    } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
 5320                        DiffHunkStatusKind::Added => (
 5321                            hunk_hitbox.bounds,
 5322                            cx.theme().colors().version_control_added,
 5323                            Corners::all(px(0.)),
 5324                            *status,
 5325                        ),
 5326                        DiffHunkStatusKind::Modified => (
 5327                            hunk_hitbox.bounds,
 5328                            cx.theme().colors().version_control_modified,
 5329                            Corners::all(px(0.)),
 5330                            *status,
 5331                        ),
 5332                        DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
 5333                            hunk_hitbox.bounds,
 5334                            cx.theme().colors().version_control_deleted,
 5335                            Corners::all(px(0.)),
 5336                            *status,
 5337                        ),
 5338                        DiffHunkStatusKind::Deleted => (
 5339                            Bounds::new(
 5340                                point(
 5341                                    hunk_hitbox.origin.x - hunk_hitbox.size.width,
 5342                                    hunk_hitbox.origin.y,
 5343                                ),
 5344                                size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
 5345                            ),
 5346                            cx.theme().colors().version_control_deleted,
 5347                            Corners::all(1. * line_height),
 5348                            *status,
 5349                        ),
 5350                    }),
 5351                };
 5352
 5353                if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
 5354                    // Flatten the background color with the editor color to prevent
 5355                    // elements below transparent hunks from showing through
 5356                    let flattened_background_color = cx
 5357                        .theme()
 5358                        .colors()
 5359                        .editor_background
 5360                        .blend(background_color);
 5361
 5362                    if !Self::diff_hunk_hollow(status, cx) {
 5363                        window.paint_quad(quad(
 5364                            hunk_bounds,
 5365                            corner_radii,
 5366                            flattened_background_color,
 5367                            Edges::default(),
 5368                            transparent_black(),
 5369                            BorderStyle::default(),
 5370                        ));
 5371                    } else {
 5372                        let flattened_unstaged_background_color = cx
 5373                            .theme()
 5374                            .colors()
 5375                            .editor_background
 5376                            .blend(background_color.opacity(0.3));
 5377
 5378                        window.paint_quad(quad(
 5379                            hunk_bounds,
 5380                            corner_radii,
 5381                            flattened_unstaged_background_color,
 5382                            Edges::all(Pixels(1.0)),
 5383                            flattened_background_color,
 5384                            BorderStyle::Solid,
 5385                        ));
 5386                    }
 5387                }
 5388            }
 5389        });
 5390    }
 5391
 5392    fn gutter_strip_width(line_height: Pixels) -> Pixels {
 5393        (0.275 * line_height).floor()
 5394    }
 5395
 5396    fn diff_hunk_bounds(
 5397        snapshot: &EditorSnapshot,
 5398        line_height: Pixels,
 5399        gutter_bounds: Bounds<Pixels>,
 5400        hunk: &DisplayDiffHunk,
 5401    ) -> Bounds<Pixels> {
 5402        let scroll_position = snapshot.scroll_position();
 5403        let scroll_top = scroll_position.y * line_height;
 5404        let gutter_strip_width = Self::gutter_strip_width(line_height);
 5405
 5406        match hunk {
 5407            DisplayDiffHunk::Folded { display_row, .. } => {
 5408                let start_y = display_row.as_f32() * line_height - scroll_top;
 5409                let end_y = start_y + line_height;
 5410                let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 5411                let highlight_size = size(gutter_strip_width, end_y - start_y);
 5412                Bounds::new(highlight_origin, highlight_size)
 5413            }
 5414            DisplayDiffHunk::Unfolded {
 5415                display_row_range,
 5416                status,
 5417                ..
 5418            } => {
 5419                if status.is_deleted() && display_row_range.is_empty() {
 5420                    let row = display_row_range.start;
 5421
 5422                    let offset = line_height / 2.;
 5423                    let start_y = row.as_f32() * line_height - offset - scroll_top;
 5424                    let end_y = start_y + line_height;
 5425
 5426                    let width = (0.35 * line_height).floor();
 5427                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 5428                    let highlight_size = size(width, end_y - start_y);
 5429                    Bounds::new(highlight_origin, highlight_size)
 5430                } else {
 5431                    let start_row = display_row_range.start;
 5432                    let end_row = display_row_range.end;
 5433                    // If we're in a multibuffer, row range span might include an
 5434                    // excerpt header, so if we were to draw the marker straight away,
 5435                    // the hunk might include the rows of that header.
 5436                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
 5437                    // Instead, we simply check whether the range we're dealing with includes
 5438                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
 5439                    let end_row_in_current_excerpt = snapshot
 5440                        .blocks_in_range(start_row..end_row)
 5441                        .find_map(|(start_row, block)| {
 5442                            if matches!(block, Block::ExcerptBoundary { .. }) {
 5443                                Some(start_row)
 5444                            } else {
 5445                                None
 5446                            }
 5447                        })
 5448                        .unwrap_or(end_row);
 5449
 5450                    let start_y = start_row.as_f32() * line_height - scroll_top;
 5451                    let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
 5452
 5453                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 5454                    let highlight_size = size(gutter_strip_width, end_y - start_y);
 5455                    Bounds::new(highlight_origin, highlight_size)
 5456                }
 5457            }
 5458        }
 5459    }
 5460
 5461    fn paint_gutter_indicators(
 5462        &self,
 5463        layout: &mut EditorLayout,
 5464        window: &mut Window,
 5465        cx: &mut App,
 5466    ) {
 5467        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 5468            window.with_element_namespace("crease_toggles", |window| {
 5469                for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
 5470                    crease_toggle.paint(window, cx);
 5471                }
 5472            });
 5473
 5474            window.with_element_namespace("expand_toggles", |window| {
 5475                for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
 5476                    expand_toggle.paint(window, cx);
 5477                }
 5478            });
 5479
 5480            for breakpoint in layout.breakpoints.iter_mut() {
 5481                breakpoint.paint(window, cx);
 5482            }
 5483
 5484            for test_indicator in layout.test_indicators.iter_mut() {
 5485                test_indicator.paint(window, cx);
 5486            }
 5487        });
 5488    }
 5489
 5490    fn paint_gutter_highlights(
 5491        &self,
 5492        layout: &mut EditorLayout,
 5493        window: &mut Window,
 5494        cx: &mut App,
 5495    ) {
 5496        for (_, hunk_hitbox) in &layout.display_hunks {
 5497            if let Some(hunk_hitbox) = hunk_hitbox {
 5498                if !self
 5499                    .editor
 5500                    .read(cx)
 5501                    .buffer()
 5502                    .read(cx)
 5503                    .all_diff_hunks_expanded()
 5504                {
 5505                    window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
 5506                }
 5507            }
 5508        }
 5509
 5510        let show_git_gutter = layout
 5511            .position_map
 5512            .snapshot
 5513            .show_git_diff_gutter
 5514            .unwrap_or_else(|| {
 5515                matches!(
 5516                    ProjectSettings::get_global(cx).git.git_gutter,
 5517                    Some(GitGutterSetting::TrackedFiles)
 5518                )
 5519            });
 5520        if show_git_gutter {
 5521            Self::paint_gutter_diff_hunks(layout, window, cx)
 5522        }
 5523
 5524        let highlight_width = 0.275 * layout.position_map.line_height;
 5525        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
 5526        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 5527            for (range, color) in &layout.highlighted_gutter_ranges {
 5528                let start_row = if range.start.row() < layout.visible_display_row_range.start {
 5529                    layout.visible_display_row_range.start - DisplayRow(1)
 5530                } else {
 5531                    range.start.row()
 5532                };
 5533                let end_row = if range.end.row() > layout.visible_display_row_range.end {
 5534                    layout.visible_display_row_range.end + DisplayRow(1)
 5535                } else {
 5536                    range.end.row()
 5537                };
 5538
 5539                let start_y = layout.gutter_hitbox.top()
 5540                    + start_row.0 as f32 * layout.position_map.line_height
 5541                    - layout.position_map.scroll_pixel_position.y;
 5542                let end_y = layout.gutter_hitbox.top()
 5543                    + (end_row.0 + 1) as f32 * layout.position_map.line_height
 5544                    - layout.position_map.scroll_pixel_position.y;
 5545                let bounds = Bounds::from_corners(
 5546                    point(layout.gutter_hitbox.left(), start_y),
 5547                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
 5548                );
 5549                window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
 5550            }
 5551        });
 5552    }
 5553
 5554    fn paint_blamed_display_rows(
 5555        &self,
 5556        layout: &mut EditorLayout,
 5557        window: &mut Window,
 5558        cx: &mut App,
 5559    ) {
 5560        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
 5561            return;
 5562        };
 5563
 5564        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 5565            for mut blame_element in blamed_display_rows.into_iter() {
 5566                blame_element.paint(window, cx);
 5567            }
 5568        })
 5569    }
 5570
 5571    fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 5572        window.with_content_mask(
 5573            Some(ContentMask {
 5574                bounds: layout.position_map.text_hitbox.bounds,
 5575            }),
 5576            |window| {
 5577                let editor = self.editor.read(cx);
 5578                if editor.mouse_cursor_hidden {
 5579                    window.set_window_cursor_style(CursorStyle::None);
 5580                } else if editor
 5581                    .hovered_link_state
 5582                    .as_ref()
 5583                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
 5584                {
 5585                    window.set_cursor_style(
 5586                        CursorStyle::PointingHand,
 5587                        &layout.position_map.text_hitbox,
 5588                    );
 5589                } else {
 5590                    window.set_cursor_style(CursorStyle::IBeam, &layout.position_map.text_hitbox);
 5591                };
 5592
 5593                self.paint_lines_background(layout, window, cx);
 5594                let invisible_display_ranges = self.paint_highlights(layout, window);
 5595                self.paint_lines(&invisible_display_ranges, layout, window, cx);
 5596                self.paint_redactions(layout, window);
 5597                self.paint_cursors(layout, window, cx);
 5598                self.paint_inline_diagnostics(layout, window, cx);
 5599                self.paint_inline_blame(layout, window, cx);
 5600                self.paint_inline_code_actions(layout, window, cx);
 5601                self.paint_diff_hunk_controls(layout, window, cx);
 5602                window.with_element_namespace("crease_trailers", |window| {
 5603                    for trailer in layout.crease_trailers.iter_mut().flatten() {
 5604                        trailer.element.paint(window, cx);
 5605                    }
 5606                });
 5607            },
 5608        )
 5609    }
 5610
 5611    fn paint_highlights(
 5612        &mut self,
 5613        layout: &mut EditorLayout,
 5614        window: &mut Window,
 5615    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
 5616        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 5617            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
 5618            let line_end_overshoot = 0.15 * layout.position_map.line_height;
 5619            for (range, color) in &layout.highlighted_ranges {
 5620                self.paint_highlighted_range(
 5621                    range.clone(),
 5622                    *color,
 5623                    Pixels::ZERO,
 5624                    line_end_overshoot,
 5625                    layout,
 5626                    window,
 5627                );
 5628            }
 5629
 5630            let corner_radius = 0.15 * layout.position_map.line_height;
 5631
 5632            for (player_color, selections) in &layout.selections {
 5633                for selection in selections.iter() {
 5634                    self.paint_highlighted_range(
 5635                        selection.range.clone(),
 5636                        player_color.selection,
 5637                        corner_radius,
 5638                        corner_radius * 2.,
 5639                        layout,
 5640                        window,
 5641                    );
 5642
 5643                    if selection.is_local && !selection.range.is_empty() {
 5644                        invisible_display_ranges.push(selection.range.clone());
 5645                    }
 5646                }
 5647            }
 5648            invisible_display_ranges
 5649        })
 5650    }
 5651
 5652    fn paint_lines(
 5653        &mut self,
 5654        invisible_display_ranges: &[Range<DisplayPoint>],
 5655        layout: &mut EditorLayout,
 5656        window: &mut Window,
 5657        cx: &mut App,
 5658    ) {
 5659        let whitespace_setting = self
 5660            .editor
 5661            .read(cx)
 5662            .buffer
 5663            .read(cx)
 5664            .language_settings(cx)
 5665            .show_whitespaces;
 5666
 5667        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
 5668            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
 5669            line_with_invisibles.draw(
 5670                layout,
 5671                row,
 5672                layout.content_origin,
 5673                whitespace_setting,
 5674                invisible_display_ranges,
 5675                window,
 5676                cx,
 5677            )
 5678        }
 5679
 5680        for line_element in &mut layout.line_elements {
 5681            line_element.paint(window, cx);
 5682        }
 5683    }
 5684
 5685    fn paint_lines_background(
 5686        &mut self,
 5687        layout: &mut EditorLayout,
 5688        window: &mut Window,
 5689        cx: &mut App,
 5690    ) {
 5691        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
 5692            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
 5693            line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
 5694        }
 5695    }
 5696
 5697    fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
 5698        if layout.redacted_ranges.is_empty() {
 5699            return;
 5700        }
 5701
 5702        let line_end_overshoot = layout.line_end_overshoot();
 5703
 5704        // A softer than perfect black
 5705        let redaction_color = gpui::rgb(0x0e1111);
 5706
 5707        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 5708            for range in layout.redacted_ranges.iter() {
 5709                self.paint_highlighted_range(
 5710                    range.clone(),
 5711                    redaction_color.into(),
 5712                    Pixels::ZERO,
 5713                    line_end_overshoot,
 5714                    layout,
 5715                    window,
 5716                );
 5717            }
 5718        });
 5719    }
 5720
 5721    fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 5722        for cursor in &mut layout.visible_cursors {
 5723            cursor.paint(layout.content_origin, window, cx);
 5724        }
 5725    }
 5726
 5727    fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 5728        let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
 5729            return;
 5730        };
 5731        let any_scrollbar_dragged = self.editor.read(cx).scroll_manager.any_scrollbar_dragged();
 5732
 5733        for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
 5734            let hitbox = &scrollbar_layout.hitbox;
 5735            if scrollbars_layout.visible {
 5736                let scrollbar_edges = match axis {
 5737                    ScrollbarAxis::Horizontal => Edges {
 5738                        top: Pixels::ZERO,
 5739                        right: Pixels::ZERO,
 5740                        bottom: Pixels::ZERO,
 5741                        left: Pixels::ZERO,
 5742                    },
 5743                    ScrollbarAxis::Vertical => Edges {
 5744                        top: Pixels::ZERO,
 5745                        right: Pixels::ZERO,
 5746                        bottom: Pixels::ZERO,
 5747                        left: ScrollbarLayout::BORDER_WIDTH,
 5748                    },
 5749                };
 5750
 5751                window.paint_layer(hitbox.bounds, |window| {
 5752                    window.paint_quad(quad(
 5753                        hitbox.bounds,
 5754                        Corners::default(),
 5755                        cx.theme().colors().scrollbar_track_background,
 5756                        scrollbar_edges,
 5757                        cx.theme().colors().scrollbar_track_border,
 5758                        BorderStyle::Solid,
 5759                    ));
 5760
 5761                    if axis == ScrollbarAxis::Vertical {
 5762                        let fast_markers =
 5763                            self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
 5764                        // Refresh slow scrollbar markers in the background. Below, we
 5765                        // paint whatever markers have already been computed.
 5766                        self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx);
 5767
 5768                        let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
 5769                        for marker in markers.iter().chain(&fast_markers) {
 5770                            let mut marker = marker.clone();
 5771                            marker.bounds.origin += hitbox.origin;
 5772                            window.paint_quad(marker);
 5773                        }
 5774                    }
 5775
 5776                    if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
 5777                        let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
 5778                            ScrollbarThumbState::Dragging => {
 5779                                cx.theme().colors().scrollbar_thumb_active_background
 5780                            }
 5781                            ScrollbarThumbState::Hovered => {
 5782                                cx.theme().colors().scrollbar_thumb_hover_background
 5783                            }
 5784                            ScrollbarThumbState::Idle => {
 5785                                cx.theme().colors().scrollbar_thumb_background
 5786                            }
 5787                        };
 5788                        window.paint_quad(quad(
 5789                            thumb_bounds,
 5790                            Corners::default(),
 5791                            scrollbar_thumb_color,
 5792                            scrollbar_edges,
 5793                            cx.theme().colors().scrollbar_thumb_border,
 5794                            BorderStyle::Solid,
 5795                        ));
 5796
 5797                        if any_scrollbar_dragged {
 5798                            window.set_window_cursor_style(CursorStyle::Arrow);
 5799                        } else {
 5800                            window.set_cursor_style(CursorStyle::Arrow, &hitbox);
 5801                        }
 5802                    }
 5803                })
 5804            }
 5805        }
 5806
 5807        window.on_mouse_event({
 5808            let editor = self.editor.clone();
 5809            let scrollbars_layout = scrollbars_layout.clone();
 5810
 5811            let mut mouse_position = window.mouse_position();
 5812            move |event: &MouseMoveEvent, phase, window, cx| {
 5813                if phase == DispatchPhase::Capture {
 5814                    return;
 5815                }
 5816
 5817                editor.update(cx, |editor, cx| {
 5818                    if let Some((scrollbar_layout, axis)) = event
 5819                        .pressed_button
 5820                        .filter(|button| *button == MouseButton::Left)
 5821                        .and(editor.scroll_manager.dragging_scrollbar_axis())
 5822                        .and_then(|axis| {
 5823                            scrollbars_layout
 5824                                .iter_scrollbars()
 5825                                .find(|(_, a)| *a == axis)
 5826                        })
 5827                    {
 5828                        let ScrollbarLayout {
 5829                            hitbox,
 5830                            text_unit_size,
 5831                            ..
 5832                        } = scrollbar_layout;
 5833
 5834                        let old_position = mouse_position.along(axis);
 5835                        let new_position = event.position.along(axis);
 5836                        if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
 5837                            .contains(&old_position)
 5838                        {
 5839                            let position = editor.scroll_position(cx).apply_along(axis, |p| {
 5840                                (p + (new_position - old_position) / *text_unit_size).max(0.)
 5841                            });
 5842                            editor.set_scroll_position(position, window, cx);
 5843                        }
 5844
 5845                        editor.scroll_manager.show_scrollbars(window, cx);
 5846                        cx.stop_propagation();
 5847                    } else if let Some((layout, axis)) = scrollbars_layout
 5848                        .get_hovered_axis(window)
 5849                        .filter(|_| !event.dragging())
 5850                    {
 5851                        if layout.thumb_hovered(&event.position) {
 5852                            editor
 5853                                .scroll_manager
 5854                                .set_hovered_scroll_thumb_axis(axis, cx);
 5855                        } else {
 5856                            editor.scroll_manager.reset_scrollbar_state(cx);
 5857                        }
 5858
 5859                        editor.scroll_manager.show_scrollbars(window, cx);
 5860                    } else {
 5861                        editor.scroll_manager.reset_scrollbar_state(cx);
 5862                    }
 5863
 5864                    mouse_position = event.position;
 5865                })
 5866            }
 5867        });
 5868
 5869        if any_scrollbar_dragged {
 5870            window.on_mouse_event({
 5871                let editor = self.editor.clone();
 5872                move |_: &MouseUpEvent, phase, window, cx| {
 5873                    if phase == DispatchPhase::Capture {
 5874                        return;
 5875                    }
 5876
 5877                    editor.update(cx, |editor, cx| {
 5878                        if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
 5879                            editor
 5880                                .scroll_manager
 5881                                .set_hovered_scroll_thumb_axis(axis, cx);
 5882                        } else {
 5883                            editor.scroll_manager.reset_scrollbar_state(cx);
 5884                        }
 5885                        cx.stop_propagation();
 5886                    });
 5887                }
 5888            });
 5889        } else {
 5890            window.on_mouse_event({
 5891                let editor = self.editor.clone();
 5892
 5893                move |event: &MouseDownEvent, phase, window, cx| {
 5894                    if phase == DispatchPhase::Capture {
 5895                        return;
 5896                    }
 5897                    let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
 5898                    else {
 5899                        return;
 5900                    };
 5901
 5902                    let ScrollbarLayout {
 5903                        hitbox,
 5904                        visible_range,
 5905                        text_unit_size,
 5906                        thumb_bounds,
 5907                        ..
 5908                    } = scrollbar_layout;
 5909
 5910                    let Some(thumb_bounds) = thumb_bounds else {
 5911                        return;
 5912                    };
 5913
 5914                    editor.update(cx, |editor, cx| {
 5915                        editor
 5916                            .scroll_manager
 5917                            .set_dragged_scroll_thumb_axis(axis, cx);
 5918
 5919                        let event_position = event.position.along(axis);
 5920
 5921                        if event_position < thumb_bounds.origin.along(axis)
 5922                            || thumb_bounds.bottom_right().along(axis) < event_position
 5923                        {
 5924                            let center_position = ((event_position - hitbox.origin.along(axis))
 5925                                / *text_unit_size)
 5926                                .round() as u32;
 5927                            let start_position = center_position.saturating_sub(
 5928                                (visible_range.end - visible_range.start) as u32 / 2,
 5929                            );
 5930
 5931                            let position = editor
 5932                                .scroll_position(cx)
 5933                                .apply_along(axis, |_| start_position as f32);
 5934
 5935                            editor.set_scroll_position(position, window, cx);
 5936                        } else {
 5937                            editor.scroll_manager.show_scrollbars(window, cx);
 5938                        }
 5939
 5940                        cx.stop_propagation();
 5941                    });
 5942                }
 5943            });
 5944        }
 5945    }
 5946
 5947    fn collect_fast_scrollbar_markers(
 5948        &self,
 5949        layout: &EditorLayout,
 5950        scrollbar_layout: &ScrollbarLayout,
 5951        cx: &mut App,
 5952    ) -> Vec<PaintQuad> {
 5953        const LIMIT: usize = 100;
 5954        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
 5955            return vec![];
 5956        }
 5957        let cursor_ranges = layout
 5958            .cursors
 5959            .iter()
 5960            .map(|(point, color)| ColoredRange {
 5961                start: point.row(),
 5962                end: point.row(),
 5963                color: *color,
 5964            })
 5965            .collect_vec();
 5966        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
 5967    }
 5968
 5969    fn refresh_slow_scrollbar_markers(
 5970        &self,
 5971        layout: &EditorLayout,
 5972        scrollbar_layout: &ScrollbarLayout,
 5973        window: &mut Window,
 5974        cx: &mut App,
 5975    ) {
 5976        self.editor.update(cx, |editor, cx| {
 5977            if !editor.is_singleton(cx)
 5978                || !editor
 5979                    .scrollbar_marker_state
 5980                    .should_refresh(scrollbar_layout.hitbox.size)
 5981            {
 5982                return;
 5983            }
 5984
 5985            let scrollbar_layout = scrollbar_layout.clone();
 5986            let background_highlights = editor.background_highlights.clone();
 5987            let snapshot = layout.position_map.snapshot.clone();
 5988            let theme = cx.theme().clone();
 5989            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
 5990
 5991            editor.scrollbar_marker_state.dirty = false;
 5992            editor.scrollbar_marker_state.pending_refresh =
 5993                Some(cx.spawn_in(window, async move |editor, cx| {
 5994                    let scrollbar_size = scrollbar_layout.hitbox.size;
 5995                    let scrollbar_markers = cx
 5996                        .background_spawn(async move {
 5997                            let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
 5998                            let mut marker_quads = Vec::new();
 5999                            if scrollbar_settings.git_diff {
 6000                                let marker_row_ranges =
 6001                                    snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
 6002                                        let start_display_row =
 6003                                            MultiBufferPoint::new(hunk.row_range.start.0, 0)
 6004                                                .to_display_point(&snapshot.display_snapshot)
 6005                                                .row();
 6006                                        let mut end_display_row =
 6007                                            MultiBufferPoint::new(hunk.row_range.end.0, 0)
 6008                                                .to_display_point(&snapshot.display_snapshot)
 6009                                                .row();
 6010                                        if end_display_row != start_display_row {
 6011                                            end_display_row.0 -= 1;
 6012                                        }
 6013                                        let color = match &hunk.status().kind {
 6014                                            DiffHunkStatusKind::Added => {
 6015                                                theme.colors().version_control_added
 6016                                            }
 6017                                            DiffHunkStatusKind::Modified => {
 6018                                                theme.colors().version_control_modified
 6019                                            }
 6020                                            DiffHunkStatusKind::Deleted => {
 6021                                                theme.colors().version_control_deleted
 6022                                            }
 6023                                        };
 6024                                        ColoredRange {
 6025                                            start: start_display_row,
 6026                                            end: end_display_row,
 6027                                            color,
 6028                                        }
 6029                                    });
 6030
 6031                                marker_quads.extend(
 6032                                    scrollbar_layout
 6033                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
 6034                                );
 6035                            }
 6036
 6037                            for (background_highlight_id, (_, background_ranges)) in
 6038                                background_highlights.iter()
 6039                            {
 6040                                let is_search_highlights = *background_highlight_id
 6041                                    == HighlightKey::Type(TypeId::of::<BufferSearchHighlights>());
 6042                                let is_text_highlights = *background_highlight_id
 6043                                    == HighlightKey::Type(TypeId::of::<SelectedTextHighlight>());
 6044                                let is_symbol_occurrences = *background_highlight_id
 6045                                    == HighlightKey::Type(TypeId::of::<DocumentHighlightRead>())
 6046                                    || *background_highlight_id
 6047                                        == HighlightKey::Type(
 6048                                            TypeId::of::<DocumentHighlightWrite>(),
 6049                                        );
 6050                                if (is_search_highlights && scrollbar_settings.search_results)
 6051                                    || (is_text_highlights && scrollbar_settings.selected_text)
 6052                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
 6053                                {
 6054                                    let mut color = theme.status().info;
 6055                                    if is_symbol_occurrences {
 6056                                        color.fade_out(0.5);
 6057                                    }
 6058                                    let marker_row_ranges = background_ranges.iter().map(|range| {
 6059                                        let display_start = range
 6060                                            .start
 6061                                            .to_display_point(&snapshot.display_snapshot);
 6062                                        let display_end =
 6063                                            range.end.to_display_point(&snapshot.display_snapshot);
 6064                                        ColoredRange {
 6065                                            start: display_start.row(),
 6066                                            end: display_end.row(),
 6067                                            color,
 6068                                        }
 6069                                    });
 6070                                    marker_quads.extend(
 6071                                        scrollbar_layout
 6072                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
 6073                                    );
 6074                                }
 6075                            }
 6076
 6077                            if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
 6078                                let diagnostics = snapshot
 6079                                    .buffer_snapshot
 6080                                    .diagnostics_in_range::<Point>(Point::zero()..max_point)
 6081                                    // Don't show diagnostics the user doesn't care about
 6082                                    .filter(|diagnostic| {
 6083                                        match (
 6084                                            scrollbar_settings.diagnostics,
 6085                                            diagnostic.diagnostic.severity,
 6086                                        ) {
 6087                                            (ScrollbarDiagnostics::All, _) => true,
 6088                                            (
 6089                                                ScrollbarDiagnostics::Error,
 6090                                                lsp::DiagnosticSeverity::ERROR,
 6091                                            ) => true,
 6092                                            (
 6093                                                ScrollbarDiagnostics::Warning,
 6094                                                lsp::DiagnosticSeverity::ERROR
 6095                                                | lsp::DiagnosticSeverity::WARNING,
 6096                                            ) => true,
 6097                                            (
 6098                                                ScrollbarDiagnostics::Information,
 6099                                                lsp::DiagnosticSeverity::ERROR
 6100                                                | lsp::DiagnosticSeverity::WARNING
 6101                                                | lsp::DiagnosticSeverity::INFORMATION,
 6102                                            ) => true,
 6103                                            (_, _) => false,
 6104                                        }
 6105                                    })
 6106                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
 6107                                    .sorted_by_key(|diagnostic| {
 6108                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
 6109                                    });
 6110
 6111                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
 6112                                    let start_display = diagnostic
 6113                                        .range
 6114                                        .start
 6115                                        .to_display_point(&snapshot.display_snapshot);
 6116                                    let end_display = diagnostic
 6117                                        .range
 6118                                        .end
 6119                                        .to_display_point(&snapshot.display_snapshot);
 6120                                    let color = match diagnostic.diagnostic.severity {
 6121                                        lsp::DiagnosticSeverity::ERROR => theme.status().error,
 6122                                        lsp::DiagnosticSeverity::WARNING => theme.status().warning,
 6123                                        lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
 6124                                        _ => theme.status().hint,
 6125                                    };
 6126                                    ColoredRange {
 6127                                        start: start_display.row(),
 6128                                        end: end_display.row(),
 6129                                        color,
 6130                                    }
 6131                                });
 6132                                marker_quads.extend(
 6133                                    scrollbar_layout
 6134                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
 6135                                );
 6136                            }
 6137
 6138                            Arc::from(marker_quads)
 6139                        })
 6140                        .await;
 6141
 6142                    editor.update(cx, |editor, cx| {
 6143                        editor.scrollbar_marker_state.markers = scrollbar_markers;
 6144                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
 6145                        editor.scrollbar_marker_state.pending_refresh = None;
 6146                        cx.notify();
 6147                    })?;
 6148
 6149                    Ok(())
 6150                }));
 6151        });
 6152    }
 6153
 6154    fn paint_highlighted_range(
 6155        &self,
 6156        range: Range<DisplayPoint>,
 6157        color: Hsla,
 6158        corner_radius: Pixels,
 6159        line_end_overshoot: Pixels,
 6160        layout: &EditorLayout,
 6161        window: &mut Window,
 6162    ) {
 6163        let start_row = layout.visible_display_row_range.start;
 6164        let end_row = layout.visible_display_row_range.end;
 6165        if range.start != range.end {
 6166            let row_range = if range.end.column() == 0 {
 6167                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
 6168            } else {
 6169                cmp::max(range.start.row(), start_row)
 6170                    ..cmp::min(range.end.row().next_row(), end_row)
 6171            };
 6172
 6173            let highlighted_range = HighlightedRange {
 6174                color,
 6175                line_height: layout.position_map.line_height,
 6176                corner_radius,
 6177                start_y: layout.content_origin.y
 6178                    + row_range.start.as_f32() * layout.position_map.line_height
 6179                    - layout.position_map.scroll_pixel_position.y,
 6180                lines: row_range
 6181                    .iter_rows()
 6182                    .map(|row| {
 6183                        let line_layout =
 6184                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
 6185                        HighlightedRangeLine {
 6186                            start_x: if row == range.start.row() {
 6187                                layout.content_origin.x
 6188                                    + line_layout.x_for_index(range.start.column() as usize)
 6189                                    - layout.position_map.scroll_pixel_position.x
 6190                            } else {
 6191                                layout.content_origin.x
 6192                                    - layout.position_map.scroll_pixel_position.x
 6193                            },
 6194                            end_x: if row == range.end.row() {
 6195                                layout.content_origin.x
 6196                                    + line_layout.x_for_index(range.end.column() as usize)
 6197                                    - layout.position_map.scroll_pixel_position.x
 6198                            } else {
 6199                                layout.content_origin.x + line_layout.width + line_end_overshoot
 6200                                    - layout.position_map.scroll_pixel_position.x
 6201                            },
 6202                        }
 6203                    })
 6204                    .collect(),
 6205            };
 6206
 6207            highlighted_range.paint(layout.position_map.text_hitbox.bounds, window);
 6208        }
 6209    }
 6210
 6211    fn paint_inline_diagnostics(
 6212        &mut self,
 6213        layout: &mut EditorLayout,
 6214        window: &mut Window,
 6215        cx: &mut App,
 6216    ) {
 6217        for mut inline_diagnostic in layout.inline_diagnostics.drain() {
 6218            inline_diagnostic.1.paint(window, cx);
 6219        }
 6220    }
 6221
 6222    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6223        if let Some(mut inline_blame) = layout.inline_blame.take() {
 6224            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6225                inline_blame.paint(window, cx);
 6226            })
 6227        }
 6228    }
 6229
 6230    fn paint_inline_code_actions(
 6231        &mut self,
 6232        layout: &mut EditorLayout,
 6233        window: &mut Window,
 6234        cx: &mut App,
 6235    ) {
 6236        if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
 6237            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6238                inline_code_actions.paint(window, cx);
 6239            })
 6240        }
 6241    }
 6242
 6243    fn paint_diff_hunk_controls(
 6244        &mut self,
 6245        layout: &mut EditorLayout,
 6246        window: &mut Window,
 6247        cx: &mut App,
 6248    ) {
 6249        for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
 6250            diff_hunk_control.paint(window, cx);
 6251        }
 6252    }
 6253
 6254    fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6255        if let Some(mut layout) = layout.minimap.take() {
 6256            let minimap_hitbox = layout.thumb_layout.hitbox.clone();
 6257            let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
 6258
 6259            window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
 6260                window.with_element_namespace("minimap", |window| {
 6261                    layout.minimap.paint(window, cx);
 6262                    if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
 6263                        let minimap_thumb_color = match layout.thumb_layout.thumb_state {
 6264                            ScrollbarThumbState::Idle => {
 6265                                cx.theme().colors().minimap_thumb_background
 6266                            }
 6267                            ScrollbarThumbState::Hovered => {
 6268                                cx.theme().colors().minimap_thumb_hover_background
 6269                            }
 6270                            ScrollbarThumbState::Dragging => {
 6271                                cx.theme().colors().minimap_thumb_active_background
 6272                            }
 6273                        };
 6274                        let minimap_thumb_border = match layout.thumb_border_style {
 6275                            MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
 6276                            MinimapThumbBorder::LeftOnly => Edges {
 6277                                left: ScrollbarLayout::BORDER_WIDTH,
 6278                                ..Default::default()
 6279                            },
 6280                            MinimapThumbBorder::LeftOpen => Edges {
 6281                                right: ScrollbarLayout::BORDER_WIDTH,
 6282                                top: ScrollbarLayout::BORDER_WIDTH,
 6283                                bottom: ScrollbarLayout::BORDER_WIDTH,
 6284                                ..Default::default()
 6285                            },
 6286                            MinimapThumbBorder::RightOpen => Edges {
 6287                                left: ScrollbarLayout::BORDER_WIDTH,
 6288                                top: ScrollbarLayout::BORDER_WIDTH,
 6289                                bottom: ScrollbarLayout::BORDER_WIDTH,
 6290                                ..Default::default()
 6291                            },
 6292                            MinimapThumbBorder::None => Default::default(),
 6293                        };
 6294
 6295                        window.paint_layer(minimap_hitbox.bounds, |window| {
 6296                            window.paint_quad(quad(
 6297                                thumb_bounds,
 6298                                Corners::default(),
 6299                                minimap_thumb_color,
 6300                                minimap_thumb_border,
 6301                                cx.theme().colors().minimap_thumb_border,
 6302                                BorderStyle::Solid,
 6303                            ));
 6304                        });
 6305                    }
 6306                });
 6307            });
 6308
 6309            if dragging_minimap {
 6310                window.set_window_cursor_style(CursorStyle::Arrow);
 6311            } else {
 6312                window.set_cursor_style(CursorStyle::Arrow, &minimap_hitbox);
 6313            }
 6314
 6315            let minimap_axis = ScrollbarAxis::Vertical;
 6316            let pixels_per_line = (minimap_hitbox.size.height / layout.max_scroll_top)
 6317                .min(layout.minimap_line_height);
 6318
 6319            let mut mouse_position = window.mouse_position();
 6320
 6321            window.on_mouse_event({
 6322                let editor = self.editor.clone();
 6323
 6324                let minimap_hitbox = minimap_hitbox.clone();
 6325
 6326                move |event: &MouseMoveEvent, phase, window, cx| {
 6327                    if phase == DispatchPhase::Capture {
 6328                        return;
 6329                    }
 6330
 6331                    editor.update(cx, |editor, cx| {
 6332                        if event.pressed_button == Some(MouseButton::Left)
 6333                            && editor.scroll_manager.is_dragging_minimap()
 6334                        {
 6335                            let old_position = mouse_position.along(minimap_axis);
 6336                            let new_position = event.position.along(minimap_axis);
 6337                            if (minimap_hitbox.origin.along(minimap_axis)
 6338                                ..minimap_hitbox.bottom_right().along(minimap_axis))
 6339                                .contains(&old_position)
 6340                            {
 6341                                let position =
 6342                                    editor.scroll_position(cx).apply_along(minimap_axis, |p| {
 6343                                        (p + (new_position - old_position) / pixels_per_line)
 6344                                            .max(0.)
 6345                                    });
 6346                                editor.set_scroll_position(position, window, cx);
 6347                            }
 6348                            cx.stop_propagation();
 6349                        } else {
 6350                            if minimap_hitbox.is_hovered(window) {
 6351                                editor.scroll_manager.set_is_hovering_minimap_thumb(
 6352                                    !event.dragging()
 6353                                        && layout
 6354                                            .thumb_layout
 6355                                            .thumb_bounds
 6356                                            .is_some_and(|bounds| bounds.contains(&event.position)),
 6357                                    cx,
 6358                                );
 6359
 6360                                // Stop hover events from propagating to the
 6361                                // underlying editor if the minimap hitbox is hovered
 6362                                if !event.dragging() {
 6363                                    cx.stop_propagation();
 6364                                }
 6365                            } else {
 6366                                editor.scroll_manager.hide_minimap_thumb(cx);
 6367                            }
 6368                        }
 6369                        mouse_position = event.position;
 6370                    });
 6371                }
 6372            });
 6373
 6374            if dragging_minimap {
 6375                window.on_mouse_event({
 6376                    let editor = self.editor.clone();
 6377                    move |event: &MouseUpEvent, phase, window, cx| {
 6378                        if phase == DispatchPhase::Capture {
 6379                            return;
 6380                        }
 6381
 6382                        editor.update(cx, |editor, cx| {
 6383                            if minimap_hitbox.is_hovered(window) {
 6384                                editor.scroll_manager.set_is_hovering_minimap_thumb(
 6385                                    layout
 6386                                        .thumb_layout
 6387                                        .thumb_bounds
 6388                                        .is_some_and(|bounds| bounds.contains(&event.position)),
 6389                                    cx,
 6390                                );
 6391                            } else {
 6392                                editor.scroll_manager.hide_minimap_thumb(cx);
 6393                            }
 6394                            cx.stop_propagation();
 6395                        });
 6396                    }
 6397                });
 6398            } else {
 6399                window.on_mouse_event({
 6400                    let editor = self.editor.clone();
 6401
 6402                    move |event: &MouseDownEvent, phase, window, cx| {
 6403                        if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
 6404                            return;
 6405                        }
 6406
 6407                        let event_position = event.position;
 6408
 6409                        let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
 6410                            return;
 6411                        };
 6412
 6413                        editor.update(cx, |editor, cx| {
 6414                            if !thumb_bounds.contains(&event_position) {
 6415                                let click_position =
 6416                                    event_position.relative_to(&minimap_hitbox.origin).y;
 6417
 6418                                let top_position = (click_position
 6419                                    - thumb_bounds.size.along(minimap_axis) / 2.0)
 6420                                    .max(Pixels::ZERO);
 6421
 6422                                let scroll_offset = (layout.minimap_scroll_top
 6423                                    + top_position / layout.minimap_line_height)
 6424                                    .min(layout.max_scroll_top);
 6425
 6426                                let scroll_position = editor
 6427                                    .scroll_position(cx)
 6428                                    .apply_along(minimap_axis, |_| scroll_offset);
 6429                                editor.set_scroll_position(scroll_position, window, cx);
 6430                            }
 6431
 6432                            editor.scroll_manager.set_is_dragging_minimap(cx);
 6433                            cx.stop_propagation();
 6434                        });
 6435                    }
 6436                });
 6437            }
 6438        }
 6439    }
 6440
 6441    fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6442        for mut block in layout.blocks.drain(..) {
 6443            if block.overlaps_gutter {
 6444                block.element.paint(window, cx);
 6445            } else {
 6446                let mut bounds = layout.hitbox.bounds;
 6447                bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
 6448                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 6449                    block.element.paint(window, cx);
 6450                })
 6451            }
 6452        }
 6453    }
 6454
 6455    fn paint_inline_completion_popover(
 6456        &mut self,
 6457        layout: &mut EditorLayout,
 6458        window: &mut Window,
 6459        cx: &mut App,
 6460    ) {
 6461        if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
 6462            inline_completion_popover.paint(window, cx);
 6463        }
 6464    }
 6465
 6466    fn paint_mouse_context_menu(
 6467        &mut self,
 6468        layout: &mut EditorLayout,
 6469        window: &mut Window,
 6470        cx: &mut App,
 6471    ) {
 6472        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
 6473            mouse_context_menu.paint(window, cx);
 6474        }
 6475    }
 6476
 6477    fn paint_scroll_wheel_listener(
 6478        &mut self,
 6479        layout: &EditorLayout,
 6480        window: &mut Window,
 6481        cx: &mut App,
 6482    ) {
 6483        window.on_mouse_event({
 6484            let position_map = layout.position_map.clone();
 6485            let editor = self.editor.clone();
 6486            let hitbox = layout.hitbox.clone();
 6487            let mut delta = ScrollDelta::default();
 6488
 6489            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
 6490            // accidentally turn off their scrolling.
 6491            let base_scroll_sensitivity =
 6492                EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
 6493
 6494            // Use a minimum fast_scroll_sensitivity for same reason above
 6495            let fast_scroll_sensitivity = EditorSettings::get_global(cx)
 6496                .fast_scroll_sensitivity
 6497                .max(0.01);
 6498
 6499            move |event: &ScrollWheelEvent, phase, window, cx| {
 6500                let scroll_sensitivity = {
 6501                    if event.modifiers.alt {
 6502                        fast_scroll_sensitivity
 6503                    } else {
 6504                        base_scroll_sensitivity
 6505                    }
 6506                };
 6507
 6508                if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
 6509                    delta = delta.coalesce(event.delta);
 6510                    editor.update(cx, |editor, cx| {
 6511                        let position_map: &PositionMap = &position_map;
 6512
 6513                        let line_height = position_map.line_height;
 6514                        let max_glyph_width = position_map.em_width;
 6515                        let (delta, axis) = match delta {
 6516                            gpui::ScrollDelta::Pixels(mut pixels) => {
 6517                                //Trackpad
 6518                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
 6519                                (pixels, axis)
 6520                            }
 6521
 6522                            gpui::ScrollDelta::Lines(lines) => {
 6523                                //Not trackpad
 6524                                let pixels =
 6525                                    point(lines.x * max_glyph_width, lines.y * line_height);
 6526                                (pixels, None)
 6527                            }
 6528                        };
 6529
 6530                        let current_scroll_position = position_map.snapshot.scroll_position();
 6531                        let x = (current_scroll_position.x * max_glyph_width
 6532                            - (delta.x * scroll_sensitivity))
 6533                            / max_glyph_width;
 6534                        let y = (current_scroll_position.y * line_height
 6535                            - (delta.y * scroll_sensitivity))
 6536                            / line_height;
 6537                        let mut scroll_position =
 6538                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
 6539                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
 6540                        if forbid_vertical_scroll {
 6541                            scroll_position.y = current_scroll_position.y;
 6542                        }
 6543
 6544                        if scroll_position != current_scroll_position {
 6545                            editor.scroll(scroll_position, axis, window, cx);
 6546                            cx.stop_propagation();
 6547                        } else if y < 0. {
 6548                            // Due to clamping, we may fail to detect cases of overscroll to the top;
 6549                            // We want the scroll manager to get an update in such cases and detect the change of direction
 6550                            // on the next frame.
 6551                            cx.notify();
 6552                        }
 6553                    });
 6554                }
 6555            }
 6556        });
 6557    }
 6558
 6559    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
 6560        if self.editor.read(cx).mode.is_minimap() {
 6561            return;
 6562        }
 6563
 6564        self.paint_scroll_wheel_listener(layout, window, cx);
 6565
 6566        window.on_mouse_event({
 6567            let position_map = layout.position_map.clone();
 6568            let editor = self.editor.clone();
 6569            let diff_hunk_range =
 6570                layout
 6571                    .display_hunks
 6572                    .iter()
 6573                    .find_map(|(hunk, hunk_hitbox)| match hunk {
 6574                        DisplayDiffHunk::Folded { .. } => None,
 6575                        DisplayDiffHunk::Unfolded {
 6576                            multi_buffer_range, ..
 6577                        } => {
 6578                            if hunk_hitbox
 6579                                .as_ref()
 6580                                .map(|hitbox| hitbox.is_hovered(window))
 6581                                .unwrap_or(false)
 6582                            {
 6583                                Some(multi_buffer_range.clone())
 6584                            } else {
 6585                                None
 6586                            }
 6587                        }
 6588                    });
 6589            let line_numbers = layout.line_numbers.clone();
 6590
 6591            move |event: &MouseDownEvent, phase, window, cx| {
 6592                if phase == DispatchPhase::Bubble {
 6593                    match event.button {
 6594                        MouseButton::Left => editor.update(cx, |editor, cx| {
 6595                            let pending_mouse_down = editor
 6596                                .pending_mouse_down
 6597                                .get_or_insert_with(Default::default)
 6598                                .clone();
 6599
 6600                            *pending_mouse_down.borrow_mut() = Some(event.clone());
 6601
 6602                            Self::mouse_left_down(
 6603                                editor,
 6604                                event,
 6605                                diff_hunk_range.clone(),
 6606                                &position_map,
 6607                                line_numbers.as_ref(),
 6608                                window,
 6609                                cx,
 6610                            );
 6611                        }),
 6612                        MouseButton::Right => editor.update(cx, |editor, cx| {
 6613                            Self::mouse_right_down(editor, event, &position_map, window, cx);
 6614                        }),
 6615                        MouseButton::Middle => editor.update(cx, |editor, cx| {
 6616                            Self::mouse_middle_down(editor, event, &position_map, window, cx);
 6617                        }),
 6618                        _ => {}
 6619                    };
 6620                }
 6621            }
 6622        });
 6623
 6624        window.on_mouse_event({
 6625            let editor = self.editor.clone();
 6626            let position_map = layout.position_map.clone();
 6627
 6628            move |event: &MouseUpEvent, phase, window, cx| {
 6629                if phase == DispatchPhase::Bubble {
 6630                    editor.update(cx, |editor, cx| {
 6631                        Self::mouse_up(editor, event, &position_map, window, cx)
 6632                    });
 6633                }
 6634            }
 6635        });
 6636
 6637        window.on_mouse_event({
 6638            let editor = self.editor.clone();
 6639            let position_map = layout.position_map.clone();
 6640            let mut captured_mouse_down = None;
 6641
 6642            move |event: &MouseUpEvent, phase, window, cx| match phase {
 6643                // Clear the pending mouse down during the capture phase,
 6644                // so that it happens even if another event handler stops
 6645                // propagation.
 6646                DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
 6647                    let pending_mouse_down = editor
 6648                        .pending_mouse_down
 6649                        .get_or_insert_with(Default::default)
 6650                        .clone();
 6651
 6652                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
 6653                    if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
 6654                        captured_mouse_down = pending_mouse_down.take();
 6655                        window.refresh();
 6656                    }
 6657                }),
 6658                // Fire click handlers during the bubble phase.
 6659                DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
 6660                    if let Some(mouse_down) = captured_mouse_down.take() {
 6661                        let event = ClickEvent {
 6662                            down: mouse_down,
 6663                            up: event.clone(),
 6664                        };
 6665                        Self::click(editor, &event, &position_map, window, cx);
 6666                    }
 6667                }),
 6668            }
 6669        });
 6670
 6671        window.on_mouse_event({
 6672            let position_map = layout.position_map.clone();
 6673            let editor = self.editor.clone();
 6674
 6675            move |event: &MouseMoveEvent, phase, window, cx| {
 6676                if phase == DispatchPhase::Bubble {
 6677                    editor.update(cx, |editor, cx| {
 6678                        if editor.hover_state.focused(window, cx) {
 6679                            return;
 6680                        }
 6681                        if event.pressed_button == Some(MouseButton::Left)
 6682                            || event.pressed_button == Some(MouseButton::Middle)
 6683                        {
 6684                            Self::mouse_dragged(editor, event, &position_map, window, cx)
 6685                        }
 6686
 6687                        Self::mouse_moved(editor, event, &position_map, window, cx)
 6688                    });
 6689                }
 6690            }
 6691        });
 6692    }
 6693
 6694    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
 6695        bounds.top_right().x - self.style.scrollbar_width
 6696    }
 6697
 6698    fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
 6699        let style = &self.style;
 6700        let font_size = style.text.font_size.to_pixels(window.rem_size());
 6701        let layout = window.text_system().shape_line(
 6702            SharedString::from(" ".repeat(column)),
 6703            font_size,
 6704            &[TextRun {
 6705                len: column,
 6706                font: style.text.font(),
 6707                color: Hsla::default(),
 6708                background_color: None,
 6709                underline: None,
 6710                strikethrough: None,
 6711            }],
 6712        );
 6713
 6714        layout.width
 6715    }
 6716
 6717    fn max_line_number_width(
 6718        &self,
 6719        snapshot: &EditorSnapshot,
 6720        window: &mut Window,
 6721        cx: &mut App,
 6722    ) -> Pixels {
 6723        let digit_count = snapshot.widest_line_number().ilog10() + 1;
 6724        self.column_pixels(digit_count as usize, window, cx)
 6725    }
 6726
 6727    fn shape_line_number(
 6728        &self,
 6729        text: SharedString,
 6730        color: Hsla,
 6731        window: &mut Window,
 6732    ) -> ShapedLine {
 6733        let run = TextRun {
 6734            len: text.len(),
 6735            font: self.style.text.font(),
 6736            color,
 6737            background_color: None,
 6738            underline: None,
 6739            strikethrough: None,
 6740        };
 6741        window.text_system().shape_line(
 6742            text,
 6743            self.style.text.font_size.to_pixels(window.rem_size()),
 6744            &[run],
 6745        )
 6746    }
 6747
 6748    fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
 6749        let unstaged = status.has_secondary_hunk();
 6750        let unstaged_hollow = ProjectSettings::get_global(cx)
 6751            .git
 6752            .hunk_style
 6753            .map_or(false, |style| {
 6754                matches!(style, GitHunkStyleSetting::UnstagedHollow)
 6755            });
 6756
 6757        unstaged == unstaged_hollow
 6758    }
 6759}
 6760
 6761fn header_jump_data(
 6762    snapshot: &EditorSnapshot,
 6763    block_row_start: DisplayRow,
 6764    height: u32,
 6765    for_excerpt: &ExcerptInfo,
 6766) -> JumpData {
 6767    let range = &for_excerpt.range;
 6768    let buffer = &for_excerpt.buffer;
 6769    let jump_anchor = range.primary.start;
 6770
 6771    let excerpt_start = range.context.start;
 6772    let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
 6773    let rows_from_excerpt_start = if jump_anchor == excerpt_start {
 6774        0
 6775    } else {
 6776        let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
 6777        jump_position.row.saturating_sub(excerpt_start_point.row)
 6778    };
 6779
 6780    let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
 6781        .saturating_sub(
 6782            snapshot
 6783                .scroll_anchor
 6784                .scroll_position(&snapshot.display_snapshot)
 6785                .y as u32,
 6786        );
 6787
 6788    JumpData::MultiBufferPoint {
 6789        excerpt_id: for_excerpt.id,
 6790        anchor: jump_anchor,
 6791        position: jump_position,
 6792        line_offset_from_top,
 6793    }
 6794}
 6795
 6796pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
 6797
 6798impl AcceptEditPredictionBinding {
 6799    pub fn keystroke(&self) -> Option<&Keystroke> {
 6800        if let Some(binding) = self.0.as_ref() {
 6801            match &binding.keystrokes() {
 6802                [keystroke, ..] => Some(keystroke),
 6803                _ => None,
 6804            }
 6805        } else {
 6806            None
 6807        }
 6808    }
 6809}
 6810
 6811fn prepaint_gutter_button(
 6812    button: IconButton,
 6813    row: DisplayRow,
 6814    line_height: Pixels,
 6815    gutter_dimensions: &GutterDimensions,
 6816    scroll_pixel_position: gpui::Point<Pixels>,
 6817    gutter_hitbox: &Hitbox,
 6818    display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 6819    window: &mut Window,
 6820    cx: &mut App,
 6821) -> AnyElement {
 6822    let mut button = button.into_any_element();
 6823
 6824    let available_space = size(
 6825        AvailableSpace::MinContent,
 6826        AvailableSpace::Definite(line_height),
 6827    );
 6828    let indicator_size = button.layout_as_root(available_space, window, cx);
 6829
 6830    let blame_width = gutter_dimensions.git_blame_entries_width;
 6831    let gutter_width = display_hunks
 6832        .binary_search_by(|(hunk, _)| match hunk {
 6833            DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
 6834            DisplayDiffHunk::Unfolded {
 6835                display_row_range, ..
 6836            } => {
 6837                if display_row_range.end <= row {
 6838                    Ordering::Less
 6839                } else if display_row_range.start > row {
 6840                    Ordering::Greater
 6841                } else {
 6842                    Ordering::Equal
 6843                }
 6844            }
 6845        })
 6846        .ok()
 6847        .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
 6848    let left_offset = blame_width.max(gutter_width).unwrap_or_default();
 6849
 6850    let mut x = left_offset;
 6851    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
 6852        - indicator_size.width
 6853        - left_offset;
 6854    x += available_width / 2.;
 6855
 6856    let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
 6857    y += (line_height - indicator_size.height) / 2.;
 6858
 6859    button.prepaint_as_root(
 6860        gutter_hitbox.origin + point(x, y),
 6861        available_space,
 6862        window,
 6863        cx,
 6864    );
 6865    button
 6866}
 6867
 6868fn render_inline_blame_entry(
 6869    blame_entry: BlameEntry,
 6870    style: &EditorStyle,
 6871    cx: &mut App,
 6872) -> Option<AnyElement> {
 6873    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 6874    renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
 6875}
 6876
 6877fn render_blame_entry_popover(
 6878    blame_entry: BlameEntry,
 6879    scroll_handle: ScrollHandle,
 6880    commit_message: Option<ParsedCommitMessage>,
 6881    markdown: Entity<Markdown>,
 6882    workspace: WeakEntity<Workspace>,
 6883    blame: &Entity<GitBlame>,
 6884    window: &mut Window,
 6885    cx: &mut App,
 6886) -> Option<AnyElement> {
 6887    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 6888    let blame = blame.read(cx);
 6889    let repository = blame.repository(cx)?.clone();
 6890    renderer.render_blame_entry_popover(
 6891        blame_entry,
 6892        scroll_handle,
 6893        commit_message,
 6894        markdown,
 6895        repository,
 6896        workspace,
 6897        window,
 6898        cx,
 6899    )
 6900}
 6901
 6902fn render_blame_entry(
 6903    ix: usize,
 6904    blame: &Entity<GitBlame>,
 6905    blame_entry: BlameEntry,
 6906    style: &EditorStyle,
 6907    last_used_color: &mut Option<(PlayerColor, Oid)>,
 6908    editor: Entity<Editor>,
 6909    workspace: Entity<Workspace>,
 6910    renderer: Arc<dyn BlameRenderer>,
 6911    cx: &mut App,
 6912) -> Option<AnyElement> {
 6913    let mut sha_color = cx
 6914        .theme()
 6915        .players()
 6916        .color_for_participant(blame_entry.sha.into());
 6917
 6918    // If the last color we used is the same as the one we get for this line, but
 6919    // the commit SHAs are different, then we try again to get a different color.
 6920    match *last_used_color {
 6921        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
 6922            let index: u32 = blame_entry.sha.into();
 6923            sha_color = cx.theme().players().color_for_participant(index + 1);
 6924        }
 6925        _ => {}
 6926    };
 6927    last_used_color.replace((sha_color, blame_entry.sha));
 6928
 6929    let blame = blame.read(cx);
 6930    let details = blame.details_for_entry(&blame_entry);
 6931    let repository = blame.repository(cx)?;
 6932    renderer.render_blame_entry(
 6933        &style.text,
 6934        blame_entry,
 6935        details,
 6936        repository,
 6937        workspace.downgrade(),
 6938        editor,
 6939        ix,
 6940        sha_color.cursor,
 6941        cx,
 6942    )
 6943}
 6944
 6945#[derive(Debug)]
 6946pub(crate) struct LineWithInvisibles {
 6947    fragments: SmallVec<[LineFragment; 1]>,
 6948    invisibles: Vec<Invisible>,
 6949    len: usize,
 6950    pub(crate) width: Pixels,
 6951    font_size: Pixels,
 6952}
 6953
 6954enum LineFragment {
 6955    Text(ShapedLine),
 6956    Element {
 6957        id: FoldId,
 6958        element: Option<AnyElement>,
 6959        size: Size<Pixels>,
 6960        len: usize,
 6961    },
 6962}
 6963
 6964impl fmt::Debug for LineFragment {
 6965    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 6966        match self {
 6967            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
 6968            LineFragment::Element { size, len, .. } => f
 6969                .debug_struct("Element")
 6970                .field("size", size)
 6971                .field("len", len)
 6972                .finish(),
 6973        }
 6974    }
 6975}
 6976
 6977impl LineWithInvisibles {
 6978    fn from_chunks<'a>(
 6979        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
 6980        editor_style: &EditorStyle,
 6981        max_line_len: usize,
 6982        max_line_count: usize,
 6983        editor_mode: &EditorMode,
 6984        text_width: Pixels,
 6985        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 6986        window: &mut Window,
 6987        cx: &mut App,
 6988    ) -> Vec<Self> {
 6989        let text_style = &editor_style.text;
 6990        let mut layouts = Vec::with_capacity(max_line_count);
 6991        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
 6992        let mut line = String::new();
 6993        let mut invisibles = Vec::new();
 6994        let mut width = Pixels::ZERO;
 6995        let mut len = 0;
 6996        let mut styles = Vec::new();
 6997        let mut non_whitespace_added = false;
 6998        let mut row = 0;
 6999        let mut line_exceeded_max_len = false;
 7000        let font_size = text_style.font_size.to_pixels(window.rem_size());
 7001
 7002        let ellipsis = SharedString::from("");
 7003
 7004        for highlighted_chunk in chunks.chain([HighlightedChunk {
 7005            text: "\n",
 7006            style: None,
 7007            is_tab: false,
 7008            is_inlay: false,
 7009            replacement: None,
 7010        }]) {
 7011            if let Some(replacement) = highlighted_chunk.replacement {
 7012                if !line.is_empty() {
 7013                    let shaped_line =
 7014                        window
 7015                            .text_system()
 7016                            .shape_line(line.clone().into(), font_size, &styles);
 7017                    width += shaped_line.width;
 7018                    len += shaped_line.len;
 7019                    fragments.push(LineFragment::Text(shaped_line));
 7020                    line.clear();
 7021                    styles.clear();
 7022                }
 7023
 7024                match replacement {
 7025                    ChunkReplacement::Renderer(renderer) => {
 7026                        let available_width = if renderer.constrain_width {
 7027                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
 7028                                ellipsis.clone()
 7029                            } else {
 7030                                SharedString::from(Arc::from(highlighted_chunk.text))
 7031                            };
 7032                            let shaped_line = window.text_system().shape_line(
 7033                                chunk,
 7034                                font_size,
 7035                                &[text_style.to_run(highlighted_chunk.text.len())],
 7036                            );
 7037                            AvailableSpace::Definite(shaped_line.width)
 7038                        } else {
 7039                            AvailableSpace::MinContent
 7040                        };
 7041
 7042                        let mut element = (renderer.render)(&mut ChunkRendererContext {
 7043                            context: cx,
 7044                            window,
 7045                            max_width: text_width,
 7046                        });
 7047                        let line_height = text_style.line_height_in_pixels(window.rem_size());
 7048                        let size = element.layout_as_root(
 7049                            size(available_width, AvailableSpace::Definite(line_height)),
 7050                            window,
 7051                            cx,
 7052                        );
 7053
 7054                        width += size.width;
 7055                        len += highlighted_chunk.text.len();
 7056                        fragments.push(LineFragment::Element {
 7057                            id: renderer.id,
 7058                            element: Some(element),
 7059                            size,
 7060                            len: highlighted_chunk.text.len(),
 7061                        });
 7062                    }
 7063                    ChunkReplacement::Str(x) => {
 7064                        let text_style = if let Some(style) = highlighted_chunk.style {
 7065                            Cow::Owned(text_style.clone().highlight(style))
 7066                        } else {
 7067                            Cow::Borrowed(text_style)
 7068                        };
 7069
 7070                        let run = TextRun {
 7071                            len: x.len(),
 7072                            font: text_style.font(),
 7073                            color: text_style.color,
 7074                            background_color: text_style.background_color,
 7075                            underline: text_style.underline,
 7076                            strikethrough: text_style.strikethrough,
 7077                        };
 7078                        let line_layout = window
 7079                            .text_system()
 7080                            .shape_line(x, font_size, &[run])
 7081                            .with_len(highlighted_chunk.text.len());
 7082
 7083                        width += line_layout.width;
 7084                        len += highlighted_chunk.text.len();
 7085                        fragments.push(LineFragment::Text(line_layout))
 7086                    }
 7087                }
 7088            } else {
 7089                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
 7090                    if ix > 0 {
 7091                        let shaped_line = window.text_system().shape_line(
 7092                            line.clone().into(),
 7093                            font_size,
 7094                            &styles,
 7095                        );
 7096                        width += shaped_line.width;
 7097                        len += shaped_line.len;
 7098                        fragments.push(LineFragment::Text(shaped_line));
 7099                        layouts.push(Self {
 7100                            width: mem::take(&mut width),
 7101                            len: mem::take(&mut len),
 7102                            fragments: mem::take(&mut fragments),
 7103                            invisibles: std::mem::take(&mut invisibles),
 7104                            font_size,
 7105                        });
 7106
 7107                        line.clear();
 7108                        styles.clear();
 7109                        row += 1;
 7110                        line_exceeded_max_len = false;
 7111                        non_whitespace_added = false;
 7112                        if row == max_line_count {
 7113                            return layouts;
 7114                        }
 7115                    }
 7116
 7117                    if !line_chunk.is_empty() && !line_exceeded_max_len {
 7118                        let text_style = if let Some(style) = highlighted_chunk.style {
 7119                            Cow::Owned(text_style.clone().highlight(style))
 7120                        } else {
 7121                            Cow::Borrowed(text_style)
 7122                        };
 7123
 7124                        if line.len() + line_chunk.len() > max_line_len {
 7125                            let mut chunk_len = max_line_len - line.len();
 7126                            while !line_chunk.is_char_boundary(chunk_len) {
 7127                                chunk_len -= 1;
 7128                            }
 7129                            line_chunk = &line_chunk[..chunk_len];
 7130                            line_exceeded_max_len = true;
 7131                        }
 7132
 7133                        styles.push(TextRun {
 7134                            len: line_chunk.len(),
 7135                            font: text_style.font(),
 7136                            color: text_style.color,
 7137                            background_color: text_style.background_color,
 7138                            underline: text_style.underline,
 7139                            strikethrough: text_style.strikethrough,
 7140                        });
 7141
 7142                        if editor_mode.is_full() && !highlighted_chunk.is_inlay {
 7143                            // Line wrap pads its contents with fake whitespaces,
 7144                            // avoid printing them
 7145                            let is_soft_wrapped = is_row_soft_wrapped(row);
 7146                            if highlighted_chunk.is_tab {
 7147                                if non_whitespace_added || !is_soft_wrapped {
 7148                                    invisibles.push(Invisible::Tab {
 7149                                        line_start_offset: line.len(),
 7150                                        line_end_offset: line.len() + line_chunk.len(),
 7151                                    });
 7152                                }
 7153                            } else {
 7154                                invisibles.extend(line_chunk.char_indices().filter_map(
 7155                                    |(index, c)| {
 7156                                        let is_whitespace = c.is_whitespace();
 7157                                        non_whitespace_added |= !is_whitespace;
 7158                                        if is_whitespace
 7159                                            && (non_whitespace_added || !is_soft_wrapped)
 7160                                        {
 7161                                            Some(Invisible::Whitespace {
 7162                                                line_offset: line.len() + index,
 7163                                            })
 7164                                        } else {
 7165                                            None
 7166                                        }
 7167                                    },
 7168                                ))
 7169                            }
 7170                        }
 7171
 7172                        line.push_str(line_chunk);
 7173                    }
 7174                }
 7175            }
 7176        }
 7177
 7178        layouts
 7179    }
 7180
 7181    fn prepaint(
 7182        &mut self,
 7183        line_height: Pixels,
 7184        scroll_pixel_position: gpui::Point<Pixels>,
 7185        row: DisplayRow,
 7186        content_origin: gpui::Point<Pixels>,
 7187        line_elements: &mut SmallVec<[AnyElement; 1]>,
 7188        window: &mut Window,
 7189        cx: &mut App,
 7190    ) {
 7191        let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
 7192        let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
 7193        for fragment in &mut self.fragments {
 7194            match fragment {
 7195                LineFragment::Text(line) => {
 7196                    fragment_origin.x += line.width;
 7197                }
 7198                LineFragment::Element { element, size, .. } => {
 7199                    let mut element = element
 7200                        .take()
 7201                        .expect("you can't prepaint LineWithInvisibles twice");
 7202
 7203                    // Center the element vertically within the line.
 7204                    let mut element_origin = fragment_origin;
 7205                    element_origin.y += (line_height - size.height) / 2.;
 7206                    element.prepaint_at(element_origin, window, cx);
 7207                    line_elements.push(element);
 7208
 7209                    fragment_origin.x += size.width;
 7210                }
 7211            }
 7212        }
 7213    }
 7214
 7215    fn draw(
 7216        &self,
 7217        layout: &EditorLayout,
 7218        row: DisplayRow,
 7219        content_origin: gpui::Point<Pixels>,
 7220        whitespace_setting: ShowWhitespaceSetting,
 7221        selection_ranges: &[Range<DisplayPoint>],
 7222        window: &mut Window,
 7223        cx: &mut App,
 7224    ) {
 7225        let line_height = layout.position_map.line_height;
 7226        let line_y = line_height
 7227            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
 7228
 7229        let mut fragment_origin =
 7230            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
 7231
 7232        for fragment in &self.fragments {
 7233            match fragment {
 7234                LineFragment::Text(line) => {
 7235                    line.paint(fragment_origin, line_height, window, cx)
 7236                        .log_err();
 7237                    fragment_origin.x += line.width;
 7238                }
 7239                LineFragment::Element { size, .. } => {
 7240                    fragment_origin.x += size.width;
 7241                }
 7242            }
 7243        }
 7244
 7245        self.draw_invisibles(
 7246            selection_ranges,
 7247            layout,
 7248            content_origin,
 7249            line_y,
 7250            row,
 7251            line_height,
 7252            whitespace_setting,
 7253            window,
 7254            cx,
 7255        );
 7256    }
 7257
 7258    fn draw_background(
 7259        &self,
 7260        layout: &EditorLayout,
 7261        row: DisplayRow,
 7262        content_origin: gpui::Point<Pixels>,
 7263        window: &mut Window,
 7264        cx: &mut App,
 7265    ) {
 7266        let line_height = layout.position_map.line_height;
 7267        let line_y = line_height
 7268            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
 7269
 7270        let mut fragment_origin =
 7271            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
 7272
 7273        for fragment in &self.fragments {
 7274            match fragment {
 7275                LineFragment::Text(line) => {
 7276                    line.paint_background(fragment_origin, line_height, window, cx)
 7277                        .log_err();
 7278                    fragment_origin.x += line.width;
 7279                }
 7280                LineFragment::Element { size, .. } => {
 7281                    fragment_origin.x += size.width;
 7282                }
 7283            }
 7284        }
 7285    }
 7286
 7287    fn draw_invisibles(
 7288        &self,
 7289        selection_ranges: &[Range<DisplayPoint>],
 7290        layout: &EditorLayout,
 7291        content_origin: gpui::Point<Pixels>,
 7292        line_y: Pixels,
 7293        row: DisplayRow,
 7294        line_height: Pixels,
 7295        whitespace_setting: ShowWhitespaceSetting,
 7296        window: &mut Window,
 7297        cx: &mut App,
 7298    ) {
 7299        let extract_whitespace_info = |invisible: &Invisible| {
 7300            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
 7301                Invisible::Tab {
 7302                    line_start_offset,
 7303                    line_end_offset,
 7304                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
 7305                Invisible::Whitespace { line_offset } => {
 7306                    (*line_offset, line_offset + 1, &layout.space_invisible)
 7307                }
 7308            };
 7309
 7310            let x_offset = self.x_for_index(token_offset);
 7311            let invisible_offset =
 7312                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
 7313            let origin = content_origin
 7314                + gpui::point(
 7315                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
 7316                    line_y,
 7317                );
 7318
 7319            (
 7320                [token_offset, token_end_offset],
 7321                Box::new(move |window: &mut Window, cx: &mut App| {
 7322                    invisible_symbol
 7323                        .paint(origin, line_height, window, cx)
 7324                        .log_err();
 7325                }),
 7326            )
 7327        };
 7328
 7329        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
 7330        match whitespace_setting {
 7331            ShowWhitespaceSetting::None => (),
 7332            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
 7333            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
 7334                let invisible_point = DisplayPoint::new(row, start as u32);
 7335                if !selection_ranges
 7336                    .iter()
 7337                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
 7338                {
 7339                    return;
 7340                }
 7341
 7342                paint(window, cx);
 7343            }),
 7344
 7345            ShowWhitespaceSetting::Trailing => {
 7346                let mut previous_start = self.len;
 7347                for ([start, end], paint) in invisible_iter.rev() {
 7348                    if previous_start != end {
 7349                        break;
 7350                    }
 7351                    previous_start = start;
 7352                    paint(window, cx);
 7353                }
 7354            }
 7355
 7356            // For a whitespace to be on a boundary, any of the following conditions need to be met:
 7357            // - It is a tab
 7358            // - It is adjacent to an edge (start or end)
 7359            // - It is adjacent to a whitespace (left or right)
 7360            ShowWhitespaceSetting::Boundary => {
 7361                // 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
 7362                // the above cases.
 7363                // Note: We zip in the original `invisibles` to check for tab equality
 7364                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
 7365                for (([start, end], paint), invisible) in
 7366                    invisible_iter.zip_eq(self.invisibles.iter())
 7367                {
 7368                    let should_render = match (&last_seen, invisible) {
 7369                        (_, Invisible::Tab { .. }) => true,
 7370                        (Some((_, last_end, _)), _) => *last_end == start,
 7371                        _ => false,
 7372                    };
 7373
 7374                    if should_render || start == 0 || end == self.len {
 7375                        paint(window, cx);
 7376
 7377                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
 7378                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
 7379                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
 7380                            // Note that we need to make sure that the last one is actually adjacent
 7381                            if !should_render_last && last_end == start {
 7382                                paint_last(window, cx);
 7383                            }
 7384                        }
 7385                    }
 7386
 7387                    // Manually render anything within a selection
 7388                    let invisible_point = DisplayPoint::new(row, start as u32);
 7389                    if selection_ranges.iter().any(|region| {
 7390                        region.start <= invisible_point && invisible_point < region.end
 7391                    }) {
 7392                        paint(window, cx);
 7393                    }
 7394
 7395                    last_seen = Some((should_render, end, paint));
 7396                }
 7397            }
 7398        }
 7399    }
 7400
 7401    pub fn x_for_index(&self, index: usize) -> Pixels {
 7402        let mut fragment_start_x = Pixels::ZERO;
 7403        let mut fragment_start_index = 0;
 7404
 7405        for fragment in &self.fragments {
 7406            match fragment {
 7407                LineFragment::Text(shaped_line) => {
 7408                    let fragment_end_index = fragment_start_index + shaped_line.len;
 7409                    if index < fragment_end_index {
 7410                        return fragment_start_x
 7411                            + shaped_line.x_for_index(index - fragment_start_index);
 7412                    }
 7413                    fragment_start_x += shaped_line.width;
 7414                    fragment_start_index = fragment_end_index;
 7415                }
 7416                LineFragment::Element { len, size, .. } => {
 7417                    let fragment_end_index = fragment_start_index + len;
 7418                    if index < fragment_end_index {
 7419                        return fragment_start_x;
 7420                    }
 7421                    fragment_start_x += size.width;
 7422                    fragment_start_index = fragment_end_index;
 7423                }
 7424            }
 7425        }
 7426
 7427        fragment_start_x
 7428    }
 7429
 7430    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
 7431        let mut fragment_start_x = Pixels::ZERO;
 7432        let mut fragment_start_index = 0;
 7433
 7434        for fragment in &self.fragments {
 7435            match fragment {
 7436                LineFragment::Text(shaped_line) => {
 7437                    let fragment_end_x = fragment_start_x + shaped_line.width;
 7438                    if x < fragment_end_x {
 7439                        return Some(
 7440                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
 7441                        );
 7442                    }
 7443                    fragment_start_x = fragment_end_x;
 7444                    fragment_start_index += shaped_line.len;
 7445                }
 7446                LineFragment::Element { len, size, .. } => {
 7447                    let fragment_end_x = fragment_start_x + size.width;
 7448                    if x < fragment_end_x {
 7449                        return Some(fragment_start_index);
 7450                    }
 7451                    fragment_start_index += len;
 7452                    fragment_start_x = fragment_end_x;
 7453                }
 7454            }
 7455        }
 7456
 7457        None
 7458    }
 7459
 7460    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
 7461        let mut fragment_start_index = 0;
 7462
 7463        for fragment in &self.fragments {
 7464            match fragment {
 7465                LineFragment::Text(shaped_line) => {
 7466                    let fragment_end_index = fragment_start_index + shaped_line.len;
 7467                    if index < fragment_end_index {
 7468                        return shaped_line.font_id_for_index(index - fragment_start_index);
 7469                    }
 7470                    fragment_start_index = fragment_end_index;
 7471                }
 7472                LineFragment::Element { len, .. } => {
 7473                    let fragment_end_index = fragment_start_index + len;
 7474                    if index < fragment_end_index {
 7475                        return None;
 7476                    }
 7477                    fragment_start_index = fragment_end_index;
 7478                }
 7479            }
 7480        }
 7481
 7482        None
 7483    }
 7484}
 7485
 7486#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 7487enum Invisible {
 7488    /// A tab character
 7489    ///
 7490    /// A tab character is internally represented by spaces (configured by the user's tab width)
 7491    /// aligned to the nearest column, so it's necessary to store the start and end offset for
 7492    /// adjacency checks.
 7493    Tab {
 7494        line_start_offset: usize,
 7495        line_end_offset: usize,
 7496    },
 7497    Whitespace {
 7498        line_offset: usize,
 7499    },
 7500}
 7501
 7502impl EditorElement {
 7503    /// Returns the rem size to use when rendering the [`EditorElement`].
 7504    ///
 7505    /// This allows UI elements to scale based on the `buffer_font_size`.
 7506    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
 7507        match self.editor.read(cx).mode {
 7508            EditorMode::Full {
 7509                scale_ui_elements_with_buffer_font_size: true,
 7510                ..
 7511            }
 7512            | EditorMode::Minimap { .. } => {
 7513                let buffer_font_size = self.style.text.font_size;
 7514                match buffer_font_size {
 7515                    AbsoluteLength::Pixels(pixels) => {
 7516                        let rem_size_scale = {
 7517                            // Our default UI font size is 14px on a 16px base scale.
 7518                            // This means the default UI font size is 0.875rems.
 7519                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
 7520
 7521                            // We then determine the delta between a single rem and the default font
 7522                            // size scale.
 7523                            let default_font_size_delta = 1. - default_font_size_scale;
 7524
 7525                            // Finally, we add this delta to 1rem to get the scale factor that
 7526                            // should be used to scale up the UI.
 7527                            1. + default_font_size_delta
 7528                        };
 7529
 7530                        Some(pixels * rem_size_scale)
 7531                    }
 7532                    AbsoluteLength::Rems(rems) => {
 7533                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
 7534                    }
 7535                }
 7536            }
 7537            // We currently use single-line and auto-height editors in UI contexts,
 7538            // so we don't want to scale everything with the buffer font size, as it
 7539            // ends up looking off.
 7540            _ => None,
 7541        }
 7542    }
 7543
 7544    fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
 7545        if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
 7546            parent.upgrade()
 7547        } else {
 7548            Some(self.editor.clone())
 7549        }
 7550    }
 7551}
 7552
 7553impl Element for EditorElement {
 7554    type RequestLayoutState = ();
 7555    type PrepaintState = EditorLayout;
 7556
 7557    fn id(&self) -> Option<ElementId> {
 7558        None
 7559    }
 7560
 7561    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
 7562        None
 7563    }
 7564
 7565    fn request_layout(
 7566        &mut self,
 7567        _: Option<&GlobalElementId>,
 7568        __inspector_id: Option<&gpui::InspectorElementId>,
 7569        window: &mut Window,
 7570        cx: &mut App,
 7571    ) -> (gpui::LayoutId, ()) {
 7572        let rem_size = self.rem_size(cx);
 7573        window.with_rem_size(rem_size, |window| {
 7574            self.editor.update(cx, |editor, cx| {
 7575                editor.set_style(self.style.clone(), window, cx);
 7576
 7577                let layout_id = match editor.mode {
 7578                    EditorMode::SingleLine { auto_width } => {
 7579                        let rem_size = window.rem_size();
 7580
 7581                        let height = self.style.text.line_height_in_pixels(rem_size);
 7582                        if auto_width {
 7583                            let editor_handle = cx.entity().clone();
 7584                            let style = self.style.clone();
 7585                            window.request_measured_layout(
 7586                                Style::default(),
 7587                                move |_, _, window, cx| {
 7588                                    let editor_snapshot = editor_handle
 7589                                        .update(cx, |editor, cx| editor.snapshot(window, cx));
 7590                                    let line = Self::layout_lines(
 7591                                        DisplayRow(0)..DisplayRow(1),
 7592                                        &editor_snapshot,
 7593                                        &style,
 7594                                        px(f32::MAX),
 7595                                        |_| false, // Single lines never soft wrap
 7596                                        window,
 7597                                        cx,
 7598                                    )
 7599                                    .pop()
 7600                                    .unwrap();
 7601
 7602                                    let font_id =
 7603                                        window.text_system().resolve_font(&style.text.font());
 7604                                    let font_size =
 7605                                        style.text.font_size.to_pixels(window.rem_size());
 7606                                    let em_width =
 7607                                        window.text_system().em_width(font_id, font_size).unwrap();
 7608
 7609                                    size(line.width + em_width, height)
 7610                                },
 7611                            )
 7612                        } else {
 7613                            let mut style = Style::default();
 7614                            style.size.height = height.into();
 7615                            style.size.width = relative(1.).into();
 7616                            window.request_layout(style, None, cx)
 7617                        }
 7618                    }
 7619                    EditorMode::AutoHeight { max_lines } => {
 7620                        let editor_handle = cx.entity().clone();
 7621                        let max_line_number_width =
 7622                            self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
 7623                        window.request_measured_layout(
 7624                            Style::default(),
 7625                            move |known_dimensions, available_space, window, cx| {
 7626                                editor_handle
 7627                                    .update(cx, |editor, cx| {
 7628                                        compute_auto_height_layout(
 7629                                            editor,
 7630                                            max_lines,
 7631                                            max_line_number_width,
 7632                                            known_dimensions,
 7633                                            available_space.width,
 7634                                            window,
 7635                                            cx,
 7636                                        )
 7637                                    })
 7638                                    .unwrap_or_default()
 7639                            },
 7640                        )
 7641                    }
 7642                    EditorMode::Minimap { .. } => {
 7643                        let mut style = Style::default();
 7644                        style.size.width = relative(1.).into();
 7645                        style.size.height = relative(1.).into();
 7646                        window.request_layout(style, None, cx)
 7647                    }
 7648                    EditorMode::Full {
 7649                        sized_by_content, ..
 7650                    } => {
 7651                        let mut style = Style::default();
 7652                        style.size.width = relative(1.).into();
 7653                        if sized_by_content {
 7654                            let snapshot = editor.snapshot(window, cx);
 7655                            let line_height =
 7656                                self.style.text.line_height_in_pixels(window.rem_size());
 7657                            let scroll_height =
 7658                                (snapshot.max_point().row().next_row().0 as f32) * line_height;
 7659                            style.size.height = scroll_height.into();
 7660                        } else {
 7661                            style.size.height = relative(1.).into();
 7662                        }
 7663                        window.request_layout(style, None, cx)
 7664                    }
 7665                };
 7666
 7667                (layout_id, ())
 7668            })
 7669        })
 7670    }
 7671
 7672    fn prepaint(
 7673        &mut self,
 7674        _: Option<&GlobalElementId>,
 7675        _inspector_id: Option<&gpui::InspectorElementId>,
 7676        bounds: Bounds<Pixels>,
 7677        _: &mut Self::RequestLayoutState,
 7678        window: &mut Window,
 7679        cx: &mut App,
 7680    ) -> Self::PrepaintState {
 7681        let text_style = TextStyleRefinement {
 7682            font_size: Some(self.style.text.font_size),
 7683            line_height: Some(self.style.text.line_height),
 7684            ..Default::default()
 7685        };
 7686        let focus_handle = self.editor.focus_handle(cx);
 7687        window.set_view_id(self.editor.entity_id());
 7688        window.set_focus_handle(&focus_handle, cx);
 7689
 7690        let rem_size = self.rem_size(cx);
 7691        window.with_rem_size(rem_size, |window| {
 7692            window.with_text_style(Some(text_style), |window| {
 7693                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 7694                    let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
 7695                        (editor.snapshot(window, cx), editor.read_only(cx))
 7696                    });
 7697                    let style = self.style.clone();
 7698
 7699                    let font_id = window.text_system().resolve_font(&style.text.font());
 7700                    let font_size = style.text.font_size.to_pixels(window.rem_size());
 7701                    let line_height = style.text.line_height_in_pixels(window.rem_size());
 7702                    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
 7703                    let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
 7704
 7705                    let glyph_grid_cell = size(em_width, line_height);
 7706
 7707                    let gutter_dimensions = snapshot
 7708                        .gutter_dimensions(
 7709                            font_id,
 7710                            font_size,
 7711                            self.max_line_number_width(&snapshot, window, cx),
 7712                            cx,
 7713                        )
 7714                        .or_else(|| {
 7715                            self.editor.read(cx).offset_content.then(|| {
 7716                                GutterDimensions::default_with_margin(font_id, font_size, cx)
 7717                            })
 7718                        })
 7719                        .unwrap_or_default();
 7720                    let text_width = bounds.size.width - gutter_dimensions.width;
 7721
 7722                    let settings = EditorSettings::get_global(cx);
 7723                    let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
 7724                    let vertical_scrollbar_width = (scrollbars_shown
 7725                        && settings.scrollbar.axes.vertical
 7726                        && self.editor.read(cx).show_scrollbars.vertical)
 7727                        .then_some(style.scrollbar_width)
 7728                        .unwrap_or_default();
 7729                    let minimap_width = self
 7730                        .editor
 7731                        .read(cx)
 7732                        .minimap()
 7733                        .is_some()
 7734                        .then(|| match settings.minimap.show {
 7735                            ShowMinimap::Auto => {
 7736                                scrollbars_shown.then_some(MinimapLayout::MINIMAP_WIDTH)
 7737                            }
 7738                            _ => Some(MinimapLayout::MINIMAP_WIDTH),
 7739                        })
 7740                        .flatten()
 7741                        .filter(|minimap_width| {
 7742                            text_width - vertical_scrollbar_width - *minimap_width > *minimap_width
 7743                        })
 7744                        .unwrap_or_default();
 7745
 7746                    let right_margin = minimap_width + vertical_scrollbar_width;
 7747
 7748                    let editor_width =
 7749                        text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
 7750
 7751                    let editor_margins = EditorMargins {
 7752                        gutter: gutter_dimensions,
 7753                        right: right_margin,
 7754                    };
 7755
 7756                    // Offset the content_bounds from the text_bounds by the gutter margin (which
 7757                    // is roughly half a character wide) to make hit testing work more like how we want.
 7758                    let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
 7759
 7760                    let editor_content_width = editor_width - content_offset.x;
 7761
 7762                    snapshot = self.editor.update(cx, |editor, cx| {
 7763                        editor.last_bounds = Some(bounds);
 7764                        editor.gutter_dimensions = gutter_dimensions;
 7765                        editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
 7766
 7767                        if matches!(
 7768                            editor.mode,
 7769                            EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
 7770                        ) {
 7771                            snapshot
 7772                        } else {
 7773                            let wrap_width_for = |column: u32| (column as f32 * em_advance).ceil();
 7774                            let wrap_width = match editor.soft_wrap_mode(cx) {
 7775                                SoftWrap::GitDiff => None,
 7776                                SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
 7777                                SoftWrap::EditorWidth => Some(editor_content_width),
 7778                                SoftWrap::Column(column) => Some(wrap_width_for(column)),
 7779                                SoftWrap::Bounded(column) => {
 7780                                    Some(editor_content_width.min(wrap_width_for(column)))
 7781                                }
 7782                            };
 7783
 7784                            if editor.set_wrap_width(wrap_width, cx) {
 7785                                editor.snapshot(window, cx)
 7786                            } else {
 7787                                snapshot
 7788                            }
 7789                        }
 7790                    });
 7791
 7792                    let wrap_guides = self
 7793                        .editor
 7794                        .read(cx)
 7795                        .wrap_guides(cx)
 7796                        .iter()
 7797                        .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
 7798                        .collect::<SmallVec<[_; 2]>>();
 7799
 7800                    let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
 7801                    let gutter_hitbox = window.insert_hitbox(
 7802                        gutter_bounds(bounds, gutter_dimensions),
 7803                        HitboxBehavior::Normal,
 7804                    );
 7805                    let text_hitbox = window.insert_hitbox(
 7806                        Bounds {
 7807                            origin: gutter_hitbox.top_right(),
 7808                            size: size(text_width, bounds.size.height),
 7809                        },
 7810                        HitboxBehavior::Normal,
 7811                    );
 7812
 7813                    let content_origin = text_hitbox.origin + content_offset;
 7814
 7815                    let editor_text_bounds =
 7816                        Bounds::from_corners(content_origin, bounds.bottom_right());
 7817
 7818                    let height_in_lines = editor_text_bounds.size.height / line_height;
 7819
 7820                    let max_row = snapshot.max_point().row().as_f32();
 7821
 7822                    // The max scroll position for the top of the window
 7823                    let max_scroll_top = if matches!(
 7824                        snapshot.mode,
 7825                        EditorMode::SingleLine { .. }
 7826                            | EditorMode::AutoHeight { .. }
 7827                            | EditorMode::Full {
 7828                                sized_by_content: true,
 7829                                ..
 7830                            }
 7831                    ) {
 7832                        (max_row - height_in_lines + 1.).max(0.)
 7833                    } else {
 7834                        let settings = EditorSettings::get_global(cx);
 7835                        match settings.scroll_beyond_last_line {
 7836                            ScrollBeyondLastLine::OnePage => max_row,
 7837                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
 7838                            ScrollBeyondLastLine::VerticalScrollMargin => {
 7839                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
 7840                                    .max(0.)
 7841                            }
 7842                        }
 7843                    };
 7844
 7845                    // TODO: Autoscrolling for both axes
 7846                    let mut autoscroll_request = None;
 7847                    let mut autoscroll_containing_element = false;
 7848                    let mut autoscroll_horizontally = false;
 7849                    self.editor.update(cx, |editor, cx| {
 7850                        autoscroll_request = editor.autoscroll_request();
 7851                        autoscroll_containing_element =
 7852                            autoscroll_request.is_some() || editor.has_pending_selection();
 7853                        // TODO: Is this horizontal or vertical?!
 7854                        autoscroll_horizontally = editor.autoscroll_vertically(
 7855                            bounds,
 7856                            line_height,
 7857                            max_scroll_top,
 7858                            window,
 7859                            cx,
 7860                        );
 7861                        snapshot = editor.snapshot(window, cx);
 7862                    });
 7863
 7864                    let mut scroll_position = snapshot.scroll_position();
 7865                    // The scroll position is a fractional point, the whole number of which represents
 7866                    // the top of the window in terms of display rows.
 7867                    let start_row = DisplayRow(scroll_position.y as u32);
 7868                    let max_row = snapshot.max_point().row();
 7869                    let end_row = cmp::min(
 7870                        (scroll_position.y + height_in_lines).ceil() as u32,
 7871                        max_row.next_row().0,
 7872                    );
 7873                    let end_row = DisplayRow(end_row);
 7874
 7875                    let row_infos = snapshot
 7876                        .row_infos(start_row)
 7877                        .take((start_row..end_row).len())
 7878                        .collect::<Vec<RowInfo>>();
 7879                    let is_row_soft_wrapped = |row: usize| {
 7880                        row_infos
 7881                            .get(row)
 7882                            .map_or(true, |info| info.buffer_row.is_none())
 7883                    };
 7884
 7885                    let start_anchor = if start_row == Default::default() {
 7886                        Anchor::min()
 7887                    } else {
 7888                        snapshot.buffer_snapshot.anchor_before(
 7889                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
 7890                        )
 7891                    };
 7892                    let end_anchor = if end_row > max_row {
 7893                        Anchor::max()
 7894                    } else {
 7895                        snapshot.buffer_snapshot.anchor_before(
 7896                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
 7897                        )
 7898                    };
 7899
 7900                    let mut highlighted_rows = self
 7901                        .editor
 7902                        .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
 7903
 7904                    let is_light = cx.theme().appearance().is_light();
 7905
 7906                    for (ix, row_info) in row_infos.iter().enumerate() {
 7907                        let Some(diff_status) = row_info.diff_status else {
 7908                            continue;
 7909                        };
 7910
 7911                        let background_color = match diff_status.kind {
 7912                            DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
 7913                            DiffHunkStatusKind::Deleted => {
 7914                                cx.theme().colors().version_control_deleted
 7915                            }
 7916                            DiffHunkStatusKind::Modified => {
 7917                                debug_panic!("modified diff status for row info");
 7918                                continue;
 7919                            }
 7920                        };
 7921
 7922                        let hunk_opacity = if is_light { 0.16 } else { 0.12 };
 7923
 7924                        let hollow_highlight = LineHighlight {
 7925                            background: (background_color.opacity(if is_light {
 7926                                0.08
 7927                            } else {
 7928                                0.06
 7929                            }))
 7930                            .into(),
 7931                            border: Some(if is_light {
 7932                                background_color.opacity(0.48)
 7933                            } else {
 7934                                background_color.opacity(0.36)
 7935                            }),
 7936                            include_gutter: true,
 7937                            type_id: None,
 7938                        };
 7939
 7940                        let filled_highlight = LineHighlight {
 7941                            background: solid_background(background_color.opacity(hunk_opacity)),
 7942                            border: None,
 7943                            include_gutter: true,
 7944                            type_id: None,
 7945                        };
 7946
 7947                        let background = if Self::diff_hunk_hollow(diff_status, cx) {
 7948                            hollow_highlight
 7949                        } else {
 7950                            filled_highlight
 7951                        };
 7952
 7953                        highlighted_rows
 7954                            .entry(start_row + DisplayRow(ix as u32))
 7955                            .or_insert(background);
 7956                    }
 7957
 7958                    let highlighted_ranges = self
 7959                        .editor_with_selections(cx)
 7960                        .map(|editor| {
 7961                            editor.read(cx).background_highlights_in_range(
 7962                                start_anchor..end_anchor,
 7963                                &snapshot.display_snapshot,
 7964                                cx.theme(),
 7965                            )
 7966                        })
 7967                        .unwrap_or_default();
 7968                    let highlighted_gutter_ranges =
 7969                        self.editor.read(cx).gutter_highlights_in_range(
 7970                            start_anchor..end_anchor,
 7971                            &snapshot.display_snapshot,
 7972                            cx,
 7973                        );
 7974
 7975                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
 7976                        start_anchor..end_anchor,
 7977                        &snapshot.display_snapshot,
 7978                        cx,
 7979                    );
 7980
 7981                    let (local_selections, selected_buffer_ids): (
 7982                        Vec<Selection<Point>>,
 7983                        Vec<BufferId>,
 7984                    ) = self
 7985                        .editor_with_selections(cx)
 7986                        .map(|editor| {
 7987                            editor.update(cx, |editor, cx| {
 7988                                let all_selections = editor.selections.all::<Point>(cx);
 7989                                let selected_buffer_ids = if editor.is_singleton(cx) {
 7990                                    Vec::new()
 7991                                } else {
 7992                                    let mut selected_buffer_ids =
 7993                                        Vec::with_capacity(all_selections.len());
 7994
 7995                                    for selection in all_selections {
 7996                                        for buffer_id in snapshot
 7997                                            .buffer_snapshot
 7998                                            .buffer_ids_for_range(selection.range())
 7999                                        {
 8000                                            if selected_buffer_ids.last() != Some(&buffer_id) {
 8001                                                selected_buffer_ids.push(buffer_id);
 8002                                            }
 8003                                        }
 8004                                    }
 8005
 8006                                    selected_buffer_ids
 8007                                };
 8008
 8009                                let mut selections = editor
 8010                                    .selections
 8011                                    .disjoint_in_range(start_anchor..end_anchor, cx);
 8012                                selections.extend(editor.selections.pending(cx));
 8013
 8014                                (selections, selected_buffer_ids)
 8015                            })
 8016                        })
 8017                        .unwrap_or_default();
 8018
 8019                    let (selections, mut active_rows, newest_selection_head) = self
 8020                        .layout_selections(
 8021                            start_anchor,
 8022                            end_anchor,
 8023                            &local_selections,
 8024                            &snapshot,
 8025                            start_row,
 8026                            end_row,
 8027                            window,
 8028                            cx,
 8029                        );
 8030                    let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
 8031                        editor.active_breakpoints(start_row..end_row, window, cx)
 8032                    });
 8033                    if cx.has_flag::<DebuggerFeatureFlag>() {
 8034                        for (display_row, (_, bp, state)) in &breakpoint_rows {
 8035                            if bp.is_enabled() && state.is_none_or(|s| s.verified) {
 8036                                active_rows.entry(*display_row).or_default().breakpoint = true;
 8037                            }
 8038                        }
 8039                    }
 8040
 8041                    let line_numbers = self.layout_line_numbers(
 8042                        Some(&gutter_hitbox),
 8043                        gutter_dimensions,
 8044                        line_height,
 8045                        scroll_position,
 8046                        start_row..end_row,
 8047                        &row_infos,
 8048                        &active_rows,
 8049                        newest_selection_head,
 8050                        &snapshot,
 8051                        window,
 8052                        cx,
 8053                    );
 8054
 8055                    // We add the gutter breakpoint indicator to breakpoint_rows after painting
 8056                    // line numbers so we don't paint a line number debug accent color if a user
 8057                    // has their mouse over that line when a breakpoint isn't there
 8058                    if cx.has_flag::<DebuggerFeatureFlag>() {
 8059                        self.editor.update(cx, |editor, _| {
 8060                            if let Some(phantom_breakpoint) = &mut editor
 8061                                .gutter_breakpoint_indicator
 8062                                .0
 8063                                .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
 8064                            {
 8065                                // Is there a non-phantom breakpoint on this line?
 8066                                phantom_breakpoint.collides_with_existing_breakpoint = true;
 8067                                breakpoint_rows
 8068                                    .entry(phantom_breakpoint.display_row)
 8069                                    .or_insert_with(|| {
 8070                                        let position = snapshot.display_point_to_anchor(
 8071                                            DisplayPoint::new(phantom_breakpoint.display_row, 0),
 8072                                            Bias::Right,
 8073                                        );
 8074                                        let breakpoint = Breakpoint::new_standard();
 8075                                        phantom_breakpoint.collides_with_existing_breakpoint =
 8076                                            false;
 8077                                        (position, breakpoint, None)
 8078                                    });
 8079                            }
 8080                        })
 8081                    }
 8082
 8083                    let mut expand_toggles =
 8084                        window.with_element_namespace("expand_toggles", |window| {
 8085                            self.layout_expand_toggles(
 8086                                &gutter_hitbox,
 8087                                gutter_dimensions,
 8088                                em_width,
 8089                                line_height,
 8090                                scroll_position,
 8091                                &row_infos,
 8092                                window,
 8093                                cx,
 8094                            )
 8095                        });
 8096
 8097                    let mut crease_toggles =
 8098                        window.with_element_namespace("crease_toggles", |window| {
 8099                            self.layout_crease_toggles(
 8100                                start_row..end_row,
 8101                                &row_infos,
 8102                                &active_rows,
 8103                                &snapshot,
 8104                                window,
 8105                                cx,
 8106                            )
 8107                        });
 8108                    let crease_trailers =
 8109                        window.with_element_namespace("crease_trailers", |window| {
 8110                            self.layout_crease_trailers(
 8111                                row_infos.iter().copied(),
 8112                                &snapshot,
 8113                                window,
 8114                                cx,
 8115                            )
 8116                        });
 8117
 8118                    let display_hunks = self.layout_gutter_diff_hunks(
 8119                        line_height,
 8120                        &gutter_hitbox,
 8121                        start_row..end_row,
 8122                        &snapshot,
 8123                        window,
 8124                        cx,
 8125                    );
 8126
 8127                    let mut line_layouts = Self::layout_lines(
 8128                        start_row..end_row,
 8129                        &snapshot,
 8130                        &self.style,
 8131                        editor_width,
 8132                        is_row_soft_wrapped,
 8133                        window,
 8134                        cx,
 8135                    );
 8136                    let new_fold_widths = line_layouts
 8137                        .iter()
 8138                        .flat_map(|layout| &layout.fragments)
 8139                        .filter_map(|fragment| {
 8140                            if let LineFragment::Element { id, size, .. } = fragment {
 8141                                Some((*id, size.width))
 8142                            } else {
 8143                                None
 8144                            }
 8145                        });
 8146                    if self.editor.update(cx, |editor, cx| {
 8147                        editor.update_fold_widths(new_fold_widths, cx)
 8148                    }) {
 8149                        // If the fold widths have changed, we need to prepaint
 8150                        // the element again to account for any changes in
 8151                        // wrapping.
 8152                        return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
 8153                    }
 8154
 8155                    let longest_line_blame_width = self
 8156                        .editor
 8157                        .update(cx, |editor, cx| {
 8158                            if !editor.show_git_blame_inline {
 8159                                return None;
 8160                            }
 8161                            let blame = editor.blame.as_ref()?;
 8162                            let blame_entry = blame
 8163                                .update(cx, |blame, cx| {
 8164                                    let row_infos =
 8165                                        snapshot.row_infos(snapshot.longest_row()).next()?;
 8166                                    blame.blame_for_rows(&[row_infos], cx).next()
 8167                                })
 8168                                .flatten()?;
 8169                            let mut element = render_inline_blame_entry(blame_entry, &style, cx)?;
 8170                            let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
 8171                            Some(
 8172                                element
 8173                                    .layout_as_root(AvailableSpace::min_size(), window, cx)
 8174                                    .width
 8175                                    + inline_blame_padding,
 8176                            )
 8177                        })
 8178                        .unwrap_or(Pixels::ZERO);
 8179
 8180                    let longest_line_width = layout_line(
 8181                        snapshot.longest_row(),
 8182                        &snapshot,
 8183                        &style,
 8184                        editor_width,
 8185                        is_row_soft_wrapped,
 8186                        window,
 8187                        cx,
 8188                    )
 8189                    .width;
 8190
 8191                    let scrollbar_layout_information = ScrollbarLayoutInformation::new(
 8192                        text_hitbox.bounds,
 8193                        glyph_grid_cell,
 8194                        size(longest_line_width, max_row.as_f32() * line_height),
 8195                        longest_line_blame_width,
 8196                        editor_width,
 8197                        EditorSettings::get_global(cx),
 8198                    );
 8199
 8200                    let mut scroll_width = scrollbar_layout_information.scroll_range.width;
 8201
 8202                    let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
 8203                        snapshot.sticky_header_excerpt(scroll_position.y)
 8204                    } else {
 8205                        None
 8206                    };
 8207                    let sticky_header_excerpt_id =
 8208                        sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
 8209
 8210                    let blocks = window.with_element_namespace("blocks", |window| {
 8211                        self.render_blocks(
 8212                            start_row..end_row,
 8213                            &snapshot,
 8214                            &hitbox,
 8215                            &text_hitbox,
 8216                            editor_width,
 8217                            &mut scroll_width,
 8218                            &editor_margins,
 8219                            em_width,
 8220                            gutter_dimensions.full_width(),
 8221                            line_height,
 8222                            &mut line_layouts,
 8223                            &local_selections,
 8224                            &selected_buffer_ids,
 8225                            is_row_soft_wrapped,
 8226                            sticky_header_excerpt_id,
 8227                            window,
 8228                            cx,
 8229                        )
 8230                    });
 8231                    let (mut blocks, row_block_types) = match blocks {
 8232                        Ok(blocks) => blocks,
 8233                        Err(resized_blocks) => {
 8234                            self.editor.update(cx, |editor, cx| {
 8235                                editor.resize_blocks(resized_blocks, autoscroll_request, cx)
 8236                            });
 8237                            return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
 8238                        }
 8239                    };
 8240
 8241                    let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
 8242                        window.with_element_namespace("blocks", |window| {
 8243                            self.layout_sticky_buffer_header(
 8244                                sticky_header_excerpt,
 8245                                scroll_position.y,
 8246                                line_height,
 8247                                right_margin,
 8248                                &snapshot,
 8249                                &hitbox,
 8250                                &selected_buffer_ids,
 8251                                &blocks,
 8252                                window,
 8253                                cx,
 8254                            )
 8255                        })
 8256                    });
 8257
 8258                    let start_buffer_row =
 8259                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
 8260                    let end_buffer_row =
 8261                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
 8262
 8263                    let scroll_max = point(
 8264                        ((scroll_width - editor_content_width) / em_width).max(0.0),
 8265                        max_scroll_top,
 8266                    );
 8267
 8268                    self.editor.update(cx, |editor, cx| {
 8269                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
 8270
 8271                        let autoscrolled = if autoscroll_horizontally {
 8272                            editor.autoscroll_horizontally(
 8273                                start_row,
 8274                                editor_content_width,
 8275                                scroll_width,
 8276                                em_width,
 8277                                &line_layouts,
 8278                                cx,
 8279                            )
 8280                        } else {
 8281                            false
 8282                        };
 8283
 8284                        if clamped || autoscrolled {
 8285                            snapshot = editor.snapshot(window, cx);
 8286                            scroll_position = snapshot.scroll_position();
 8287                        }
 8288                    });
 8289
 8290                    let scroll_pixel_position = point(
 8291                        scroll_position.x * em_width,
 8292                        scroll_position.y * line_height,
 8293                    );
 8294
 8295                    let indent_guides = self.layout_indent_guides(
 8296                        content_origin,
 8297                        text_hitbox.origin,
 8298                        start_buffer_row..end_buffer_row,
 8299                        scroll_pixel_position,
 8300                        line_height,
 8301                        &snapshot,
 8302                        window,
 8303                        cx,
 8304                    );
 8305
 8306                    let crease_trailers =
 8307                        window.with_element_namespace("crease_trailers", |window| {
 8308                            self.prepaint_crease_trailers(
 8309                                crease_trailers,
 8310                                &line_layouts,
 8311                                line_height,
 8312                                content_origin,
 8313                                scroll_pixel_position,
 8314                                em_width,
 8315                                window,
 8316                                cx,
 8317                            )
 8318                        });
 8319
 8320                    let (inline_completion_popover, inline_completion_popover_origin) = self
 8321                        .editor
 8322                        .update(cx, |editor, cx| {
 8323                            editor.render_edit_prediction_popover(
 8324                                &text_hitbox.bounds,
 8325                                content_origin,
 8326                                right_margin,
 8327                                &snapshot,
 8328                                start_row..end_row,
 8329                                scroll_position.y,
 8330                                scroll_position.y + height_in_lines,
 8331                                &line_layouts,
 8332                                line_height,
 8333                                scroll_pixel_position,
 8334                                newest_selection_head,
 8335                                editor_width,
 8336                                &style,
 8337                                window,
 8338                                cx,
 8339                            )
 8340                        })
 8341                        .unzip();
 8342
 8343                    let mut inline_diagnostics = self.layout_inline_diagnostics(
 8344                        &line_layouts,
 8345                        &crease_trailers,
 8346                        &row_block_types,
 8347                        content_origin,
 8348                        scroll_pixel_position,
 8349                        inline_completion_popover_origin,
 8350                        start_row,
 8351                        end_row,
 8352                        line_height,
 8353                        em_width,
 8354                        &style,
 8355                        window,
 8356                        cx,
 8357                    );
 8358
 8359                    let mut inline_blame = None;
 8360                    let mut inline_code_actions = None;
 8361                    if let Some(newest_selection_head) = newest_selection_head {
 8362                        let display_row = newest_selection_head.row();
 8363                        if (start_row..end_row).contains(&display_row)
 8364                            && !row_block_types.contains_key(&display_row)
 8365                        {
 8366                            inline_code_actions = self.layout_inline_code_actions(
 8367                                newest_selection_head,
 8368                                content_origin,
 8369                                scroll_pixel_position,
 8370                                line_height,
 8371                                &snapshot,
 8372                                window,
 8373                                cx,
 8374                            );
 8375
 8376                            let line_ix = display_row.minus(start_row) as usize;
 8377                            let row_info = &row_infos[line_ix];
 8378                            let line_layout = &line_layouts[line_ix];
 8379                            let crease_trailer_layout = crease_trailers[line_ix].as_ref();
 8380
 8381                            inline_blame = self.layout_inline_blame(
 8382                                display_row,
 8383                                row_info,
 8384                                line_layout,
 8385                                crease_trailer_layout,
 8386                                em_width,
 8387                                content_origin,
 8388                                scroll_pixel_position,
 8389                                line_height,
 8390                                &text_hitbox,
 8391                                window,
 8392                                cx,
 8393                            );
 8394                            if inline_blame.is_some() {
 8395                                // Blame overrides inline diagnostics
 8396                                inline_diagnostics.remove(&display_row);
 8397                            }
 8398                        }
 8399                    }
 8400
 8401                    let blamed_display_rows = self.layout_blame_entries(
 8402                        &row_infos,
 8403                        em_width,
 8404                        scroll_position,
 8405                        line_height,
 8406                        &gutter_hitbox,
 8407                        gutter_dimensions.git_blame_entries_width,
 8408                        window,
 8409                        cx,
 8410                    );
 8411
 8412                    self.editor.update(cx, |editor, cx| {
 8413                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
 8414
 8415                        let autoscrolled = if autoscroll_horizontally {
 8416                            editor.autoscroll_horizontally(
 8417                                start_row,
 8418                                editor_content_width,
 8419                                scroll_width,
 8420                                em_width,
 8421                                &line_layouts,
 8422                                cx,
 8423                            )
 8424                        } else {
 8425                            false
 8426                        };
 8427
 8428                        if clamped || autoscrolled {
 8429                            snapshot = editor.snapshot(window, cx);
 8430                            scroll_position = snapshot.scroll_position();
 8431                        }
 8432                    });
 8433
 8434                    let line_elements = self.prepaint_lines(
 8435                        start_row,
 8436                        &mut line_layouts,
 8437                        line_height,
 8438                        scroll_pixel_position,
 8439                        content_origin,
 8440                        window,
 8441                        cx,
 8442                    );
 8443
 8444                    window.with_element_namespace("blocks", |window| {
 8445                        self.layout_blocks(
 8446                            &mut blocks,
 8447                            &hitbox,
 8448                            line_height,
 8449                            scroll_pixel_position,
 8450                            window,
 8451                            cx,
 8452                        );
 8453                    });
 8454
 8455                    let cursors = self.collect_cursors(&snapshot, cx);
 8456                    let visible_row_range = start_row..end_row;
 8457                    let non_visible_cursors = cursors
 8458                        .iter()
 8459                        .any(|c| !visible_row_range.contains(&c.0.row()));
 8460
 8461                    let visible_cursors = self.layout_visible_cursors(
 8462                        &snapshot,
 8463                        &selections,
 8464                        &row_block_types,
 8465                        start_row..end_row,
 8466                        &line_layouts,
 8467                        &text_hitbox,
 8468                        content_origin,
 8469                        scroll_position,
 8470                        scroll_pixel_position,
 8471                        line_height,
 8472                        em_width,
 8473                        em_advance,
 8474                        autoscroll_containing_element,
 8475                        window,
 8476                        cx,
 8477                    );
 8478
 8479                    let scrollbars_layout = self.layout_scrollbars(
 8480                        &snapshot,
 8481                        &scrollbar_layout_information,
 8482                        content_offset,
 8483                        scroll_position,
 8484                        non_visible_cursors,
 8485                        right_margin,
 8486                        editor_width,
 8487                        window,
 8488                        cx,
 8489                    );
 8490
 8491                    let gutter_settings = EditorSettings::get_global(cx).gutter;
 8492
 8493                    let context_menu_layout =
 8494                        if let Some(newest_selection_head) = newest_selection_head {
 8495                            let newest_selection_point =
 8496                                newest_selection_head.to_point(&snapshot.display_snapshot);
 8497                            if (start_row..end_row).contains(&newest_selection_head.row()) {
 8498                                self.layout_cursor_popovers(
 8499                                    line_height,
 8500                                    &text_hitbox,
 8501                                    content_origin,
 8502                                    right_margin,
 8503                                    start_row,
 8504                                    scroll_pixel_position,
 8505                                    &line_layouts,
 8506                                    newest_selection_head,
 8507                                    newest_selection_point,
 8508                                    &style,
 8509                                    window,
 8510                                    cx,
 8511                                )
 8512                            } else {
 8513                                None
 8514                            }
 8515                        } else {
 8516                            None
 8517                        };
 8518
 8519                    self.layout_gutter_menu(
 8520                        line_height,
 8521                        &text_hitbox,
 8522                        content_origin,
 8523                        right_margin,
 8524                        scroll_pixel_position,
 8525                        gutter_dimensions.width - gutter_dimensions.left_padding,
 8526                        window,
 8527                        cx,
 8528                    );
 8529
 8530                    let test_indicators = if gutter_settings.runnables {
 8531                        self.layout_run_indicators(
 8532                            line_height,
 8533                            start_row..end_row,
 8534                            &row_infos,
 8535                            scroll_pixel_position,
 8536                            &gutter_dimensions,
 8537                            &gutter_hitbox,
 8538                            &display_hunks,
 8539                            &snapshot,
 8540                            &mut breakpoint_rows,
 8541                            window,
 8542                            cx,
 8543                        )
 8544                    } else {
 8545                        Vec::new()
 8546                    };
 8547
 8548                    let show_breakpoints = snapshot
 8549                        .show_breakpoints
 8550                        .unwrap_or(gutter_settings.breakpoints);
 8551                    let breakpoints = if cx.has_flag::<DebuggerFeatureFlag>() && show_breakpoints {
 8552                        self.layout_breakpoints(
 8553                            line_height,
 8554                            start_row..end_row,
 8555                            scroll_pixel_position,
 8556                            &gutter_dimensions,
 8557                            &gutter_hitbox,
 8558                            &display_hunks,
 8559                            &snapshot,
 8560                            breakpoint_rows,
 8561                            &row_infos,
 8562                            window,
 8563                            cx,
 8564                        )
 8565                    } else {
 8566                        vec![]
 8567                    };
 8568
 8569                    self.layout_signature_help(
 8570                        &hitbox,
 8571                        content_origin,
 8572                        scroll_pixel_position,
 8573                        newest_selection_head,
 8574                        start_row,
 8575                        &line_layouts,
 8576                        line_height,
 8577                        em_width,
 8578                        context_menu_layout,
 8579                        window,
 8580                        cx,
 8581                    );
 8582
 8583                    if !cx.has_active_drag() {
 8584                        self.layout_hover_popovers(
 8585                            &snapshot,
 8586                            &hitbox,
 8587                            start_row..end_row,
 8588                            content_origin,
 8589                            scroll_pixel_position,
 8590                            &line_layouts,
 8591                            line_height,
 8592                            em_width,
 8593                            context_menu_layout,
 8594                            window,
 8595                            cx,
 8596                        );
 8597                    }
 8598
 8599                    let mouse_context_menu = self.layout_mouse_context_menu(
 8600                        &snapshot,
 8601                        start_row..end_row,
 8602                        content_origin,
 8603                        window,
 8604                        cx,
 8605                    );
 8606
 8607                    window.with_element_namespace("crease_toggles", |window| {
 8608                        self.prepaint_crease_toggles(
 8609                            &mut crease_toggles,
 8610                            line_height,
 8611                            &gutter_dimensions,
 8612                            gutter_settings,
 8613                            scroll_pixel_position,
 8614                            &gutter_hitbox,
 8615                            window,
 8616                            cx,
 8617                        )
 8618                    });
 8619
 8620                    window.with_element_namespace("expand_toggles", |window| {
 8621                        self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
 8622                    });
 8623
 8624                    let minimap = window.with_element_namespace("minimap", |window| {
 8625                        self.layout_minimap(
 8626                            &snapshot,
 8627                            minimap_width,
 8628                            scroll_position,
 8629                            &scrollbar_layout_information,
 8630                            scrollbars_layout.as_ref(),
 8631                            window,
 8632                            cx,
 8633                        )
 8634                    });
 8635
 8636                    let invisible_symbol_font_size = font_size / 2.;
 8637                    let tab_invisible = window.text_system().shape_line(
 8638                        "".into(),
 8639                        invisible_symbol_font_size,
 8640                        &[TextRun {
 8641                            len: "".len(),
 8642                            font: self.style.text.font(),
 8643                            color: cx.theme().colors().editor_invisible,
 8644                            background_color: None,
 8645                            underline: None,
 8646                            strikethrough: None,
 8647                        }],
 8648                    );
 8649                    let space_invisible = window.text_system().shape_line(
 8650                        "".into(),
 8651                        invisible_symbol_font_size,
 8652                        &[TextRun {
 8653                            len: "".len(),
 8654                            font: self.style.text.font(),
 8655                            color: cx.theme().colors().editor_invisible,
 8656                            background_color: None,
 8657                            underline: None,
 8658                            strikethrough: None,
 8659                        }],
 8660                    );
 8661
 8662                    let mode = snapshot.mode.clone();
 8663
 8664                    let position_map = Rc::new(PositionMap {
 8665                        size: bounds.size,
 8666                        visible_row_range,
 8667                        scroll_pixel_position,
 8668                        scroll_max,
 8669                        line_layouts,
 8670                        line_height,
 8671                        em_width,
 8672                        em_advance,
 8673                        snapshot,
 8674                        gutter_hitbox: gutter_hitbox.clone(),
 8675                        text_hitbox: text_hitbox.clone(),
 8676                    });
 8677
 8678                    self.editor.update(cx, |editor, _| {
 8679                        editor.last_position_map = Some(position_map.clone())
 8680                    });
 8681
 8682                    let diff_hunk_controls = if is_read_only {
 8683                        vec![]
 8684                    } else {
 8685                        self.layout_diff_hunk_controls(
 8686                            start_row..end_row,
 8687                            &row_infos,
 8688                            &text_hitbox,
 8689                            &position_map,
 8690                            newest_selection_head,
 8691                            line_height,
 8692                            right_margin,
 8693                            scroll_pixel_position,
 8694                            &display_hunks,
 8695                            &highlighted_rows,
 8696                            self.editor.clone(),
 8697                            window,
 8698                            cx,
 8699                        )
 8700                    };
 8701
 8702                    EditorLayout {
 8703                        mode,
 8704                        position_map,
 8705                        visible_display_row_range: start_row..end_row,
 8706                        wrap_guides,
 8707                        indent_guides,
 8708                        hitbox,
 8709                        gutter_hitbox,
 8710                        display_hunks,
 8711                        content_origin,
 8712                        scrollbars_layout,
 8713                        minimap,
 8714                        active_rows,
 8715                        highlighted_rows,
 8716                        highlighted_ranges,
 8717                        highlighted_gutter_ranges,
 8718                        redacted_ranges,
 8719                        line_elements,
 8720                        line_numbers,
 8721                        blamed_display_rows,
 8722                        inline_diagnostics,
 8723                        inline_blame,
 8724                        inline_code_actions,
 8725                        blocks,
 8726                        cursors,
 8727                        visible_cursors,
 8728                        selections,
 8729                        inline_completion_popover,
 8730                        diff_hunk_controls,
 8731                        mouse_context_menu,
 8732                        test_indicators,
 8733                        breakpoints,
 8734                        crease_toggles,
 8735                        crease_trailers,
 8736                        tab_invisible,
 8737                        space_invisible,
 8738                        sticky_buffer_header,
 8739                        expand_toggles,
 8740                    }
 8741                })
 8742            })
 8743        })
 8744    }
 8745
 8746    fn paint(
 8747        &mut self,
 8748        _: Option<&GlobalElementId>,
 8749        __inspector_id: Option<&gpui::InspectorElementId>,
 8750        bounds: Bounds<gpui::Pixels>,
 8751        _: &mut Self::RequestLayoutState,
 8752        layout: &mut Self::PrepaintState,
 8753        window: &mut Window,
 8754        cx: &mut App,
 8755    ) {
 8756        let focus_handle = self.editor.focus_handle(cx);
 8757        let key_context = self
 8758            .editor
 8759            .update(cx, |editor, cx| editor.key_context(window, cx));
 8760
 8761        window.set_key_context(key_context);
 8762        window.handle_input(
 8763            &focus_handle,
 8764            ElementInputHandler::new(bounds, self.editor.clone()),
 8765            cx,
 8766        );
 8767        self.register_actions(window, cx);
 8768        self.register_key_listeners(window, cx, layout);
 8769
 8770        let text_style = TextStyleRefinement {
 8771            font_size: Some(self.style.text.font_size),
 8772            line_height: Some(self.style.text.line_height),
 8773            ..Default::default()
 8774        };
 8775        let rem_size = self.rem_size(cx);
 8776        window.with_rem_size(rem_size, |window| {
 8777            window.with_text_style(Some(text_style), |window| {
 8778                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 8779                    self.paint_mouse_listeners(layout, window, cx);
 8780                    self.paint_background(layout, window, cx);
 8781                    self.paint_indent_guides(layout, window, cx);
 8782
 8783                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
 8784                        self.paint_blamed_display_rows(layout, window, cx);
 8785                        self.paint_line_numbers(layout, window, cx);
 8786                    }
 8787
 8788                    self.paint_text(layout, window, cx);
 8789
 8790                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
 8791                        self.paint_gutter_highlights(layout, window, cx);
 8792                        self.paint_gutter_indicators(layout, window, cx);
 8793                    }
 8794
 8795                    if !layout.blocks.is_empty() {
 8796                        window.with_element_namespace("blocks", |window| {
 8797                            self.paint_blocks(layout, window, cx);
 8798                        });
 8799                    }
 8800
 8801                    window.with_element_namespace("blocks", |window| {
 8802                        if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
 8803                            sticky_header.paint(window, cx)
 8804                        }
 8805                    });
 8806
 8807                    self.paint_minimap(layout, window, cx);
 8808                    self.paint_scrollbars(layout, window, cx);
 8809                    self.paint_inline_completion_popover(layout, window, cx);
 8810                    self.paint_mouse_context_menu(layout, window, cx);
 8811                });
 8812            })
 8813        })
 8814    }
 8815}
 8816
 8817pub(super) fn gutter_bounds(
 8818    editor_bounds: Bounds<Pixels>,
 8819    gutter_dimensions: GutterDimensions,
 8820) -> Bounds<Pixels> {
 8821    Bounds {
 8822        origin: editor_bounds.origin,
 8823        size: size(gutter_dimensions.width, editor_bounds.size.height),
 8824    }
 8825}
 8826
 8827#[derive(Clone, Copy)]
 8828struct ContextMenuLayout {
 8829    y_flipped: bool,
 8830    bounds: Bounds<Pixels>,
 8831}
 8832
 8833/// Holds information required for layouting the editor scrollbars.
 8834struct ScrollbarLayoutInformation {
 8835    /// The bounds of the editor area (excluding the content offset).
 8836    editor_bounds: Bounds<Pixels>,
 8837    /// The available range to scroll within the document.
 8838    scroll_range: Size<Pixels>,
 8839    /// The space available for one glyph in the editor.
 8840    glyph_grid_cell: Size<Pixels>,
 8841}
 8842
 8843impl ScrollbarLayoutInformation {
 8844    pub fn new(
 8845        editor_bounds: Bounds<Pixels>,
 8846        glyph_grid_cell: Size<Pixels>,
 8847        document_size: Size<Pixels>,
 8848        longest_line_blame_width: Pixels,
 8849        editor_width: Pixels,
 8850        settings: &EditorSettings,
 8851    ) -> Self {
 8852        let vertical_overscroll = match settings.scroll_beyond_last_line {
 8853            ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
 8854            ScrollBeyondLastLine::Off => glyph_grid_cell.height,
 8855            ScrollBeyondLastLine::VerticalScrollMargin => {
 8856                (1.0 + settings.vertical_scroll_margin) * glyph_grid_cell.height
 8857            }
 8858        };
 8859
 8860        let right_margin = if document_size.width + longest_line_blame_width >= editor_width {
 8861            glyph_grid_cell.width
 8862        } else {
 8863            px(0.0)
 8864        };
 8865
 8866        let overscroll = size(right_margin + longest_line_blame_width, vertical_overscroll);
 8867
 8868        let scroll_range = document_size + overscroll;
 8869
 8870        ScrollbarLayoutInformation {
 8871            editor_bounds,
 8872            scroll_range,
 8873            glyph_grid_cell,
 8874        }
 8875    }
 8876}
 8877
 8878impl IntoElement for EditorElement {
 8879    type Element = Self;
 8880
 8881    fn into_element(self) -> Self::Element {
 8882        self
 8883    }
 8884}
 8885
 8886pub struct EditorLayout {
 8887    position_map: Rc<PositionMap>,
 8888    hitbox: Hitbox,
 8889    gutter_hitbox: Hitbox,
 8890    content_origin: gpui::Point<Pixels>,
 8891    scrollbars_layout: Option<EditorScrollbars>,
 8892    minimap: Option<MinimapLayout>,
 8893    mode: EditorMode,
 8894    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
 8895    indent_guides: Option<Vec<IndentGuideLayout>>,
 8896    visible_display_row_range: Range<DisplayRow>,
 8897    active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
 8898    highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
 8899    line_elements: SmallVec<[AnyElement; 1]>,
 8900    line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
 8901    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
 8902    blamed_display_rows: Option<Vec<AnyElement>>,
 8903    inline_diagnostics: HashMap<DisplayRow, AnyElement>,
 8904    inline_blame: Option<AnyElement>,
 8905    inline_code_actions: Option<AnyElement>,
 8906    blocks: Vec<BlockLayout>,
 8907    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
 8908    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
 8909    redacted_ranges: Vec<Range<DisplayPoint>>,
 8910    cursors: Vec<(DisplayPoint, Hsla)>,
 8911    visible_cursors: Vec<CursorLayout>,
 8912    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
 8913    test_indicators: Vec<AnyElement>,
 8914    breakpoints: Vec<AnyElement>,
 8915    crease_toggles: Vec<Option<AnyElement>>,
 8916    expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
 8917    diff_hunk_controls: Vec<AnyElement>,
 8918    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
 8919    inline_completion_popover: Option<AnyElement>,
 8920    mouse_context_menu: Option<AnyElement>,
 8921    tab_invisible: ShapedLine,
 8922    space_invisible: ShapedLine,
 8923    sticky_buffer_header: Option<AnyElement>,
 8924}
 8925
 8926impl EditorLayout {
 8927    fn line_end_overshoot(&self) -> Pixels {
 8928        0.15 * self.position_map.line_height
 8929    }
 8930}
 8931
 8932struct LineNumberLayout {
 8933    shaped_line: ShapedLine,
 8934    hitbox: Option<Hitbox>,
 8935}
 8936
 8937struct ColoredRange<T> {
 8938    start: T,
 8939    end: T,
 8940    color: Hsla,
 8941}
 8942
 8943impl Along for ScrollbarAxes {
 8944    type Unit = bool;
 8945
 8946    fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
 8947        match axis {
 8948            ScrollbarAxis::Horizontal => self.horizontal,
 8949            ScrollbarAxis::Vertical => self.vertical,
 8950        }
 8951    }
 8952
 8953    fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
 8954        match axis {
 8955            ScrollbarAxis::Horizontal => ScrollbarAxes {
 8956                horizontal: f(self.horizontal),
 8957                vertical: self.vertical,
 8958            },
 8959            ScrollbarAxis::Vertical => ScrollbarAxes {
 8960                horizontal: self.horizontal,
 8961                vertical: f(self.vertical),
 8962            },
 8963        }
 8964    }
 8965}
 8966
 8967#[derive(Clone)]
 8968struct EditorScrollbars {
 8969    pub vertical: Option<ScrollbarLayout>,
 8970    pub horizontal: Option<ScrollbarLayout>,
 8971    pub visible: bool,
 8972}
 8973
 8974impl EditorScrollbars {
 8975    pub fn from_scrollbar_axes(
 8976        settings_visibility: ScrollbarAxes,
 8977        layout_information: &ScrollbarLayoutInformation,
 8978        content_offset: gpui::Point<Pixels>,
 8979        scroll_position: gpui::Point<f32>,
 8980        scrollbar_width: Pixels,
 8981        right_margin: Pixels,
 8982        editor_width: Pixels,
 8983        show_scrollbars: bool,
 8984        scrollbar_state: Option<&ActiveScrollbarState>,
 8985        window: &mut Window,
 8986    ) -> Self {
 8987        let ScrollbarLayoutInformation {
 8988            editor_bounds,
 8989            scroll_range,
 8990            glyph_grid_cell,
 8991        } = layout_information;
 8992
 8993        let viewport_size = size(editor_width, editor_bounds.size.height);
 8994
 8995        let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
 8996            ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
 8997                Corner::BottomLeft,
 8998                editor_bounds.bottom_left(),
 8999                size(
 9000                    // The horizontal viewport size differs from the space available for the
 9001                    // horizontal scrollbar, so we have to manually stich it together here.
 9002                    editor_bounds.size.width - right_margin,
 9003                    scrollbar_width,
 9004                ),
 9005            ),
 9006            ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
 9007                Corner::TopRight,
 9008                editor_bounds.top_right(),
 9009                size(scrollbar_width, viewport_size.height),
 9010            ),
 9011        };
 9012
 9013        let mut create_scrollbar_layout = |axis| {
 9014            settings_visibility
 9015                .along(axis)
 9016                .then(|| {
 9017                    (
 9018                        viewport_size.along(axis) - content_offset.along(axis),
 9019                        scroll_range.along(axis),
 9020                    )
 9021                })
 9022                .filter(|(viewport_size, scroll_range)| {
 9023                    // The scrollbar should only be rendered if the content does
 9024                    // not entirely fit into the editor
 9025                    // However, this only applies to the horizontal scrollbar, as information about the
 9026                    // vertical scrollbar layout is always needed for scrollbar diagnostics.
 9027                    axis != ScrollbarAxis::Horizontal || viewport_size < scroll_range
 9028                })
 9029                .map(|(viewport_size, scroll_range)| {
 9030                    ScrollbarLayout::new(
 9031                        window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
 9032                        viewport_size,
 9033                        scroll_range,
 9034                        glyph_grid_cell.along(axis),
 9035                        content_offset.along(axis),
 9036                        scroll_position.along(axis),
 9037                        show_scrollbars,
 9038                        axis,
 9039                    )
 9040                    .with_thumb_state(
 9041                        scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
 9042                    )
 9043                })
 9044        };
 9045
 9046        Self {
 9047            vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
 9048            horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
 9049            visible: show_scrollbars,
 9050        }
 9051    }
 9052
 9053    pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
 9054        [
 9055            (&self.vertical, ScrollbarAxis::Vertical),
 9056            (&self.horizontal, ScrollbarAxis::Horizontal),
 9057        ]
 9058        .into_iter()
 9059        .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
 9060    }
 9061
 9062    /// Returns the currently hovered scrollbar axis, if any.
 9063    pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
 9064        self.iter_scrollbars()
 9065            .find(|s| s.0.hitbox.is_hovered(window))
 9066    }
 9067}
 9068
 9069#[derive(Clone)]
 9070struct ScrollbarLayout {
 9071    hitbox: Hitbox,
 9072    visible_range: Range<f32>,
 9073    text_unit_size: Pixels,
 9074    thumb_bounds: Option<Bounds<Pixels>>,
 9075    thumb_state: ScrollbarThumbState,
 9076}
 9077
 9078impl ScrollbarLayout {
 9079    const BORDER_WIDTH: Pixels = px(1.0);
 9080    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
 9081    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
 9082    const MIN_THUMB_SIZE: Pixels = px(25.0);
 9083
 9084    fn new(
 9085        scrollbar_track_hitbox: Hitbox,
 9086        viewport_size: Pixels,
 9087        scroll_range: Pixels,
 9088        glyph_space: Pixels,
 9089        content_offset: Pixels,
 9090        scroll_position: f32,
 9091        show_thumb: bool,
 9092        axis: ScrollbarAxis,
 9093    ) -> Self {
 9094        let track_bounds = scrollbar_track_hitbox.bounds;
 9095        // The length of the track available to the scrollbar thumb. We deliberately
 9096        // exclude the content size here so that the thumb aligns with the content.
 9097        let track_length = track_bounds.size.along(axis) - content_offset;
 9098
 9099        Self::new_with_hitbox_and_track_length(
 9100            scrollbar_track_hitbox,
 9101            track_length,
 9102            viewport_size,
 9103            scroll_range,
 9104            glyph_space,
 9105            content_offset,
 9106            scroll_position,
 9107            show_thumb,
 9108            axis,
 9109        )
 9110    }
 9111
 9112    fn for_minimap(
 9113        minimap_track_hitbox: Hitbox,
 9114        visible_lines: f32,
 9115        total_editor_lines: f32,
 9116        minimap_line_height: Pixels,
 9117        scroll_position: f32,
 9118        minimap_scroll_top: f32,
 9119        show_thumb: bool,
 9120    ) -> Self {
 9121        // The scrollbar thumb size is calculated as
 9122        // (visible_content/total_content) × scrollbar_track_length.
 9123        //
 9124        // For the minimap's thumb layout, we leverage this by setting the
 9125        // scrollbar track length to the entire document size (using minimap line
 9126        // height). This creates a thumb that exactly represents the editor
 9127        // viewport scaled to minimap proportions.
 9128        //
 9129        // We adjust the thumb position relative to `minimap_scroll_top` to
 9130        // accommodate for the deliberately oversized track.
 9131        //
 9132        // This approach ensures that the minimap thumb accurately reflects the
 9133        // editor's current scroll position whilst nicely synchronizing the minimap
 9134        // thumb and scrollbar thumb.
 9135        let scroll_range = total_editor_lines * minimap_line_height;
 9136        let viewport_size = visible_lines * minimap_line_height;
 9137
 9138        let track_top_offset = -minimap_scroll_top * minimap_line_height;
 9139
 9140        Self::new_with_hitbox_and_track_length(
 9141            minimap_track_hitbox,
 9142            scroll_range,
 9143            viewport_size,
 9144            scroll_range,
 9145            minimap_line_height,
 9146            track_top_offset,
 9147            scroll_position,
 9148            show_thumb,
 9149            ScrollbarAxis::Vertical,
 9150        )
 9151    }
 9152
 9153    fn new_with_hitbox_and_track_length(
 9154        scrollbar_track_hitbox: Hitbox,
 9155        track_length: Pixels,
 9156        viewport_size: Pixels,
 9157        scroll_range: Pixels,
 9158        glyph_space: Pixels,
 9159        content_offset: Pixels,
 9160        scroll_position: f32,
 9161        show_thumb: bool,
 9162        axis: ScrollbarAxis,
 9163    ) -> Self {
 9164        let text_units_per_page = viewport_size / glyph_space;
 9165        let visible_range = scroll_position..scroll_position + text_units_per_page;
 9166        let total_text_units = scroll_range / glyph_space;
 9167
 9168        let thumb_percentage = text_units_per_page / total_text_units;
 9169        let thumb_size = (track_length * thumb_percentage)
 9170            .max(ScrollbarLayout::MIN_THUMB_SIZE)
 9171            .min(track_length);
 9172
 9173        let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
 9174
 9175        let content_larger_than_viewport = text_unit_divisor > 0.;
 9176
 9177        let text_unit_size = if content_larger_than_viewport {
 9178            (track_length - thumb_size) / text_unit_divisor
 9179        } else {
 9180            glyph_space
 9181        };
 9182
 9183        let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
 9184            Self::thumb_bounds(
 9185                &scrollbar_track_hitbox,
 9186                content_offset,
 9187                visible_range.start,
 9188                text_unit_size,
 9189                thumb_size,
 9190                axis,
 9191            )
 9192        });
 9193
 9194        ScrollbarLayout {
 9195            hitbox: scrollbar_track_hitbox,
 9196            visible_range,
 9197            text_unit_size,
 9198            thumb_bounds,
 9199            thumb_state: Default::default(),
 9200        }
 9201    }
 9202
 9203    fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
 9204        if let Some(thumb_state) = thumb_state {
 9205            Self {
 9206                thumb_state,
 9207                ..self
 9208            }
 9209        } else {
 9210            self
 9211        }
 9212    }
 9213
 9214    fn thumb_bounds(
 9215        scrollbar_track: &Hitbox,
 9216        content_offset: Pixels,
 9217        visible_range_start: f32,
 9218        text_unit_size: Pixels,
 9219        thumb_size: Pixels,
 9220        axis: ScrollbarAxis,
 9221    ) -> Bounds<Pixels> {
 9222        let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
 9223            origin + content_offset + visible_range_start * text_unit_size
 9224        });
 9225        Bounds::new(
 9226            thumb_origin,
 9227            scrollbar_track.size.apply_along(axis, |_| thumb_size),
 9228        )
 9229    }
 9230
 9231    fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
 9232        self.thumb_bounds
 9233            .is_some_and(|bounds| bounds.contains(position))
 9234    }
 9235
 9236    fn marker_quads_for_ranges(
 9237        &self,
 9238        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
 9239        column: Option<usize>,
 9240    ) -> Vec<PaintQuad> {
 9241        struct MinMax {
 9242            min: Pixels,
 9243            max: Pixels,
 9244        }
 9245        let (x_range, height_limit) = if let Some(column) = column {
 9246            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
 9247            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
 9248            let end = start + column_width;
 9249            (
 9250                Range { start, end },
 9251                MinMax {
 9252                    min: Self::MIN_MARKER_HEIGHT,
 9253                    max: px(f32::MAX),
 9254                },
 9255            )
 9256        } else {
 9257            (
 9258                Range {
 9259                    start: Self::BORDER_WIDTH,
 9260                    end: self.hitbox.size.width,
 9261                },
 9262                MinMax {
 9263                    min: Self::LINE_MARKER_HEIGHT,
 9264                    max: Self::LINE_MARKER_HEIGHT,
 9265                },
 9266            )
 9267        };
 9268
 9269        let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
 9270        let mut pixel_ranges = row_ranges
 9271            .into_iter()
 9272            .map(|range| {
 9273                let start_y = row_to_y(range.start);
 9274                let end_y = row_to_y(range.end)
 9275                    + self
 9276                        .text_unit_size
 9277                        .max(height_limit.min)
 9278                        .min(height_limit.max);
 9279                ColoredRange {
 9280                    start: start_y,
 9281                    end: end_y,
 9282                    color: range.color,
 9283                }
 9284            })
 9285            .peekable();
 9286
 9287        let mut quads = Vec::new();
 9288        while let Some(mut pixel_range) = pixel_ranges.next() {
 9289            while let Some(next_pixel_range) = pixel_ranges.peek() {
 9290                if pixel_range.end >= next_pixel_range.start - px(1.0)
 9291                    && pixel_range.color == next_pixel_range.color
 9292                {
 9293                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
 9294                    pixel_ranges.next();
 9295                } else {
 9296                    break;
 9297                }
 9298            }
 9299
 9300            let bounds = Bounds::from_corners(
 9301                point(x_range.start, pixel_range.start),
 9302                point(x_range.end, pixel_range.end),
 9303            );
 9304            quads.push(quad(
 9305                bounds,
 9306                Corners::default(),
 9307                pixel_range.color,
 9308                Edges::default(),
 9309                Hsla::transparent_black(),
 9310                BorderStyle::default(),
 9311            ));
 9312        }
 9313
 9314        quads
 9315    }
 9316}
 9317
 9318struct MinimapLayout {
 9319    pub minimap: AnyElement,
 9320    pub thumb_layout: ScrollbarLayout,
 9321    pub minimap_scroll_top: f32,
 9322    pub minimap_line_height: Pixels,
 9323    pub thumb_border_style: MinimapThumbBorder,
 9324    pub max_scroll_top: f32,
 9325}
 9326
 9327impl MinimapLayout {
 9328    const MINIMAP_WIDTH: Pixels = px(100.);
 9329    /// Calculates the scroll top offset the minimap editor has to have based on the
 9330    /// current scroll progress.
 9331    fn calculate_minimap_top_offset(
 9332        document_lines: f32,
 9333        visible_editor_lines: f32,
 9334        visible_minimap_lines: f32,
 9335        scroll_position: f32,
 9336    ) -> f32 {
 9337        let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
 9338        if non_visible_document_lines == 0. {
 9339            0.
 9340        } else {
 9341            let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
 9342            scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
 9343        }
 9344    }
 9345}
 9346
 9347struct CreaseTrailerLayout {
 9348    element: AnyElement,
 9349    bounds: Bounds<Pixels>,
 9350}
 9351
 9352pub(crate) struct PositionMap {
 9353    pub size: Size<Pixels>,
 9354    pub line_height: Pixels,
 9355    pub scroll_pixel_position: gpui::Point<Pixels>,
 9356    pub scroll_max: gpui::Point<f32>,
 9357    pub em_width: Pixels,
 9358    pub em_advance: Pixels,
 9359    pub visible_row_range: Range<DisplayRow>,
 9360    pub line_layouts: Vec<LineWithInvisibles>,
 9361    pub snapshot: EditorSnapshot,
 9362    pub text_hitbox: Hitbox,
 9363    pub gutter_hitbox: Hitbox,
 9364}
 9365
 9366#[derive(Debug, Copy, Clone)]
 9367pub struct PointForPosition {
 9368    pub previous_valid: DisplayPoint,
 9369    pub next_valid: DisplayPoint,
 9370    pub exact_unclipped: DisplayPoint,
 9371    pub column_overshoot_after_line_end: u32,
 9372}
 9373
 9374impl PointForPosition {
 9375    pub fn as_valid(&self) -> Option<DisplayPoint> {
 9376        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
 9377            Some(self.previous_valid)
 9378        } else {
 9379            None
 9380        }
 9381    }
 9382
 9383    pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
 9384        let Some(valid_point) = self.as_valid() else {
 9385            return false;
 9386        };
 9387        let range = selection.range();
 9388
 9389        let candidate_row = valid_point.row();
 9390        let candidate_col = valid_point.column();
 9391
 9392        let start_row = range.start.row();
 9393        let start_col = range.start.column();
 9394        let end_row = range.end.row();
 9395        let end_col = range.end.column();
 9396
 9397        if candidate_row < start_row || candidate_row > end_row {
 9398            false
 9399        } else if start_row == end_row {
 9400            candidate_col >= start_col && candidate_col < end_col
 9401        } else {
 9402            if candidate_row == start_row {
 9403                candidate_col >= start_col
 9404            } else if candidate_row == end_row {
 9405                candidate_col < end_col
 9406            } else {
 9407                true
 9408            }
 9409        }
 9410    }
 9411}
 9412
 9413impl PositionMap {
 9414    pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
 9415        let text_bounds = self.text_hitbox.bounds;
 9416        let scroll_position = self.snapshot.scroll_position();
 9417        let position = position - text_bounds.origin;
 9418        let y = position.y.max(px(0.)).min(self.size.height);
 9419        let x = position.x + (scroll_position.x * self.em_width);
 9420        let row = ((y / self.line_height) + scroll_position.y) as u32;
 9421
 9422        let (column, x_overshoot_after_line_end) = if let Some(line) = self
 9423            .line_layouts
 9424            .get(row as usize - scroll_position.y as usize)
 9425        {
 9426            if let Some(ix) = line.index_for_x(x) {
 9427                (ix as u32, px(0.))
 9428            } else {
 9429                (line.len as u32, px(0.).max(x - line.width))
 9430            }
 9431        } else {
 9432            (0, x)
 9433        };
 9434
 9435        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
 9436        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
 9437        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
 9438
 9439        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
 9440        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
 9441        PointForPosition {
 9442            previous_valid,
 9443            next_valid,
 9444            exact_unclipped,
 9445            column_overshoot_after_line_end,
 9446        }
 9447    }
 9448}
 9449
 9450struct BlockLayout {
 9451    id: BlockId,
 9452    x_offset: Pixels,
 9453    row: Option<DisplayRow>,
 9454    element: AnyElement,
 9455    available_space: Size<AvailableSpace>,
 9456    style: BlockStyle,
 9457    overlaps_gutter: bool,
 9458    is_buffer_header: bool,
 9459}
 9460
 9461pub fn layout_line(
 9462    row: DisplayRow,
 9463    snapshot: &EditorSnapshot,
 9464    style: &EditorStyle,
 9465    text_width: Pixels,
 9466    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 9467    window: &mut Window,
 9468    cx: &mut App,
 9469) -> LineWithInvisibles {
 9470    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
 9471    LineWithInvisibles::from_chunks(
 9472        chunks,
 9473        &style,
 9474        MAX_LINE_LEN,
 9475        1,
 9476        &snapshot.mode,
 9477        text_width,
 9478        is_row_soft_wrapped,
 9479        window,
 9480        cx,
 9481    )
 9482    .pop()
 9483    .unwrap()
 9484}
 9485
 9486#[derive(Debug)]
 9487pub struct IndentGuideLayout {
 9488    origin: gpui::Point<Pixels>,
 9489    length: Pixels,
 9490    single_indent_width: Pixels,
 9491    depth: u32,
 9492    active: bool,
 9493    settings: IndentGuideSettings,
 9494}
 9495
 9496pub struct CursorLayout {
 9497    origin: gpui::Point<Pixels>,
 9498    block_width: Pixels,
 9499    line_height: Pixels,
 9500    color: Hsla,
 9501    shape: CursorShape,
 9502    block_text: Option<ShapedLine>,
 9503    cursor_name: Option<AnyElement>,
 9504}
 9505
 9506#[derive(Debug)]
 9507pub struct CursorName {
 9508    string: SharedString,
 9509    color: Hsla,
 9510    is_top_row: bool,
 9511}
 9512
 9513impl CursorLayout {
 9514    pub fn new(
 9515        origin: gpui::Point<Pixels>,
 9516        block_width: Pixels,
 9517        line_height: Pixels,
 9518        color: Hsla,
 9519        shape: CursorShape,
 9520        block_text: Option<ShapedLine>,
 9521    ) -> CursorLayout {
 9522        CursorLayout {
 9523            origin,
 9524            block_width,
 9525            line_height,
 9526            color,
 9527            shape,
 9528            block_text,
 9529            cursor_name: None,
 9530        }
 9531    }
 9532
 9533    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
 9534        Bounds {
 9535            origin: self.origin + origin,
 9536            size: size(self.block_width, self.line_height),
 9537        }
 9538    }
 9539
 9540    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
 9541        match self.shape {
 9542            CursorShape::Bar => Bounds {
 9543                origin: self.origin + origin,
 9544                size: size(px(2.0), self.line_height),
 9545            },
 9546            CursorShape::Block | CursorShape::Hollow => Bounds {
 9547                origin: self.origin + origin,
 9548                size: size(self.block_width, self.line_height),
 9549            },
 9550            CursorShape::Underline => Bounds {
 9551                origin: self.origin
 9552                    + origin
 9553                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
 9554                size: size(self.block_width, px(2.0)),
 9555            },
 9556        }
 9557    }
 9558
 9559    pub fn layout(
 9560        &mut self,
 9561        origin: gpui::Point<Pixels>,
 9562        cursor_name: Option<CursorName>,
 9563        window: &mut Window,
 9564        cx: &mut App,
 9565    ) {
 9566        if let Some(cursor_name) = cursor_name {
 9567            let bounds = self.bounds(origin);
 9568            let text_size = self.line_height / 1.5;
 9569
 9570            let name_origin = if cursor_name.is_top_row {
 9571                point(bounds.right() - px(1.), bounds.top())
 9572            } else {
 9573                match self.shape {
 9574                    CursorShape::Bar => point(
 9575                        bounds.right() - px(2.),
 9576                        bounds.top() - text_size / 2. - px(1.),
 9577                    ),
 9578                    _ => point(
 9579                        bounds.right() - px(1.),
 9580                        bounds.top() - text_size / 2. - px(1.),
 9581                    ),
 9582                }
 9583            };
 9584            let mut name_element = div()
 9585                .bg(self.color)
 9586                .text_size(text_size)
 9587                .px_0p5()
 9588                .line_height(text_size + px(2.))
 9589                .text_color(cursor_name.color)
 9590                .child(cursor_name.string.clone())
 9591                .into_any_element();
 9592
 9593            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
 9594
 9595            self.cursor_name = Some(name_element);
 9596        }
 9597    }
 9598
 9599    pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
 9600        let bounds = self.bounds(origin);
 9601
 9602        //Draw background or border quad
 9603        let cursor = if matches!(self.shape, CursorShape::Hollow) {
 9604            outline(bounds, self.color, BorderStyle::Solid)
 9605        } else {
 9606            fill(bounds, self.color)
 9607        };
 9608
 9609        if let Some(name) = &mut self.cursor_name {
 9610            name.paint(window, cx);
 9611        }
 9612
 9613        window.paint_quad(cursor);
 9614
 9615        if let Some(block_text) = &self.block_text {
 9616            block_text
 9617                .paint(self.origin + origin, self.line_height, window, cx)
 9618                .log_err();
 9619        }
 9620    }
 9621
 9622    pub fn shape(&self) -> CursorShape {
 9623        self.shape
 9624    }
 9625}
 9626
 9627#[derive(Debug)]
 9628pub struct HighlightedRange {
 9629    pub start_y: Pixels,
 9630    pub line_height: Pixels,
 9631    pub lines: Vec<HighlightedRangeLine>,
 9632    pub color: Hsla,
 9633    pub corner_radius: Pixels,
 9634}
 9635
 9636#[derive(Debug)]
 9637pub struct HighlightedRangeLine {
 9638    pub start_x: Pixels,
 9639    pub end_x: Pixels,
 9640}
 9641
 9642impl HighlightedRange {
 9643    pub fn paint(&self, bounds: Bounds<Pixels>, window: &mut Window) {
 9644        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
 9645            self.paint_lines(self.start_y, &self.lines[0..1], bounds, window);
 9646            self.paint_lines(
 9647                self.start_y + self.line_height,
 9648                &self.lines[1..],
 9649                bounds,
 9650                window,
 9651            );
 9652        } else {
 9653            self.paint_lines(self.start_y, &self.lines, bounds, window);
 9654        }
 9655    }
 9656
 9657    fn paint_lines(
 9658        &self,
 9659        start_y: Pixels,
 9660        lines: &[HighlightedRangeLine],
 9661        _bounds: Bounds<Pixels>,
 9662        window: &mut Window,
 9663    ) {
 9664        if lines.is_empty() {
 9665            return;
 9666        }
 9667
 9668        let first_line = lines.first().unwrap();
 9669        let last_line = lines.last().unwrap();
 9670
 9671        let first_top_left = point(first_line.start_x, start_y);
 9672        let first_top_right = point(first_line.end_x, start_y);
 9673
 9674        let curve_height = point(Pixels::ZERO, self.corner_radius);
 9675        let curve_width = |start_x: Pixels, end_x: Pixels| {
 9676            let max = (end_x - start_x) / 2.;
 9677            let width = if max < self.corner_radius {
 9678                max
 9679            } else {
 9680                self.corner_radius
 9681            };
 9682
 9683            point(width, Pixels::ZERO)
 9684        };
 9685
 9686        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
 9687        let mut builder = gpui::PathBuilder::fill();
 9688        builder.move_to(first_top_right - top_curve_width);
 9689        builder.curve_to(first_top_right + curve_height, first_top_right);
 9690
 9691        let mut iter = lines.iter().enumerate().peekable();
 9692        while let Some((ix, line)) = iter.next() {
 9693            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
 9694
 9695            if let Some((_, next_line)) = iter.peek() {
 9696                let next_top_right = point(next_line.end_x, bottom_right.y);
 9697
 9698                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
 9699                    Ordering::Equal => {
 9700                        builder.line_to(bottom_right);
 9701                    }
 9702                    Ordering::Less => {
 9703                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
 9704                        builder.line_to(bottom_right - curve_height);
 9705                        if self.corner_radius > Pixels::ZERO {
 9706                            builder.curve_to(bottom_right - curve_width, bottom_right);
 9707                        }
 9708                        builder.line_to(next_top_right + curve_width);
 9709                        if self.corner_radius > Pixels::ZERO {
 9710                            builder.curve_to(next_top_right + curve_height, next_top_right);
 9711                        }
 9712                    }
 9713                    Ordering::Greater => {
 9714                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
 9715                        builder.line_to(bottom_right - curve_height);
 9716                        if self.corner_radius > Pixels::ZERO {
 9717                            builder.curve_to(bottom_right + curve_width, bottom_right);
 9718                        }
 9719                        builder.line_to(next_top_right - curve_width);
 9720                        if self.corner_radius > Pixels::ZERO {
 9721                            builder.curve_to(next_top_right + curve_height, next_top_right);
 9722                        }
 9723                    }
 9724                }
 9725            } else {
 9726                let curve_width = curve_width(line.start_x, line.end_x);
 9727                builder.line_to(bottom_right - curve_height);
 9728                if self.corner_radius > Pixels::ZERO {
 9729                    builder.curve_to(bottom_right - curve_width, bottom_right);
 9730                }
 9731
 9732                let bottom_left = point(line.start_x, bottom_right.y);
 9733                builder.line_to(bottom_left + curve_width);
 9734                if self.corner_radius > Pixels::ZERO {
 9735                    builder.curve_to(bottom_left - curve_height, bottom_left);
 9736                }
 9737            }
 9738        }
 9739
 9740        if first_line.start_x > last_line.start_x {
 9741            let curve_width = curve_width(last_line.start_x, first_line.start_x);
 9742            let second_top_left = point(last_line.start_x, start_y + self.line_height);
 9743            builder.line_to(second_top_left + curve_height);
 9744            if self.corner_radius > Pixels::ZERO {
 9745                builder.curve_to(second_top_left + curve_width, second_top_left);
 9746            }
 9747            let first_bottom_left = point(first_line.start_x, second_top_left.y);
 9748            builder.line_to(first_bottom_left - curve_width);
 9749            if self.corner_radius > Pixels::ZERO {
 9750                builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
 9751            }
 9752        }
 9753
 9754        builder.line_to(first_top_left + curve_height);
 9755        if self.corner_radius > Pixels::ZERO {
 9756            builder.curve_to(first_top_left + top_curve_width, first_top_left);
 9757        }
 9758        builder.line_to(first_top_right - top_curve_width);
 9759
 9760        if let Ok(path) = builder.build() {
 9761            window.paint_path(path, self.color);
 9762        }
 9763    }
 9764}
 9765
 9766enum CursorPopoverType {
 9767    CodeContextMenu,
 9768    EditPrediction,
 9769}
 9770
 9771pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
 9772    (delta.pow(1.2) / 100.0).min(px(3.0)).into()
 9773}
 9774
 9775fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
 9776    (delta.pow(1.2) / 300.0).into()
 9777}
 9778
 9779pub fn register_action<T: Action>(
 9780    editor: &Entity<Editor>,
 9781    window: &mut Window,
 9782    listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
 9783) {
 9784    let editor = editor.clone();
 9785    window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
 9786        let action = action.downcast_ref().unwrap();
 9787        if phase == DispatchPhase::Bubble {
 9788            editor.update(cx, |editor, cx| {
 9789                listener(editor, action, window, cx);
 9790            })
 9791        }
 9792    })
 9793}
 9794
 9795fn compute_auto_height_layout(
 9796    editor: &mut Editor,
 9797    max_lines: usize,
 9798    max_line_number_width: Pixels,
 9799    known_dimensions: Size<Option<Pixels>>,
 9800    available_width: AvailableSpace,
 9801    window: &mut Window,
 9802    cx: &mut Context<Editor>,
 9803) -> Option<Size<Pixels>> {
 9804    let width = known_dimensions.width.or({
 9805        if let AvailableSpace::Definite(available_width) = available_width {
 9806            Some(available_width)
 9807        } else {
 9808            None
 9809        }
 9810    })?;
 9811    if let Some(height) = known_dimensions.height {
 9812        return Some(size(width, height));
 9813    }
 9814
 9815    let style = editor.style.as_ref().unwrap();
 9816    let font_id = window.text_system().resolve_font(&style.text.font());
 9817    let font_size = style.text.font_size.to_pixels(window.rem_size());
 9818    let line_height = style.text.line_height_in_pixels(window.rem_size());
 9819    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
 9820
 9821    let mut snapshot = editor.snapshot(window, cx);
 9822    let gutter_dimensions = snapshot
 9823        .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
 9824        .or_else(|| {
 9825            editor
 9826                .offset_content
 9827                .then(|| GutterDimensions::default_with_margin(font_id, font_size, cx))
 9828        })
 9829        .unwrap_or_default();
 9830
 9831    editor.gutter_dimensions = gutter_dimensions;
 9832    let text_width = width - gutter_dimensions.width;
 9833    let overscroll = size(em_width, px(0.));
 9834
 9835    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
 9836    if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None) {
 9837        if editor.set_wrap_width(Some(editor_width), cx) {
 9838            snapshot = editor.snapshot(window, cx);
 9839        }
 9840    }
 9841
 9842    let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
 9843    let height = scroll_height
 9844        .max(line_height)
 9845        .min(line_height * max_lines as f32);
 9846
 9847    Some(size(width, height))
 9848}
 9849
 9850#[cfg(test)]
 9851mod tests {
 9852    use super::*;
 9853    use crate::{
 9854        Editor, MultiBuffer,
 9855        display_map::{BlockPlacement, BlockProperties},
 9856        editor_tests::{init_test, update_test_language_settings},
 9857    };
 9858    use gpui::{TestAppContext, VisualTestContext};
 9859    use language::language_settings;
 9860    use log::info;
 9861    use std::num::NonZeroU32;
 9862    use util::test::sample_text;
 9863
 9864    #[gpui::test]
 9865    fn test_shape_line_numbers(cx: &mut TestAppContext) {
 9866        init_test(cx, |_| {});
 9867        let window = cx.add_window(|window, cx| {
 9868            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
 9869            Editor::new(EditorMode::full(), buffer, None, window, cx)
 9870        });
 9871
 9872        let editor = window.root(cx).unwrap();
 9873        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
 9874        let line_height = window
 9875            .update(cx, |_, window, _| {
 9876                style.text.line_height_in_pixels(window.rem_size())
 9877            })
 9878            .unwrap();
 9879        let element = EditorElement::new(&editor, style);
 9880        let snapshot = window
 9881            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
 9882            .unwrap();
 9883
 9884        let layouts = cx
 9885            .update_window(*window, |_, window, cx| {
 9886                element.layout_line_numbers(
 9887                    None,
 9888                    GutterDimensions {
 9889                        left_padding: Pixels::ZERO,
 9890                        right_padding: Pixels::ZERO,
 9891                        width: px(30.0),
 9892                        margin: Pixels::ZERO,
 9893                        git_blame_entries_width: None,
 9894                    },
 9895                    line_height,
 9896                    gpui::Point::default(),
 9897                    DisplayRow(0)..DisplayRow(6),
 9898                    &(0..6)
 9899                        .map(|row| RowInfo {
 9900                            buffer_row: Some(row),
 9901                            ..Default::default()
 9902                        })
 9903                        .collect::<Vec<_>>(),
 9904                    &BTreeMap::default(),
 9905                    Some(DisplayPoint::new(DisplayRow(0), 0)),
 9906                    &snapshot,
 9907                    window,
 9908                    cx,
 9909                )
 9910            })
 9911            .unwrap();
 9912        assert_eq!(layouts.len(), 6);
 9913
 9914        let relative_rows = window
 9915            .update(cx, |editor, window, cx| {
 9916                let snapshot = editor.snapshot(window, cx);
 9917                element.calculate_relative_line_numbers(
 9918                    &snapshot,
 9919                    &(DisplayRow(0)..DisplayRow(6)),
 9920                    Some(DisplayRow(3)),
 9921                )
 9922            })
 9923            .unwrap();
 9924        assert_eq!(relative_rows[&DisplayRow(0)], 3);
 9925        assert_eq!(relative_rows[&DisplayRow(1)], 2);
 9926        assert_eq!(relative_rows[&DisplayRow(2)], 1);
 9927        // current line has no relative number
 9928        assert_eq!(relative_rows[&DisplayRow(4)], 1);
 9929        assert_eq!(relative_rows[&DisplayRow(5)], 2);
 9930
 9931        // works if cursor is before screen
 9932        let relative_rows = window
 9933            .update(cx, |editor, window, cx| {
 9934                let snapshot = editor.snapshot(window, cx);
 9935                element.calculate_relative_line_numbers(
 9936                    &snapshot,
 9937                    &(DisplayRow(3)..DisplayRow(6)),
 9938                    Some(DisplayRow(1)),
 9939                )
 9940            })
 9941            .unwrap();
 9942        assert_eq!(relative_rows.len(), 3);
 9943        assert_eq!(relative_rows[&DisplayRow(3)], 2);
 9944        assert_eq!(relative_rows[&DisplayRow(4)], 3);
 9945        assert_eq!(relative_rows[&DisplayRow(5)], 4);
 9946
 9947        // works if cursor is after screen
 9948        let relative_rows = window
 9949            .update(cx, |editor, window, cx| {
 9950                let snapshot = editor.snapshot(window, cx);
 9951                element.calculate_relative_line_numbers(
 9952                    &snapshot,
 9953                    &(DisplayRow(0)..DisplayRow(3)),
 9954                    Some(DisplayRow(6)),
 9955                )
 9956            })
 9957            .unwrap();
 9958        assert_eq!(relative_rows.len(), 3);
 9959        assert_eq!(relative_rows[&DisplayRow(0)], 5);
 9960        assert_eq!(relative_rows[&DisplayRow(1)], 4);
 9961        assert_eq!(relative_rows[&DisplayRow(2)], 3);
 9962    }
 9963
 9964    #[gpui::test]
 9965    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
 9966        init_test(cx, |_| {});
 9967
 9968        let window = cx.add_window(|window, cx| {
 9969            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
 9970            Editor::new(EditorMode::full(), buffer, None, window, cx)
 9971        });
 9972        let cx = &mut VisualTestContext::from_window(*window, cx);
 9973        let editor = window.root(cx).unwrap();
 9974        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
 9975
 9976        window
 9977            .update(cx, |editor, window, cx| {
 9978                editor.cursor_shape = CursorShape::Block;
 9979                editor.change_selections(None, window, cx, |s| {
 9980                    s.select_ranges([
 9981                        Point::new(0, 0)..Point::new(1, 0),
 9982                        Point::new(3, 2)..Point::new(3, 3),
 9983                        Point::new(5, 6)..Point::new(6, 0),
 9984                    ]);
 9985                });
 9986            })
 9987            .unwrap();
 9988
 9989        let (_, state) = cx.draw(
 9990            point(px(500.), px(500.)),
 9991            size(px(500.), px(500.)),
 9992            |_, _| EditorElement::new(&editor, style),
 9993        );
 9994
 9995        assert_eq!(state.selections.len(), 1);
 9996        let local_selections = &state.selections[0].1;
 9997        assert_eq!(local_selections.len(), 3);
 9998        // moves cursor back one line
 9999        assert_eq!(
10000            local_selections[0].head,
10001            DisplayPoint::new(DisplayRow(0), 6)
10002        );
10003        assert_eq!(
10004            local_selections[0].range,
10005            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
10006        );
10007
10008        // moves cursor back one column
10009        assert_eq!(
10010            local_selections[1].range,
10011            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
10012        );
10013        assert_eq!(
10014            local_selections[1].head,
10015            DisplayPoint::new(DisplayRow(3), 2)
10016        );
10017
10018        // leaves cursor on the max point
10019        assert_eq!(
10020            local_selections[2].range,
10021            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
10022        );
10023        assert_eq!(
10024            local_selections[2].head,
10025            DisplayPoint::new(DisplayRow(6), 0)
10026        );
10027
10028        // active lines does not include 1 (even though the range of the selection does)
10029        assert_eq!(
10030            state.active_rows.keys().cloned().collect::<Vec<_>>(),
10031            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
10032        );
10033    }
10034
10035    #[gpui::test]
10036    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
10037        init_test(cx, |_| {});
10038
10039        let window = cx.add_window(|window, cx| {
10040            let buffer = MultiBuffer::build_simple("", cx);
10041            Editor::new(EditorMode::full(), buffer, None, window, cx)
10042        });
10043        let cx = &mut VisualTestContext::from_window(*window, cx);
10044        let editor = window.root(cx).unwrap();
10045        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10046        window
10047            .update(cx, |editor, window, cx| {
10048                editor.set_placeholder_text("hello", cx);
10049                editor.insert_blocks(
10050                    [BlockProperties {
10051                        style: BlockStyle::Fixed,
10052                        placement: BlockPlacement::Above(Anchor::min()),
10053                        height: Some(3),
10054                        render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
10055                        priority: 0,
10056                        render_in_minimap: true,
10057                    }],
10058                    None,
10059                    cx,
10060                );
10061
10062                // Blur the editor so that it displays placeholder text.
10063                window.blur();
10064            })
10065            .unwrap();
10066
10067        let (_, state) = cx.draw(
10068            point(px(500.), px(500.)),
10069            size(px(500.), px(500.)),
10070            |_, _| EditorElement::new(&editor, style),
10071        );
10072        assert_eq!(state.position_map.line_layouts.len(), 4);
10073        assert_eq!(state.line_numbers.len(), 1);
10074        assert_eq!(
10075            state
10076                .line_numbers
10077                .get(&MultiBufferRow(0))
10078                .map(|line_number| line_number.shaped_line.text.as_ref()),
10079            Some("1")
10080        );
10081    }
10082
10083    #[gpui::test]
10084    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
10085        const TAB_SIZE: u32 = 4;
10086
10087        let input_text = "\t \t|\t| a b";
10088        let expected_invisibles = vec![
10089            Invisible::Tab {
10090                line_start_offset: 0,
10091                line_end_offset: TAB_SIZE as usize,
10092            },
10093            Invisible::Whitespace {
10094                line_offset: TAB_SIZE as usize,
10095            },
10096            Invisible::Tab {
10097                line_start_offset: TAB_SIZE as usize + 1,
10098                line_end_offset: TAB_SIZE as usize * 2,
10099            },
10100            Invisible::Tab {
10101                line_start_offset: TAB_SIZE as usize * 2 + 1,
10102                line_end_offset: TAB_SIZE as usize * 3,
10103            },
10104            Invisible::Whitespace {
10105                line_offset: TAB_SIZE as usize * 3 + 1,
10106            },
10107            Invisible::Whitespace {
10108                line_offset: TAB_SIZE as usize * 3 + 3,
10109            },
10110        ];
10111        assert_eq!(
10112            expected_invisibles.len(),
10113            input_text
10114                .chars()
10115                .filter(|initial_char| initial_char.is_whitespace())
10116                .count(),
10117            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10118        );
10119
10120        for show_line_numbers in [true, false] {
10121            init_test(cx, |s| {
10122                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10123                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
10124            });
10125
10126            let actual_invisibles = collect_invisibles_from_new_editor(
10127                cx,
10128                EditorMode::full(),
10129                input_text,
10130                px(500.0),
10131                show_line_numbers,
10132            );
10133
10134            assert_eq!(expected_invisibles, actual_invisibles);
10135        }
10136    }
10137
10138    #[gpui::test]
10139    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
10140        init_test(cx, |s| {
10141            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10142            s.defaults.tab_size = NonZeroU32::new(4);
10143        });
10144
10145        for editor_mode_without_invisibles in [
10146            EditorMode::SingleLine { auto_width: false },
10147            EditorMode::AutoHeight { max_lines: 100 },
10148        ] {
10149            for show_line_numbers in [true, false] {
10150                let invisibles = collect_invisibles_from_new_editor(
10151                    cx,
10152                    editor_mode_without_invisibles.clone(),
10153                    "\t\t\t| | a b",
10154                    px(500.0),
10155                    show_line_numbers,
10156                );
10157                assert!(
10158                    invisibles.is_empty(),
10159                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
10160                );
10161            }
10162        }
10163    }
10164
10165    #[gpui::test]
10166    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
10167        let tab_size = 4;
10168        let input_text = "a\tbcd     ".repeat(9);
10169        let repeated_invisibles = [
10170            Invisible::Tab {
10171                line_start_offset: 1,
10172                line_end_offset: tab_size as usize,
10173            },
10174            Invisible::Whitespace {
10175                line_offset: tab_size as usize + 3,
10176            },
10177            Invisible::Whitespace {
10178                line_offset: tab_size as usize + 4,
10179            },
10180            Invisible::Whitespace {
10181                line_offset: tab_size as usize + 5,
10182            },
10183            Invisible::Whitespace {
10184                line_offset: tab_size as usize + 6,
10185            },
10186            Invisible::Whitespace {
10187                line_offset: tab_size as usize + 7,
10188            },
10189        ];
10190        let expected_invisibles = std::iter::once(repeated_invisibles)
10191            .cycle()
10192            .take(9)
10193            .flatten()
10194            .collect::<Vec<_>>();
10195        assert_eq!(
10196            expected_invisibles.len(),
10197            input_text
10198                .chars()
10199                .filter(|initial_char| initial_char.is_whitespace())
10200                .count(),
10201            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10202        );
10203        info!("Expected invisibles: {expected_invisibles:?}");
10204
10205        init_test(cx, |_| {});
10206
10207        // Put the same string with repeating whitespace pattern into editors of various size,
10208        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
10209        let resize_step = 10.0;
10210        let mut editor_width = 200.0;
10211        while editor_width <= 1000.0 {
10212            for show_line_numbers in [true, false] {
10213                update_test_language_settings(cx, |s| {
10214                    s.defaults.tab_size = NonZeroU32::new(tab_size);
10215                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10216                    s.defaults.preferred_line_length = Some(editor_width as u32);
10217                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
10218                });
10219
10220                let actual_invisibles = collect_invisibles_from_new_editor(
10221                    cx,
10222                    EditorMode::full(),
10223                    &input_text,
10224                    px(editor_width),
10225                    show_line_numbers,
10226                );
10227
10228                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
10229                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
10230                let mut i = 0;
10231                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
10232                    i = actual_index;
10233                    match expected_invisibles.get(i) {
10234                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
10235                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
10236                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
10237                            _ => {
10238                                panic!(
10239                                    "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
10240                                )
10241                            }
10242                        },
10243                        None => {
10244                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
10245                        }
10246                    }
10247                }
10248                let missing_expected_invisibles = &expected_invisibles[i + 1..];
10249                assert!(
10250                    missing_expected_invisibles.is_empty(),
10251                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
10252                );
10253
10254                editor_width += resize_step;
10255            }
10256        }
10257    }
10258
10259    fn collect_invisibles_from_new_editor(
10260        cx: &mut TestAppContext,
10261        editor_mode: EditorMode,
10262        input_text: &str,
10263        editor_width: Pixels,
10264        show_line_numbers: bool,
10265    ) -> Vec<Invisible> {
10266        info!(
10267            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
10268            editor_width.0
10269        );
10270        let window = cx.add_window(|window, cx| {
10271            let buffer = MultiBuffer::build_simple(input_text, cx);
10272            Editor::new(editor_mode, buffer, None, window, cx)
10273        });
10274        let cx = &mut VisualTestContext::from_window(*window, cx);
10275        let editor = window.root(cx).unwrap();
10276
10277        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10278        window
10279            .update(cx, |editor, _, cx| {
10280                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10281                editor.set_wrap_width(Some(editor_width), cx);
10282                editor.set_show_line_numbers(show_line_numbers, cx);
10283            })
10284            .unwrap();
10285        let (_, state) = cx.draw(
10286            point(px(500.), px(500.)),
10287            size(px(500.), px(500.)),
10288            |_, _| EditorElement::new(&editor, style),
10289        );
10290        state
10291            .position_map
10292            .line_layouts
10293            .iter()
10294            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
10295            .cloned()
10296            .collect()
10297    }
10298}