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