element.rs

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