element.rs

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