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