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