element.rs

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