element.rs

    1use crate::{
    2    ActiveDiagnostic, BlockId, CURSORS_VISIBLE_FOR, ChunkRendererContext, ChunkReplacement,
    3    CodeActionSource, ColumnarMode, ConflictsOurs, ConflictsOursMarker, ConflictsOuter,
    4    ConflictsTheirs, ConflictsTheirsMarker, ContextMenuPlacement, CursorShape, CustomBlockId,
    5    DisplayDiffHunk, DisplayPoint, DisplayRow, DocumentHighlightRead, DocumentHighlightWrite,
    6    EditDisplayMode, Editor, EditorMode, EditorSettings, EditorSnapshot, EditorStyle,
    7    FILE_HEADER_HEIGHT, FocusedBlock, GutterDimensions, HalfPageDown, HalfPageUp, HandleInput,
    8    HoveredCursor, InlayHintRefreshReason, InlineCompletion, JumpData, LineDown, LineHighlight,
    9    LineUp, MAX_LINE_LEN, MINIMAP_FONT_SIZE, MULTI_BUFFER_EXCERPT_HEADER_HEIGHT, OpenExcerpts,
   10    PageDown, PageUp, PhantomBreakpointIndicator, Point, RowExt, RowRangeExt, SelectPhase,
   11    SelectedTextHighlight, Selection, SelectionDragState, SoftWrap, StickyHeaderExcerpt, ToPoint,
   12    ToggleFold,
   13    code_context_menus::{CodeActionsMenu, MENU_ASIDE_MAX_WIDTH, MENU_ASIDE_MIN_WIDTH, MENU_GAP},
   14    display_map::{
   15        Block, BlockContext, BlockStyle, DisplaySnapshot, EditorMargins, FoldId, HighlightedChunk,
   16        ToDisplayPoint,
   17    },
   18    editor_settings::{
   19        CurrentLineHighlight, DocumentColorsRenderMode, DoubleClickInMultibuffer, MinimapThumb,
   20        MinimapThumbBorder, ScrollBeyondLastLine, ScrollbarAxes, ScrollbarDiagnostics, ShowMinimap,
   21        ShowScrollbar,
   22    },
   23    git::blame::{BlameRenderer, GitBlame, GlobalBlameRenderer},
   24    hover_popover::{
   25        self, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
   26        POPOVER_RIGHT_OFFSET, hover_at,
   27    },
   28    inlay_hint_settings,
   29    items::BufferSearchHighlights,
   30    mouse_context_menu::{self, MenuPosition},
   31    scroll::{ActiveScrollbarState, ScrollbarThumbState, scroll_amount::ScrollAmount},
   32};
   33use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
   34use collections::{BTreeMap, HashMap};
   35use 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_highlights) in
 6166                                background_highlights.iter()
 6167                            {
 6168                                let is_search_highlights = *background_highlight_id
 6169                                    == TypeId::of::<BufferSearchHighlights>();
 6170                                let is_text_highlights = *background_highlight_id
 6171                                    == TypeId::of::<SelectedTextHighlight>();
 6172                                let is_symbol_occurrences = *background_highlight_id
 6173                                    == TypeId::of::<DocumentHighlightRead>()
 6174                                    || *background_highlight_id
 6175                                        == TypeId::of::<DocumentHighlightWrite>();
 6176                                if (is_search_highlights && scrollbar_settings.search_results)
 6177                                    || (is_text_highlights && scrollbar_settings.selected_text)
 6178                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
 6179                                {
 6180                                    let mut color = theme.status().info;
 6181                                    if is_symbol_occurrences {
 6182                                        color.fade_out(0.5);
 6183                                    }
 6184                                    let marker_row_ranges =
 6185                                        background_highlights.iter().map(|highlight| {
 6186                                            let display_start = highlight
 6187                                                .range
 6188                                                .start
 6189                                                .to_display_point(&snapshot.display_snapshot);
 6190                                            let display_end = highlight
 6191                                                .range
 6192                                                .end
 6193                                                .to_display_point(&snapshot.display_snapshot);
 6194                                            ColoredRange {
 6195                                                start: display_start.row(),
 6196                                                end: display_end.row(),
 6197                                                color,
 6198                                            }
 6199                                        });
 6200                                    marker_quads.extend(
 6201                                        scrollbar_layout
 6202                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
 6203                                    );
 6204                                }
 6205                            }
 6206
 6207                            if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
 6208                                let diagnostics = snapshot
 6209                                    .buffer_snapshot
 6210                                    .diagnostics_in_range::<Point>(Point::zero()..max_point)
 6211                                    // Don't show diagnostics the user doesn't care about
 6212                                    .filter(|diagnostic| {
 6213                                        match (
 6214                                            scrollbar_settings.diagnostics,
 6215                                            diagnostic.diagnostic.severity,
 6216                                        ) {
 6217                                            (ScrollbarDiagnostics::All, _) => true,
 6218                                            (
 6219                                                ScrollbarDiagnostics::Error,
 6220                                                lsp::DiagnosticSeverity::ERROR,
 6221                                            ) => true,
 6222                                            (
 6223                                                ScrollbarDiagnostics::Warning,
 6224                                                lsp::DiagnosticSeverity::ERROR
 6225                                                | lsp::DiagnosticSeverity::WARNING,
 6226                                            ) => true,
 6227                                            (
 6228                                                ScrollbarDiagnostics::Information,
 6229                                                lsp::DiagnosticSeverity::ERROR
 6230                                                | lsp::DiagnosticSeverity::WARNING
 6231                                                | lsp::DiagnosticSeverity::INFORMATION,
 6232                                            ) => true,
 6233                                            (_, _) => false,
 6234                                        }
 6235                                    })
 6236                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
 6237                                    .sorted_by_key(|diagnostic| {
 6238                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
 6239                                    });
 6240
 6241                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
 6242                                    let start_display = diagnostic
 6243                                        .range
 6244                                        .start
 6245                                        .to_display_point(&snapshot.display_snapshot);
 6246                                    let end_display = diagnostic
 6247                                        .range
 6248                                        .end
 6249                                        .to_display_point(&snapshot.display_snapshot);
 6250                                    let color = match diagnostic.diagnostic.severity {
 6251                                        lsp::DiagnosticSeverity::ERROR => theme.status().error,
 6252                                        lsp::DiagnosticSeverity::WARNING => theme.status().warning,
 6253                                        lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
 6254                                        _ => theme.status().hint,
 6255                                    };
 6256                                    ColoredRange {
 6257                                        start: start_display.row(),
 6258                                        end: end_display.row(),
 6259                                        color,
 6260                                    }
 6261                                });
 6262                                marker_quads.extend(
 6263                                    scrollbar_layout
 6264                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
 6265                                );
 6266                            }
 6267
 6268                            Arc::from(marker_quads)
 6269                        })
 6270                        .await;
 6271
 6272                    editor.update(cx, |editor, cx| {
 6273                        editor.scrollbar_marker_state.markers = scrollbar_markers;
 6274                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
 6275                        editor.scrollbar_marker_state.pending_refresh = None;
 6276                        cx.notify();
 6277                    })?;
 6278
 6279                    Ok(())
 6280                }));
 6281        });
 6282    }
 6283
 6284    fn paint_highlighted_range(
 6285        &self,
 6286        range: Range<DisplayPoint>,
 6287        fill: bool,
 6288        color: Hsla,
 6289        corner_radius: Pixels,
 6290        line_end_overshoot: Pixels,
 6291        layout: &EditorLayout,
 6292        window: &mut Window,
 6293    ) {
 6294        let start_row = layout.visible_display_row_range.start;
 6295        let end_row = layout.visible_display_row_range.end;
 6296        if range.start != range.end {
 6297            let row_range = if range.end.column() == 0 {
 6298                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
 6299            } else {
 6300                cmp::max(range.start.row(), start_row)
 6301                    ..cmp::min(range.end.row().next_row(), end_row)
 6302            };
 6303
 6304            let highlighted_range = HighlightedRange {
 6305                color,
 6306                line_height: layout.position_map.line_height,
 6307                corner_radius,
 6308                start_y: layout.content_origin.y
 6309                    + row_range.start.as_f32() * layout.position_map.line_height
 6310                    - layout.position_map.scroll_pixel_position.y,
 6311                lines: row_range
 6312                    .iter_rows()
 6313                    .map(|row| {
 6314                        let line_layout =
 6315                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
 6316                        HighlightedRangeLine {
 6317                            start_x: if row == range.start.row() {
 6318                                layout.content_origin.x
 6319                                    + line_layout.x_for_index(range.start.column() as usize)
 6320                                    - layout.position_map.scroll_pixel_position.x
 6321                            } else {
 6322                                layout.content_origin.x
 6323                                    - layout.position_map.scroll_pixel_position.x
 6324                            },
 6325                            end_x: if row == range.end.row() {
 6326                                layout.content_origin.x
 6327                                    + line_layout.x_for_index(range.end.column() as usize)
 6328                                    - layout.position_map.scroll_pixel_position.x
 6329                            } else {
 6330                                layout.content_origin.x + line_layout.width + line_end_overshoot
 6331                                    - layout.position_map.scroll_pixel_position.x
 6332                            },
 6333                        }
 6334                    })
 6335                    .collect(),
 6336            };
 6337
 6338            highlighted_range.paint(fill, layout.position_map.text_hitbox.bounds, window);
 6339        }
 6340    }
 6341
 6342    fn paint_inline_diagnostics(
 6343        &mut self,
 6344        layout: &mut EditorLayout,
 6345        window: &mut Window,
 6346        cx: &mut App,
 6347    ) {
 6348        for mut inline_diagnostic in layout.inline_diagnostics.drain() {
 6349            inline_diagnostic.1.paint(window, cx);
 6350        }
 6351    }
 6352
 6353    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6354        if let Some(mut blame_layout) = layout.inline_blame_layout.take() {
 6355            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6356                blame_layout.element.paint(window, cx);
 6357            })
 6358        }
 6359    }
 6360
 6361    fn paint_inline_code_actions(
 6362        &mut self,
 6363        layout: &mut EditorLayout,
 6364        window: &mut Window,
 6365        cx: &mut App,
 6366    ) {
 6367        if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
 6368            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6369                inline_code_actions.paint(window, cx);
 6370            })
 6371        }
 6372    }
 6373
 6374    fn paint_diff_hunk_controls(
 6375        &mut self,
 6376        layout: &mut EditorLayout,
 6377        window: &mut Window,
 6378        cx: &mut App,
 6379    ) {
 6380        for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
 6381            diff_hunk_control.paint(window, cx);
 6382        }
 6383    }
 6384
 6385    fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6386        if let Some(mut layout) = layout.minimap.take() {
 6387            let minimap_hitbox = layout.thumb_layout.hitbox.clone();
 6388            let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
 6389
 6390            window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
 6391                window.with_element_namespace("minimap", |window| {
 6392                    layout.minimap.paint(window, cx);
 6393                    if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
 6394                        let minimap_thumb_color = match layout.thumb_layout.thumb_state {
 6395                            ScrollbarThumbState::Idle => {
 6396                                cx.theme().colors().minimap_thumb_background
 6397                            }
 6398                            ScrollbarThumbState::Hovered => {
 6399                                cx.theme().colors().minimap_thumb_hover_background
 6400                            }
 6401                            ScrollbarThumbState::Dragging => {
 6402                                cx.theme().colors().minimap_thumb_active_background
 6403                            }
 6404                        };
 6405                        let minimap_thumb_border = match layout.thumb_border_style {
 6406                            MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
 6407                            MinimapThumbBorder::LeftOnly => Edges {
 6408                                left: ScrollbarLayout::BORDER_WIDTH,
 6409                                ..Default::default()
 6410                            },
 6411                            MinimapThumbBorder::LeftOpen => Edges {
 6412                                right: ScrollbarLayout::BORDER_WIDTH,
 6413                                top: ScrollbarLayout::BORDER_WIDTH,
 6414                                bottom: ScrollbarLayout::BORDER_WIDTH,
 6415                                ..Default::default()
 6416                            },
 6417                            MinimapThumbBorder::RightOpen => Edges {
 6418                                left: ScrollbarLayout::BORDER_WIDTH,
 6419                                top: ScrollbarLayout::BORDER_WIDTH,
 6420                                bottom: ScrollbarLayout::BORDER_WIDTH,
 6421                                ..Default::default()
 6422                            },
 6423                            MinimapThumbBorder::None => Default::default(),
 6424                        };
 6425
 6426                        window.paint_layer(minimap_hitbox.bounds, |window| {
 6427                            window.paint_quad(quad(
 6428                                thumb_bounds,
 6429                                Corners::default(),
 6430                                minimap_thumb_color,
 6431                                minimap_thumb_border,
 6432                                cx.theme().colors().minimap_thumb_border,
 6433                                BorderStyle::Solid,
 6434                            ));
 6435                        });
 6436                    }
 6437                });
 6438            });
 6439
 6440            if dragging_minimap {
 6441                window.set_window_cursor_style(CursorStyle::Arrow);
 6442            } else {
 6443                window.set_cursor_style(CursorStyle::Arrow, &minimap_hitbox);
 6444            }
 6445
 6446            let minimap_axis = ScrollbarAxis::Vertical;
 6447            let pixels_per_line = (minimap_hitbox.size.height / layout.max_scroll_top)
 6448                .min(layout.minimap_line_height);
 6449
 6450            let mut mouse_position = window.mouse_position();
 6451
 6452            window.on_mouse_event({
 6453                let editor = self.editor.clone();
 6454
 6455                let minimap_hitbox = minimap_hitbox.clone();
 6456
 6457                move |event: &MouseMoveEvent, phase, window, cx| {
 6458                    if phase == DispatchPhase::Capture {
 6459                        return;
 6460                    }
 6461
 6462                    editor.update(cx, |editor, cx| {
 6463                        if event.pressed_button == Some(MouseButton::Left)
 6464                            && editor.scroll_manager.is_dragging_minimap()
 6465                        {
 6466                            let old_position = mouse_position.along(minimap_axis);
 6467                            let new_position = event.position.along(minimap_axis);
 6468                            if (minimap_hitbox.origin.along(minimap_axis)
 6469                                ..minimap_hitbox.bottom_right().along(minimap_axis))
 6470                                .contains(&old_position)
 6471                            {
 6472                                let position =
 6473                                    editor.scroll_position(cx).apply_along(minimap_axis, |p| {
 6474                                        (p + (new_position - old_position) / pixels_per_line)
 6475                                            .max(0.)
 6476                                    });
 6477                                editor.set_scroll_position(position, window, cx);
 6478                            }
 6479                            cx.stop_propagation();
 6480                        } else {
 6481                            if minimap_hitbox.is_hovered(window) {
 6482                                editor.scroll_manager.set_is_hovering_minimap_thumb(
 6483                                    !event.dragging()
 6484                                        && layout
 6485                                            .thumb_layout
 6486                                            .thumb_bounds
 6487                                            .is_some_and(|bounds| bounds.contains(&event.position)),
 6488                                    cx,
 6489                                );
 6490
 6491                                // Stop hover events from propagating to the
 6492                                // underlying editor if the minimap hitbox is hovered
 6493                                if !event.dragging() {
 6494                                    cx.stop_propagation();
 6495                                }
 6496                            } else {
 6497                                editor.scroll_manager.hide_minimap_thumb(cx);
 6498                            }
 6499                        }
 6500                        mouse_position = event.position;
 6501                    });
 6502                }
 6503            });
 6504
 6505            if dragging_minimap {
 6506                window.on_mouse_event({
 6507                    let editor = self.editor.clone();
 6508                    move |event: &MouseUpEvent, phase, window, cx| {
 6509                        if phase == DispatchPhase::Capture {
 6510                            return;
 6511                        }
 6512
 6513                        editor.update(cx, |editor, cx| {
 6514                            if minimap_hitbox.is_hovered(window) {
 6515                                editor.scroll_manager.set_is_hovering_minimap_thumb(
 6516                                    layout
 6517                                        .thumb_layout
 6518                                        .thumb_bounds
 6519                                        .is_some_and(|bounds| bounds.contains(&event.position)),
 6520                                    cx,
 6521                                );
 6522                            } else {
 6523                                editor.scroll_manager.hide_minimap_thumb(cx);
 6524                            }
 6525                            cx.stop_propagation();
 6526                        });
 6527                    }
 6528                });
 6529            } else {
 6530                window.on_mouse_event({
 6531                    let editor = self.editor.clone();
 6532
 6533                    move |event: &MouseDownEvent, phase, window, cx| {
 6534                        if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
 6535                            return;
 6536                        }
 6537
 6538                        let event_position = event.position;
 6539
 6540                        let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
 6541                            return;
 6542                        };
 6543
 6544                        editor.update(cx, |editor, cx| {
 6545                            if !thumb_bounds.contains(&event_position) {
 6546                                let click_position =
 6547                                    event_position.relative_to(&minimap_hitbox.origin).y;
 6548
 6549                                let top_position = (click_position
 6550                                    - thumb_bounds.size.along(minimap_axis) / 2.0)
 6551                                    .max(Pixels::ZERO);
 6552
 6553                                let scroll_offset = (layout.minimap_scroll_top
 6554                                    + top_position / layout.minimap_line_height)
 6555                                    .min(layout.max_scroll_top);
 6556
 6557                                let scroll_position = editor
 6558                                    .scroll_position(cx)
 6559                                    .apply_along(minimap_axis, |_| scroll_offset);
 6560                                editor.set_scroll_position(scroll_position, window, cx);
 6561                            }
 6562
 6563                            editor.scroll_manager.set_is_dragging_minimap(cx);
 6564                            cx.stop_propagation();
 6565                        });
 6566                    }
 6567                });
 6568            }
 6569        }
 6570    }
 6571
 6572    fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6573        for mut block in layout.blocks.drain(..) {
 6574            if block.overlaps_gutter {
 6575                block.element.paint(window, cx);
 6576            } else {
 6577                let mut bounds = layout.hitbox.bounds;
 6578                bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
 6579                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 6580                    block.element.paint(window, cx);
 6581                })
 6582            }
 6583        }
 6584    }
 6585
 6586    fn paint_inline_completion_popover(
 6587        &mut self,
 6588        layout: &mut EditorLayout,
 6589        window: &mut Window,
 6590        cx: &mut App,
 6591    ) {
 6592        if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
 6593            inline_completion_popover.paint(window, cx);
 6594        }
 6595    }
 6596
 6597    fn paint_mouse_context_menu(
 6598        &mut self,
 6599        layout: &mut EditorLayout,
 6600        window: &mut Window,
 6601        cx: &mut App,
 6602    ) {
 6603        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
 6604            mouse_context_menu.paint(window, cx);
 6605        }
 6606    }
 6607
 6608    fn paint_scroll_wheel_listener(
 6609        &mut self,
 6610        layout: &EditorLayout,
 6611        window: &mut Window,
 6612        cx: &mut App,
 6613    ) {
 6614        window.on_mouse_event({
 6615            let position_map = layout.position_map.clone();
 6616            let editor = self.editor.clone();
 6617            let hitbox = layout.hitbox.clone();
 6618            let mut delta = ScrollDelta::default();
 6619
 6620            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
 6621            // accidentally turn off their scrolling.
 6622            let base_scroll_sensitivity =
 6623                EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
 6624
 6625            // Use a minimum fast_scroll_sensitivity for same reason above
 6626            let fast_scroll_sensitivity = EditorSettings::get_global(cx)
 6627                .fast_scroll_sensitivity
 6628                .max(0.01);
 6629
 6630            move |event: &ScrollWheelEvent, phase, window, cx| {
 6631                let scroll_sensitivity = {
 6632                    if event.modifiers.alt {
 6633                        fast_scroll_sensitivity
 6634                    } else {
 6635                        base_scroll_sensitivity
 6636                    }
 6637                };
 6638
 6639                if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
 6640                    delta = delta.coalesce(event.delta);
 6641                    editor.update(cx, |editor, cx| {
 6642                        let position_map: &PositionMap = &position_map;
 6643
 6644                        let line_height = position_map.line_height;
 6645                        let max_glyph_width = position_map.em_width;
 6646                        let (delta, axis) = match delta {
 6647                            gpui::ScrollDelta::Pixels(mut pixels) => {
 6648                                //Trackpad
 6649                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
 6650                                (pixels, axis)
 6651                            }
 6652
 6653                            gpui::ScrollDelta::Lines(lines) => {
 6654                                //Not trackpad
 6655                                let pixels =
 6656                                    point(lines.x * max_glyph_width, lines.y * line_height);
 6657                                (pixels, None)
 6658                            }
 6659                        };
 6660
 6661                        let current_scroll_position = position_map.snapshot.scroll_position();
 6662                        let x = (current_scroll_position.x * max_glyph_width
 6663                            - (delta.x * scroll_sensitivity))
 6664                            / max_glyph_width;
 6665                        let y = (current_scroll_position.y * line_height
 6666                            - (delta.y * scroll_sensitivity))
 6667                            / line_height;
 6668                        let mut scroll_position =
 6669                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
 6670                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
 6671                        if forbid_vertical_scroll {
 6672                            scroll_position.y = current_scroll_position.y;
 6673                        }
 6674
 6675                        if scroll_position != current_scroll_position {
 6676                            editor.scroll(scroll_position, axis, window, cx);
 6677                            cx.stop_propagation();
 6678                        } else if y < 0. {
 6679                            // Due to clamping, we may fail to detect cases of overscroll to the top;
 6680                            // We want the scroll manager to get an update in such cases and detect the change of direction
 6681                            // on the next frame.
 6682                            cx.notify();
 6683                        }
 6684                    });
 6685                }
 6686            }
 6687        });
 6688    }
 6689
 6690    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
 6691        if self.editor.read(cx).mode.is_minimap() {
 6692            return;
 6693        }
 6694
 6695        self.paint_scroll_wheel_listener(layout, window, cx);
 6696
 6697        window.on_mouse_event({
 6698            let position_map = layout.position_map.clone();
 6699            let editor = self.editor.clone();
 6700            let diff_hunk_range =
 6701                layout
 6702                    .display_hunks
 6703                    .iter()
 6704                    .find_map(|(hunk, hunk_hitbox)| match hunk {
 6705                        DisplayDiffHunk::Folded { .. } => None,
 6706                        DisplayDiffHunk::Unfolded {
 6707                            multi_buffer_range, ..
 6708                        } => {
 6709                            if hunk_hitbox
 6710                                .as_ref()
 6711                                .map(|hitbox| hitbox.is_hovered(window))
 6712                                .unwrap_or(false)
 6713                            {
 6714                                Some(multi_buffer_range.clone())
 6715                            } else {
 6716                                None
 6717                            }
 6718                        }
 6719                    });
 6720            let line_numbers = layout.line_numbers.clone();
 6721
 6722            move |event: &MouseDownEvent, phase, window, cx| {
 6723                if phase == DispatchPhase::Bubble {
 6724                    match event.button {
 6725                        MouseButton::Left => editor.update(cx, |editor, cx| {
 6726                            let pending_mouse_down = editor
 6727                                .pending_mouse_down
 6728                                .get_or_insert_with(Default::default)
 6729                                .clone();
 6730
 6731                            *pending_mouse_down.borrow_mut() = Some(event.clone());
 6732
 6733                            Self::mouse_left_down(
 6734                                editor,
 6735                                event,
 6736                                diff_hunk_range.clone(),
 6737                                &position_map,
 6738                                line_numbers.as_ref(),
 6739                                window,
 6740                                cx,
 6741                            );
 6742                        }),
 6743                        MouseButton::Right => editor.update(cx, |editor, cx| {
 6744                            Self::mouse_right_down(editor, event, &position_map, window, cx);
 6745                        }),
 6746                        MouseButton::Middle => editor.update(cx, |editor, cx| {
 6747                            Self::mouse_middle_down(editor, event, &position_map, window, cx);
 6748                        }),
 6749                        _ => {}
 6750                    };
 6751                }
 6752            }
 6753        });
 6754
 6755        window.on_mouse_event({
 6756            let editor = self.editor.clone();
 6757            let position_map = layout.position_map.clone();
 6758
 6759            move |event: &MouseUpEvent, phase, window, cx| {
 6760                if phase == DispatchPhase::Bubble {
 6761                    editor.update(cx, |editor, cx| {
 6762                        Self::mouse_up(editor, event, &position_map, window, cx)
 6763                    });
 6764                }
 6765            }
 6766        });
 6767
 6768        window.on_mouse_event({
 6769            let editor = self.editor.clone();
 6770            let position_map = layout.position_map.clone();
 6771            let mut captured_mouse_down = None;
 6772
 6773            move |event: &MouseUpEvent, phase, window, cx| match phase {
 6774                // Clear the pending mouse down during the capture phase,
 6775                // so that it happens even if another event handler stops
 6776                // propagation.
 6777                DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
 6778                    let pending_mouse_down = editor
 6779                        .pending_mouse_down
 6780                        .get_or_insert_with(Default::default)
 6781                        .clone();
 6782
 6783                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
 6784                    if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
 6785                        captured_mouse_down = pending_mouse_down.take();
 6786                        window.refresh();
 6787                    }
 6788                }),
 6789                // Fire click handlers during the bubble phase.
 6790                DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
 6791                    if let Some(mouse_down) = captured_mouse_down.take() {
 6792                        let event = ClickEvent {
 6793                            down: mouse_down,
 6794                            up: event.clone(),
 6795                        };
 6796                        Self::click(editor, &event, &position_map, window, cx);
 6797                    }
 6798                }),
 6799            }
 6800        });
 6801
 6802        window.on_mouse_event({
 6803            let position_map = layout.position_map.clone();
 6804            let editor = self.editor.clone();
 6805
 6806            move |event: &MouseMoveEvent, phase, window, cx| {
 6807                if phase == DispatchPhase::Bubble {
 6808                    editor.update(cx, |editor, cx| {
 6809                        if editor.hover_state.focused(window, cx) {
 6810                            return;
 6811                        }
 6812                        if event.pressed_button == Some(MouseButton::Left)
 6813                            || event.pressed_button == Some(MouseButton::Middle)
 6814                        {
 6815                            Self::mouse_dragged(editor, event, &position_map, window, cx)
 6816                        }
 6817
 6818                        Self::mouse_moved(editor, event, &position_map, window, cx)
 6819                    });
 6820                }
 6821            }
 6822        });
 6823    }
 6824
 6825    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
 6826        bounds.top_right().x - self.style.scrollbar_width
 6827    }
 6828
 6829    fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
 6830        let style = &self.style;
 6831        let font_size = style.text.font_size.to_pixels(window.rem_size());
 6832        let layout = window.text_system().shape_line(
 6833            SharedString::from(" ".repeat(column)),
 6834            font_size,
 6835            &[TextRun {
 6836                len: column,
 6837                font: style.text.font(),
 6838                color: Hsla::default(),
 6839                background_color: None,
 6840                underline: None,
 6841                strikethrough: None,
 6842            }],
 6843        );
 6844
 6845        layout.width
 6846    }
 6847
 6848    fn max_line_number_width(
 6849        &self,
 6850        snapshot: &EditorSnapshot,
 6851        window: &mut Window,
 6852        cx: &mut App,
 6853    ) -> Pixels {
 6854        let digit_count = snapshot.widest_line_number().ilog10() + 1;
 6855        self.column_pixels(digit_count as usize, window, cx)
 6856    }
 6857
 6858    fn shape_line_number(
 6859        &self,
 6860        text: SharedString,
 6861        color: Hsla,
 6862        window: &mut Window,
 6863    ) -> ShapedLine {
 6864        let run = TextRun {
 6865            len: text.len(),
 6866            font: self.style.text.font(),
 6867            color,
 6868            background_color: None,
 6869            underline: None,
 6870            strikethrough: None,
 6871        };
 6872        window.text_system().shape_line(
 6873            text,
 6874            self.style.text.font_size.to_pixels(window.rem_size()),
 6875            &[run],
 6876        )
 6877    }
 6878
 6879    fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
 6880        let unstaged = status.has_secondary_hunk();
 6881        let unstaged_hollow = ProjectSettings::get_global(cx)
 6882            .git
 6883            .hunk_style
 6884            .map_or(false, |style| {
 6885                matches!(style, GitHunkStyleSetting::UnstagedHollow)
 6886            });
 6887
 6888        unstaged == unstaged_hollow
 6889    }
 6890}
 6891
 6892fn header_jump_data(
 6893    snapshot: &EditorSnapshot,
 6894    block_row_start: DisplayRow,
 6895    height: u32,
 6896    for_excerpt: &ExcerptInfo,
 6897) -> JumpData {
 6898    let range = &for_excerpt.range;
 6899    let buffer = &for_excerpt.buffer;
 6900    let jump_anchor = range.primary.start;
 6901
 6902    let excerpt_start = range.context.start;
 6903    let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
 6904    let rows_from_excerpt_start = if jump_anchor == excerpt_start {
 6905        0
 6906    } else {
 6907        let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
 6908        jump_position.row.saturating_sub(excerpt_start_point.row)
 6909    };
 6910
 6911    let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
 6912        .saturating_sub(
 6913            snapshot
 6914                .scroll_anchor
 6915                .scroll_position(&snapshot.display_snapshot)
 6916                .y as u32,
 6917        );
 6918
 6919    JumpData::MultiBufferPoint {
 6920        excerpt_id: for_excerpt.id,
 6921        anchor: jump_anchor,
 6922        position: jump_position,
 6923        line_offset_from_top,
 6924    }
 6925}
 6926
 6927pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
 6928
 6929impl AcceptEditPredictionBinding {
 6930    pub fn keystroke(&self) -> Option<&Keystroke> {
 6931        if let Some(binding) = self.0.as_ref() {
 6932            match &binding.keystrokes() {
 6933                [keystroke, ..] => Some(keystroke),
 6934                _ => None,
 6935            }
 6936        } else {
 6937            None
 6938        }
 6939    }
 6940}
 6941
 6942fn prepaint_gutter_button(
 6943    button: IconButton,
 6944    row: DisplayRow,
 6945    line_height: Pixels,
 6946    gutter_dimensions: &GutterDimensions,
 6947    scroll_pixel_position: gpui::Point<Pixels>,
 6948    gutter_hitbox: &Hitbox,
 6949    display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 6950    window: &mut Window,
 6951    cx: &mut App,
 6952) -> AnyElement {
 6953    let mut button = button.into_any_element();
 6954
 6955    let available_space = size(
 6956        AvailableSpace::MinContent,
 6957        AvailableSpace::Definite(line_height),
 6958    );
 6959    let indicator_size = button.layout_as_root(available_space, window, cx);
 6960
 6961    let blame_width = gutter_dimensions.git_blame_entries_width;
 6962    let gutter_width = display_hunks
 6963        .binary_search_by(|(hunk, _)| match hunk {
 6964            DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
 6965            DisplayDiffHunk::Unfolded {
 6966                display_row_range, ..
 6967            } => {
 6968                if display_row_range.end <= row {
 6969                    Ordering::Less
 6970                } else if display_row_range.start > row {
 6971                    Ordering::Greater
 6972                } else {
 6973                    Ordering::Equal
 6974                }
 6975            }
 6976        })
 6977        .ok()
 6978        .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
 6979    let left_offset = blame_width.max(gutter_width).unwrap_or_default();
 6980
 6981    let mut x = left_offset;
 6982    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
 6983        - indicator_size.width
 6984        - left_offset;
 6985    x += available_width / 2.;
 6986
 6987    let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
 6988    y += (line_height - indicator_size.height) / 2.;
 6989
 6990    button.prepaint_as_root(
 6991        gutter_hitbox.origin + point(x, y),
 6992        available_space,
 6993        window,
 6994        cx,
 6995    );
 6996    button
 6997}
 6998
 6999fn render_inline_blame_entry(
 7000    blame_entry: BlameEntry,
 7001    style: &EditorStyle,
 7002    cx: &mut App,
 7003) -> Option<AnyElement> {
 7004    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 7005    renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
 7006}
 7007
 7008fn render_blame_entry_popover(
 7009    blame_entry: BlameEntry,
 7010    scroll_handle: ScrollHandle,
 7011    commit_message: Option<ParsedCommitMessage>,
 7012    markdown: Entity<Markdown>,
 7013    workspace: WeakEntity<Workspace>,
 7014    blame: &Entity<GitBlame>,
 7015    window: &mut Window,
 7016    cx: &mut App,
 7017) -> Option<AnyElement> {
 7018    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 7019    let blame = blame.read(cx);
 7020    let repository = blame.repository(cx)?.clone();
 7021    renderer.render_blame_entry_popover(
 7022        blame_entry,
 7023        scroll_handle,
 7024        commit_message,
 7025        markdown,
 7026        repository,
 7027        workspace,
 7028        window,
 7029        cx,
 7030    )
 7031}
 7032
 7033fn render_blame_entry(
 7034    ix: usize,
 7035    blame: &Entity<GitBlame>,
 7036    blame_entry: BlameEntry,
 7037    style: &EditorStyle,
 7038    last_used_color: &mut Option<(PlayerColor, Oid)>,
 7039    editor: Entity<Editor>,
 7040    workspace: Entity<Workspace>,
 7041    renderer: Arc<dyn BlameRenderer>,
 7042    cx: &mut App,
 7043) -> Option<AnyElement> {
 7044    let mut sha_color = cx
 7045        .theme()
 7046        .players()
 7047        .color_for_participant(blame_entry.sha.into());
 7048
 7049    // If the last color we used is the same as the one we get for this line, but
 7050    // the commit SHAs are different, then we try again to get a different color.
 7051    match *last_used_color {
 7052        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
 7053            let index: u32 = blame_entry.sha.into();
 7054            sha_color = cx.theme().players().color_for_participant(index + 1);
 7055        }
 7056        _ => {}
 7057    };
 7058    last_used_color.replace((sha_color, blame_entry.sha));
 7059
 7060    let blame = blame.read(cx);
 7061    let details = blame.details_for_entry(&blame_entry);
 7062    let repository = blame.repository(cx)?;
 7063    renderer.render_blame_entry(
 7064        &style.text,
 7065        blame_entry,
 7066        details,
 7067        repository,
 7068        workspace.downgrade(),
 7069        editor,
 7070        ix,
 7071        sha_color.cursor,
 7072        cx,
 7073    )
 7074}
 7075
 7076#[derive(Debug)]
 7077pub(crate) struct LineWithInvisibles {
 7078    fragments: SmallVec<[LineFragment; 1]>,
 7079    invisibles: Vec<Invisible>,
 7080    len: usize,
 7081    pub(crate) width: Pixels,
 7082    font_size: Pixels,
 7083}
 7084
 7085enum LineFragment {
 7086    Text(ShapedLine),
 7087    Element {
 7088        id: FoldId,
 7089        element: Option<AnyElement>,
 7090        size: Size<Pixels>,
 7091        len: usize,
 7092    },
 7093}
 7094
 7095impl fmt::Debug for LineFragment {
 7096    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 7097        match self {
 7098            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
 7099            LineFragment::Element { size, len, .. } => f
 7100                .debug_struct("Element")
 7101                .field("size", size)
 7102                .field("len", len)
 7103                .finish(),
 7104        }
 7105    }
 7106}
 7107
 7108impl LineWithInvisibles {
 7109    fn from_chunks<'a>(
 7110        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
 7111        editor_style: &EditorStyle,
 7112        max_line_len: usize,
 7113        max_line_count: usize,
 7114        editor_mode: &EditorMode,
 7115        text_width: Pixels,
 7116        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 7117        window: &mut Window,
 7118        cx: &mut App,
 7119    ) -> Vec<Self> {
 7120        let text_style = &editor_style.text;
 7121        let mut layouts = Vec::with_capacity(max_line_count);
 7122        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
 7123        let mut line = String::new();
 7124        let mut invisibles = Vec::new();
 7125        let mut width = Pixels::ZERO;
 7126        let mut len = 0;
 7127        let mut styles = Vec::new();
 7128        let mut non_whitespace_added = false;
 7129        let mut row = 0;
 7130        let mut line_exceeded_max_len = false;
 7131        let font_size = text_style.font_size.to_pixels(window.rem_size());
 7132
 7133        let ellipsis = SharedString::from("");
 7134
 7135        for highlighted_chunk in chunks.chain([HighlightedChunk {
 7136            text: "\n",
 7137            style: None,
 7138            is_tab: false,
 7139            is_inlay: false,
 7140            replacement: None,
 7141        }]) {
 7142            if let Some(replacement) = highlighted_chunk.replacement {
 7143                if !line.is_empty() {
 7144                    let shaped_line =
 7145                        window
 7146                            .text_system()
 7147                            .shape_line(line.clone().into(), font_size, &styles);
 7148                    width += shaped_line.width;
 7149                    len += shaped_line.len;
 7150                    fragments.push(LineFragment::Text(shaped_line));
 7151                    line.clear();
 7152                    styles.clear();
 7153                }
 7154
 7155                match replacement {
 7156                    ChunkReplacement::Renderer(renderer) => {
 7157                        let available_width = if renderer.constrain_width {
 7158                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
 7159                                ellipsis.clone()
 7160                            } else {
 7161                                SharedString::from(Arc::from(highlighted_chunk.text))
 7162                            };
 7163                            let shaped_line = window.text_system().shape_line(
 7164                                chunk,
 7165                                font_size,
 7166                                &[text_style.to_run(highlighted_chunk.text.len())],
 7167                            );
 7168                            AvailableSpace::Definite(shaped_line.width)
 7169                        } else {
 7170                            AvailableSpace::MinContent
 7171                        };
 7172
 7173                        let mut element = (renderer.render)(&mut ChunkRendererContext {
 7174                            context: cx,
 7175                            window,
 7176                            max_width: text_width,
 7177                        });
 7178                        let line_height = text_style.line_height_in_pixels(window.rem_size());
 7179                        let size = element.layout_as_root(
 7180                            size(available_width, AvailableSpace::Definite(line_height)),
 7181                            window,
 7182                            cx,
 7183                        );
 7184
 7185                        width += size.width;
 7186                        len += highlighted_chunk.text.len();
 7187                        fragments.push(LineFragment::Element {
 7188                            id: renderer.id,
 7189                            element: Some(element),
 7190                            size,
 7191                            len: highlighted_chunk.text.len(),
 7192                        });
 7193                    }
 7194                    ChunkReplacement::Str(x) => {
 7195                        let text_style = if let Some(style) = highlighted_chunk.style {
 7196                            Cow::Owned(text_style.clone().highlight(style))
 7197                        } else {
 7198                            Cow::Borrowed(text_style)
 7199                        };
 7200
 7201                        let run = TextRun {
 7202                            len: x.len(),
 7203                            font: text_style.font(),
 7204                            color: text_style.color,
 7205                            background_color: text_style.background_color,
 7206                            underline: text_style.underline,
 7207                            strikethrough: text_style.strikethrough,
 7208                        };
 7209                        let line_layout = window
 7210                            .text_system()
 7211                            .shape_line(x, font_size, &[run])
 7212                            .with_len(highlighted_chunk.text.len());
 7213
 7214                        width += line_layout.width;
 7215                        len += highlighted_chunk.text.len();
 7216                        fragments.push(LineFragment::Text(line_layout))
 7217                    }
 7218                }
 7219            } else {
 7220                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
 7221                    if ix > 0 {
 7222                        let shaped_line = window.text_system().shape_line(
 7223                            line.clone().into(),
 7224                            font_size,
 7225                            &styles,
 7226                        );
 7227                        width += shaped_line.width;
 7228                        len += shaped_line.len;
 7229                        fragments.push(LineFragment::Text(shaped_line));
 7230                        layouts.push(Self {
 7231                            width: mem::take(&mut width),
 7232                            len: mem::take(&mut len),
 7233                            fragments: mem::take(&mut fragments),
 7234                            invisibles: std::mem::take(&mut invisibles),
 7235                            font_size,
 7236                        });
 7237
 7238                        line.clear();
 7239                        styles.clear();
 7240                        row += 1;
 7241                        line_exceeded_max_len = false;
 7242                        non_whitespace_added = false;
 7243                        if row == max_line_count {
 7244                            return layouts;
 7245                        }
 7246                    }
 7247
 7248                    if !line_chunk.is_empty() && !line_exceeded_max_len {
 7249                        let text_style = if let Some(style) = highlighted_chunk.style {
 7250                            Cow::Owned(text_style.clone().highlight(style))
 7251                        } else {
 7252                            Cow::Borrowed(text_style)
 7253                        };
 7254
 7255                        if line.len() + line_chunk.len() > max_line_len {
 7256                            let mut chunk_len = max_line_len - line.len();
 7257                            while !line_chunk.is_char_boundary(chunk_len) {
 7258                                chunk_len -= 1;
 7259                            }
 7260                            line_chunk = &line_chunk[..chunk_len];
 7261                            line_exceeded_max_len = true;
 7262                        }
 7263
 7264                        styles.push(TextRun {
 7265                            len: line_chunk.len(),
 7266                            font: text_style.font(),
 7267                            color: text_style.color,
 7268                            background_color: text_style.background_color,
 7269                            underline: text_style.underline,
 7270                            strikethrough: text_style.strikethrough,
 7271                        });
 7272
 7273                        if editor_mode.is_full() && !highlighted_chunk.is_inlay {
 7274                            // Line wrap pads its contents with fake whitespaces,
 7275                            // avoid printing them
 7276                            let is_soft_wrapped = is_row_soft_wrapped(row);
 7277                            if highlighted_chunk.is_tab {
 7278                                if non_whitespace_added || !is_soft_wrapped {
 7279                                    invisibles.push(Invisible::Tab {
 7280                                        line_start_offset: line.len(),
 7281                                        line_end_offset: line.len() + line_chunk.len(),
 7282                                    });
 7283                                }
 7284                            } else {
 7285                                invisibles.extend(line_chunk.char_indices().filter_map(
 7286                                    |(index, c)| {
 7287                                        let is_whitespace = c.is_whitespace();
 7288                                        non_whitespace_added |= !is_whitespace;
 7289                                        if is_whitespace
 7290                                            && (non_whitespace_added || !is_soft_wrapped)
 7291                                        {
 7292                                            Some(Invisible::Whitespace {
 7293                                                line_offset: line.len() + index,
 7294                                            })
 7295                                        } else {
 7296                                            None
 7297                                        }
 7298                                    },
 7299                                ))
 7300                            }
 7301                        }
 7302
 7303                        line.push_str(line_chunk);
 7304                    }
 7305                }
 7306            }
 7307        }
 7308
 7309        layouts
 7310    }
 7311
 7312    fn prepaint(
 7313        &mut self,
 7314        line_height: Pixels,
 7315        scroll_pixel_position: gpui::Point<Pixels>,
 7316        row: DisplayRow,
 7317        content_origin: gpui::Point<Pixels>,
 7318        line_elements: &mut SmallVec<[AnyElement; 1]>,
 7319        window: &mut Window,
 7320        cx: &mut App,
 7321    ) {
 7322        let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
 7323        let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
 7324        for fragment in &mut self.fragments {
 7325            match fragment {
 7326                LineFragment::Text(line) => {
 7327                    fragment_origin.x += line.width;
 7328                }
 7329                LineFragment::Element { element, size, .. } => {
 7330                    let mut element = element
 7331                        .take()
 7332                        .expect("you can't prepaint LineWithInvisibles twice");
 7333
 7334                    // Center the element vertically within the line.
 7335                    let mut element_origin = fragment_origin;
 7336                    element_origin.y += (line_height - size.height) / 2.;
 7337                    element.prepaint_at(element_origin, window, cx);
 7338                    line_elements.push(element);
 7339
 7340                    fragment_origin.x += size.width;
 7341                }
 7342            }
 7343        }
 7344    }
 7345
 7346    fn draw(
 7347        &self,
 7348        layout: &EditorLayout,
 7349        row: DisplayRow,
 7350        content_origin: gpui::Point<Pixels>,
 7351        whitespace_setting: ShowWhitespaceSetting,
 7352        selection_ranges: &[Range<DisplayPoint>],
 7353        window: &mut Window,
 7354        cx: &mut App,
 7355    ) {
 7356        let line_height = layout.position_map.line_height;
 7357        let line_y = line_height
 7358            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
 7359
 7360        let mut fragment_origin =
 7361            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
 7362
 7363        for fragment in &self.fragments {
 7364            match fragment {
 7365                LineFragment::Text(line) => {
 7366                    line.paint(fragment_origin, line_height, window, cx)
 7367                        .log_err();
 7368                    fragment_origin.x += line.width;
 7369                }
 7370                LineFragment::Element { size, .. } => {
 7371                    fragment_origin.x += size.width;
 7372                }
 7373            }
 7374        }
 7375
 7376        self.draw_invisibles(
 7377            selection_ranges,
 7378            layout,
 7379            content_origin,
 7380            line_y,
 7381            row,
 7382            line_height,
 7383            whitespace_setting,
 7384            window,
 7385            cx,
 7386        );
 7387    }
 7388
 7389    fn draw_background(
 7390        &self,
 7391        layout: &EditorLayout,
 7392        row: DisplayRow,
 7393        content_origin: gpui::Point<Pixels>,
 7394        window: &mut Window,
 7395        cx: &mut App,
 7396    ) {
 7397        let line_height = layout.position_map.line_height;
 7398        let line_y = line_height
 7399            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
 7400
 7401        let mut fragment_origin =
 7402            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
 7403
 7404        for fragment in &self.fragments {
 7405            match fragment {
 7406                LineFragment::Text(line) => {
 7407                    line.paint_background(fragment_origin, line_height, window, cx)
 7408                        .log_err();
 7409                    fragment_origin.x += line.width;
 7410                }
 7411                LineFragment::Element { size, .. } => {
 7412                    fragment_origin.x += size.width;
 7413                }
 7414            }
 7415        }
 7416    }
 7417
 7418    fn draw_invisibles(
 7419        &self,
 7420        selection_ranges: &[Range<DisplayPoint>],
 7421        layout: &EditorLayout,
 7422        content_origin: gpui::Point<Pixels>,
 7423        line_y: Pixels,
 7424        row: DisplayRow,
 7425        line_height: Pixels,
 7426        whitespace_setting: ShowWhitespaceSetting,
 7427        window: &mut Window,
 7428        cx: &mut App,
 7429    ) {
 7430        let extract_whitespace_info = |invisible: &Invisible| {
 7431            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
 7432                Invisible::Tab {
 7433                    line_start_offset,
 7434                    line_end_offset,
 7435                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
 7436                Invisible::Whitespace { line_offset } => {
 7437                    (*line_offset, line_offset + 1, &layout.space_invisible)
 7438                }
 7439            };
 7440
 7441            let x_offset = self.x_for_index(token_offset);
 7442            let invisible_offset =
 7443                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
 7444            let origin = content_origin
 7445                + gpui::point(
 7446                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
 7447                    line_y,
 7448                );
 7449
 7450            (
 7451                [token_offset, token_end_offset],
 7452                Box::new(move |window: &mut Window, cx: &mut App| {
 7453                    invisible_symbol
 7454                        .paint(origin, line_height, window, cx)
 7455                        .log_err();
 7456                }),
 7457            )
 7458        };
 7459
 7460        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
 7461        match whitespace_setting {
 7462            ShowWhitespaceSetting::None => (),
 7463            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
 7464            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
 7465                let invisible_point = DisplayPoint::new(row, start as u32);
 7466                if !selection_ranges
 7467                    .iter()
 7468                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
 7469                {
 7470                    return;
 7471                }
 7472
 7473                paint(window, cx);
 7474            }),
 7475
 7476            ShowWhitespaceSetting::Trailing => {
 7477                let mut previous_start = self.len;
 7478                for ([start, end], paint) in invisible_iter.rev() {
 7479                    if previous_start != end {
 7480                        break;
 7481                    }
 7482                    previous_start = start;
 7483                    paint(window, cx);
 7484                }
 7485            }
 7486
 7487            // For a whitespace to be on a boundary, any of the following conditions need to be met:
 7488            // - It is a tab
 7489            // - It is adjacent to an edge (start or end)
 7490            // - It is adjacent to a whitespace (left or right)
 7491            ShowWhitespaceSetting::Boundary => {
 7492                // 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
 7493                // the above cases.
 7494                // Note: We zip in the original `invisibles` to check for tab equality
 7495                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
 7496                for (([start, end], paint), invisible) in
 7497                    invisible_iter.zip_eq(self.invisibles.iter())
 7498                {
 7499                    let should_render = match (&last_seen, invisible) {
 7500                        (_, Invisible::Tab { .. }) => true,
 7501                        (Some((_, last_end, _)), _) => *last_end == start,
 7502                        _ => false,
 7503                    };
 7504
 7505                    if should_render || start == 0 || end == self.len {
 7506                        paint(window, cx);
 7507
 7508                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
 7509                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
 7510                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
 7511                            // Note that we need to make sure that the last one is actually adjacent
 7512                            if !should_render_last && last_end == start {
 7513                                paint_last(window, cx);
 7514                            }
 7515                        }
 7516                    }
 7517
 7518                    // Manually render anything within a selection
 7519                    let invisible_point = DisplayPoint::new(row, start as u32);
 7520                    if selection_ranges.iter().any(|region| {
 7521                        region.start <= invisible_point && invisible_point < region.end
 7522                    }) {
 7523                        paint(window, cx);
 7524                    }
 7525
 7526                    last_seen = Some((should_render, end, paint));
 7527                }
 7528            }
 7529        }
 7530    }
 7531
 7532    pub fn x_for_index(&self, index: usize) -> Pixels {
 7533        let mut fragment_start_x = Pixels::ZERO;
 7534        let mut fragment_start_index = 0;
 7535
 7536        for fragment in &self.fragments {
 7537            match fragment {
 7538                LineFragment::Text(shaped_line) => {
 7539                    let fragment_end_index = fragment_start_index + shaped_line.len;
 7540                    if index < fragment_end_index {
 7541                        return fragment_start_x
 7542                            + shaped_line.x_for_index(index - fragment_start_index);
 7543                    }
 7544                    fragment_start_x += shaped_line.width;
 7545                    fragment_start_index = fragment_end_index;
 7546                }
 7547                LineFragment::Element { len, size, .. } => {
 7548                    let fragment_end_index = fragment_start_index + len;
 7549                    if index < fragment_end_index {
 7550                        return fragment_start_x;
 7551                    }
 7552                    fragment_start_x += size.width;
 7553                    fragment_start_index = fragment_end_index;
 7554                }
 7555            }
 7556        }
 7557
 7558        fragment_start_x
 7559    }
 7560
 7561    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
 7562        let mut fragment_start_x = Pixels::ZERO;
 7563        let mut fragment_start_index = 0;
 7564
 7565        for fragment in &self.fragments {
 7566            match fragment {
 7567                LineFragment::Text(shaped_line) => {
 7568                    let fragment_end_x = fragment_start_x + shaped_line.width;
 7569                    if x < fragment_end_x {
 7570                        return Some(
 7571                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
 7572                        );
 7573                    }
 7574                    fragment_start_x = fragment_end_x;
 7575                    fragment_start_index += shaped_line.len;
 7576                }
 7577                LineFragment::Element { len, size, .. } => {
 7578                    let fragment_end_x = fragment_start_x + size.width;
 7579                    if x < fragment_end_x {
 7580                        return Some(fragment_start_index);
 7581                    }
 7582                    fragment_start_index += len;
 7583                    fragment_start_x = fragment_end_x;
 7584                }
 7585            }
 7586        }
 7587
 7588        None
 7589    }
 7590
 7591    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
 7592        let mut fragment_start_index = 0;
 7593
 7594        for fragment in &self.fragments {
 7595            match fragment {
 7596                LineFragment::Text(shaped_line) => {
 7597                    let fragment_end_index = fragment_start_index + shaped_line.len;
 7598                    if index < fragment_end_index {
 7599                        return shaped_line.font_id_for_index(index - fragment_start_index);
 7600                    }
 7601                    fragment_start_index = fragment_end_index;
 7602                }
 7603                LineFragment::Element { len, .. } => {
 7604                    let fragment_end_index = fragment_start_index + len;
 7605                    if index < fragment_end_index {
 7606                        return None;
 7607                    }
 7608                    fragment_start_index = fragment_end_index;
 7609                }
 7610            }
 7611        }
 7612
 7613        None
 7614    }
 7615}
 7616
 7617#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 7618enum Invisible {
 7619    /// A tab character
 7620    ///
 7621    /// A tab character is internally represented by spaces (configured by the user's tab width)
 7622    /// aligned to the nearest column, so it's necessary to store the start and end offset for
 7623    /// adjacency checks.
 7624    Tab {
 7625        line_start_offset: usize,
 7626        line_end_offset: usize,
 7627    },
 7628    Whitespace {
 7629        line_offset: usize,
 7630    },
 7631}
 7632
 7633impl EditorElement {
 7634    /// Returns the rem size to use when rendering the [`EditorElement`].
 7635    ///
 7636    /// This allows UI elements to scale based on the `buffer_font_size`.
 7637    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
 7638        match self.editor.read(cx).mode {
 7639            EditorMode::Full {
 7640                scale_ui_elements_with_buffer_font_size: true,
 7641                ..
 7642            }
 7643            | EditorMode::Minimap { .. } => {
 7644                let buffer_font_size = self.style.text.font_size;
 7645                match buffer_font_size {
 7646                    AbsoluteLength::Pixels(pixels) => {
 7647                        let rem_size_scale = {
 7648                            // Our default UI font size is 14px on a 16px base scale.
 7649                            // This means the default UI font size is 0.875rems.
 7650                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
 7651
 7652                            // We then determine the delta between a single rem and the default font
 7653                            // size scale.
 7654                            let default_font_size_delta = 1. - default_font_size_scale;
 7655
 7656                            // Finally, we add this delta to 1rem to get the scale factor that
 7657                            // should be used to scale up the UI.
 7658                            1. + default_font_size_delta
 7659                        };
 7660
 7661                        Some(pixels * rem_size_scale)
 7662                    }
 7663                    AbsoluteLength::Rems(rems) => {
 7664                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
 7665                    }
 7666                }
 7667            }
 7668            // We currently use single-line and auto-height editors in UI contexts,
 7669            // so we don't want to scale everything with the buffer font size, as it
 7670            // ends up looking off.
 7671            _ => None,
 7672        }
 7673    }
 7674
 7675    fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
 7676        if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
 7677            parent.upgrade()
 7678        } else {
 7679            Some(self.editor.clone())
 7680        }
 7681    }
 7682}
 7683
 7684impl Element for EditorElement {
 7685    type RequestLayoutState = ();
 7686    type PrepaintState = EditorLayout;
 7687
 7688    fn id(&self) -> Option<ElementId> {
 7689        None
 7690    }
 7691
 7692    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
 7693        None
 7694    }
 7695
 7696    fn request_layout(
 7697        &mut self,
 7698        _: Option<&GlobalElementId>,
 7699        _inspector_id: Option<&gpui::InspectorElementId>,
 7700        window: &mut Window,
 7701        cx: &mut App,
 7702    ) -> (gpui::LayoutId, ()) {
 7703        let rem_size = self.rem_size(cx);
 7704        window.with_rem_size(rem_size, |window| {
 7705            self.editor.update(cx, |editor, cx| {
 7706                editor.set_style(self.style.clone(), window, cx);
 7707
 7708                let layout_id = match editor.mode {
 7709                    EditorMode::SingleLine { auto_width } => {
 7710                        let rem_size = window.rem_size();
 7711
 7712                        let height = self.style.text.line_height_in_pixels(rem_size);
 7713                        if auto_width {
 7714                            let editor_handle = cx.entity().clone();
 7715                            let style = self.style.clone();
 7716                            window.request_measured_layout(
 7717                                Style::default(),
 7718                                move |_, _, window, cx| {
 7719                                    let editor_snapshot = editor_handle
 7720                                        .update(cx, |editor, cx| editor.snapshot(window, cx));
 7721                                    let line = Self::layout_lines(
 7722                                        DisplayRow(0)..DisplayRow(1),
 7723                                        &editor_snapshot,
 7724                                        &style,
 7725                                        px(f32::MAX),
 7726                                        |_| false, // Single lines never soft wrap
 7727                                        window,
 7728                                        cx,
 7729                                    )
 7730                                    .pop()
 7731                                    .unwrap();
 7732
 7733                                    let font_id =
 7734                                        window.text_system().resolve_font(&style.text.font());
 7735                                    let font_size =
 7736                                        style.text.font_size.to_pixels(window.rem_size());
 7737                                    let em_width =
 7738                                        window.text_system().em_width(font_id, font_size).unwrap();
 7739
 7740                                    size(line.width + em_width, height)
 7741                                },
 7742                            )
 7743                        } else {
 7744                            let mut style = Style::default();
 7745                            style.size.height = height.into();
 7746                            style.size.width = relative(1.).into();
 7747                            window.request_layout(style, None, cx)
 7748                        }
 7749                    }
 7750                    EditorMode::AutoHeight {
 7751                        min_lines,
 7752                        max_lines,
 7753                    } => {
 7754                        let editor_handle = cx.entity().clone();
 7755                        let max_line_number_width =
 7756                            self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
 7757                        window.request_measured_layout(
 7758                            Style::default(),
 7759                            move |known_dimensions, available_space, window, cx| {
 7760                                editor_handle
 7761                                    .update(cx, |editor, cx| {
 7762                                        compute_auto_height_layout(
 7763                                            editor,
 7764                                            min_lines,
 7765                                            max_lines,
 7766                                            max_line_number_width,
 7767                                            known_dimensions,
 7768                                            available_space.width,
 7769                                            window,
 7770                                            cx,
 7771                                        )
 7772                                    })
 7773                                    .unwrap_or_default()
 7774                            },
 7775                        )
 7776                    }
 7777                    EditorMode::Minimap { .. } => {
 7778                        let mut style = Style::default();
 7779                        style.size.width = relative(1.).into();
 7780                        style.size.height = relative(1.).into();
 7781                        window.request_layout(style, None, cx)
 7782                    }
 7783                    EditorMode::Full {
 7784                        sized_by_content, ..
 7785                    } => {
 7786                        let mut style = Style::default();
 7787                        style.size.width = relative(1.).into();
 7788                        if sized_by_content {
 7789                            let snapshot = editor.snapshot(window, cx);
 7790                            let line_height =
 7791                                self.style.text.line_height_in_pixels(window.rem_size());
 7792                            let scroll_height =
 7793                                (snapshot.max_point().row().next_row().0 as f32) * line_height;
 7794                            style.size.height = scroll_height.into();
 7795                        } else {
 7796                            style.size.height = relative(1.).into();
 7797                        }
 7798                        window.request_layout(style, None, cx)
 7799                    }
 7800                };
 7801
 7802                (layout_id, ())
 7803            })
 7804        })
 7805    }
 7806
 7807    fn prepaint(
 7808        &mut self,
 7809        _: Option<&GlobalElementId>,
 7810        _inspector_id: Option<&gpui::InspectorElementId>,
 7811        bounds: Bounds<Pixels>,
 7812        _: &mut Self::RequestLayoutState,
 7813        window: &mut Window,
 7814        cx: &mut App,
 7815    ) -> Self::PrepaintState {
 7816        let text_style = TextStyleRefinement {
 7817            font_size: Some(self.style.text.font_size),
 7818            line_height: Some(self.style.text.line_height),
 7819            ..Default::default()
 7820        };
 7821        let focus_handle = self.editor.focus_handle(cx);
 7822        window.set_view_id(self.editor.entity_id());
 7823        window.set_focus_handle(&focus_handle, cx);
 7824
 7825        let rem_size = self.rem_size(cx);
 7826        window.with_rem_size(rem_size, |window| {
 7827            window.with_text_style(Some(text_style), |window| {
 7828                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 7829                    let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
 7830                        (editor.snapshot(window, cx), editor.read_only(cx))
 7831                    });
 7832                    let style = self.style.clone();
 7833
 7834                    let font_id = window.text_system().resolve_font(&style.text.font());
 7835                    let font_size = style.text.font_size.to_pixels(window.rem_size());
 7836                    let line_height = style.text.line_height_in_pixels(window.rem_size());
 7837                    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
 7838                    let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
 7839                    let glyph_grid_cell = size(em_advance, line_height);
 7840
 7841                    let gutter_dimensions = snapshot
 7842                        .gutter_dimensions(
 7843                            font_id,
 7844                            font_size,
 7845                            self.max_line_number_width(&snapshot, window, cx),
 7846                            cx,
 7847                        )
 7848                        .or_else(|| {
 7849                            self.editor.read(cx).offset_content.then(|| {
 7850                                GutterDimensions::default_with_margin(font_id, font_size, cx)
 7851                            })
 7852                        })
 7853                        .unwrap_or_default();
 7854                    let text_width = bounds.size.width - gutter_dimensions.width;
 7855
 7856                    let settings = EditorSettings::get_global(cx);
 7857                    let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
 7858                    let vertical_scrollbar_width = (scrollbars_shown
 7859                        && settings.scrollbar.axes.vertical
 7860                        && self.editor.read(cx).show_scrollbars.vertical)
 7861                        .then_some(style.scrollbar_width)
 7862                        .unwrap_or_default();
 7863                    let minimap_width = self
 7864                        .editor
 7865                        .read(cx)
 7866                        .minimap()
 7867                        .is_some()
 7868                        .then(|| match settings.minimap.show {
 7869                            ShowMinimap::Auto => {
 7870                                scrollbars_shown.then_some(MinimapLayout::MINIMAP_WIDTH)
 7871                            }
 7872                            _ => Some(MinimapLayout::MINIMAP_WIDTH),
 7873                        })
 7874                        .flatten()
 7875                        .filter(|minimap_width| {
 7876                            text_width - vertical_scrollbar_width - *minimap_width > *minimap_width
 7877                        })
 7878                        .unwrap_or_default();
 7879
 7880                    let right_margin = minimap_width + vertical_scrollbar_width;
 7881
 7882                    let editor_width =
 7883                        text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
 7884
 7885                    let editor_margins = EditorMargins {
 7886                        gutter: gutter_dimensions,
 7887                        right: right_margin,
 7888                    };
 7889
 7890                    // Offset the content_bounds from the text_bounds by the gutter margin (which
 7891                    // is roughly half a character wide) to make hit testing work more like how we want.
 7892                    let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
 7893
 7894                    let editor_content_width = editor_width - content_offset.x;
 7895
 7896                    snapshot = self.editor.update(cx, |editor, cx| {
 7897                        editor.last_bounds = Some(bounds);
 7898                        editor.gutter_dimensions = gutter_dimensions;
 7899                        editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
 7900
 7901                        if matches!(
 7902                            editor.mode,
 7903                            EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
 7904                        ) {
 7905                            snapshot
 7906                        } else {
 7907                            let wrap_width_for = |column: u32| (column as f32 * em_advance).ceil();
 7908                            let wrap_width = match editor.soft_wrap_mode(cx) {
 7909                                SoftWrap::GitDiff => None,
 7910                                SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
 7911                                SoftWrap::EditorWidth => Some(editor_content_width),
 7912                                SoftWrap::Column(column) => Some(wrap_width_for(column)),
 7913                                SoftWrap::Bounded(column) => {
 7914                                    Some(editor_content_width.min(wrap_width_for(column)))
 7915                                }
 7916                            };
 7917
 7918                            if editor.set_wrap_width(wrap_width, cx) {
 7919                                editor.snapshot(window, cx)
 7920                            } else {
 7921                                snapshot
 7922                            }
 7923                        }
 7924                    });
 7925
 7926                    let wrap_guides = self
 7927                        .editor
 7928                        .read(cx)
 7929                        .wrap_guides(cx)
 7930                        .iter()
 7931                        .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
 7932                        .collect::<SmallVec<[_; 2]>>();
 7933
 7934                    let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
 7935                    let gutter_hitbox = window.insert_hitbox(
 7936                        gutter_bounds(bounds, gutter_dimensions),
 7937                        HitboxBehavior::Normal,
 7938                    );
 7939                    let text_hitbox = window.insert_hitbox(
 7940                        Bounds {
 7941                            origin: gutter_hitbox.top_right(),
 7942                            size: size(text_width, bounds.size.height),
 7943                        },
 7944                        HitboxBehavior::Normal,
 7945                    );
 7946
 7947                    let content_origin = text_hitbox.origin + content_offset;
 7948
 7949                    let editor_text_bounds =
 7950                        Bounds::from_corners(content_origin, bounds.bottom_right());
 7951
 7952                    let height_in_lines = editor_text_bounds.size.height / line_height;
 7953
 7954                    let max_row = snapshot.max_point().row().as_f32();
 7955
 7956                    // The max scroll position for the top of the window
 7957                    let max_scroll_top = if matches!(
 7958                        snapshot.mode,
 7959                        EditorMode::SingleLine { .. }
 7960                            | EditorMode::AutoHeight { .. }
 7961                            | EditorMode::Full {
 7962                                sized_by_content: true,
 7963                                ..
 7964                            }
 7965                    ) {
 7966                        (max_row - height_in_lines + 1.).max(0.)
 7967                    } else {
 7968                        let settings = EditorSettings::get_global(cx);
 7969                        match settings.scroll_beyond_last_line {
 7970                            ScrollBeyondLastLine::OnePage => max_row,
 7971                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
 7972                            ScrollBeyondLastLine::VerticalScrollMargin => {
 7973                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
 7974                                    .max(0.)
 7975                            }
 7976                        }
 7977                    };
 7978
 7979                    // TODO: Autoscrolling for both axes
 7980                    let mut autoscroll_request = None;
 7981                    let mut autoscroll_containing_element = false;
 7982                    let mut autoscroll_horizontally = false;
 7983                    self.editor.update(cx, |editor, cx| {
 7984                        autoscroll_request = editor.autoscroll_request();
 7985                        autoscroll_containing_element =
 7986                            autoscroll_request.is_some() || editor.has_pending_selection();
 7987                        // TODO: Is this horizontal or vertical?!
 7988                        autoscroll_horizontally = editor.autoscroll_vertically(
 7989                            bounds,
 7990                            line_height,
 7991                            max_scroll_top,
 7992                            window,
 7993                            cx,
 7994                        );
 7995                        snapshot = editor.snapshot(window, cx);
 7996                    });
 7997
 7998                    let mut scroll_position = snapshot.scroll_position();
 7999                    // The scroll position is a fractional point, the whole number of which represents
 8000                    // the top of the window in terms of display rows.
 8001                    let start_row = DisplayRow(scroll_position.y as u32);
 8002                    let max_row = snapshot.max_point().row();
 8003                    let end_row = cmp::min(
 8004                        (scroll_position.y + height_in_lines).ceil() as u32,
 8005                        max_row.next_row().0,
 8006                    );
 8007                    let end_row = DisplayRow(end_row);
 8008
 8009                    let row_infos = snapshot
 8010                        .row_infos(start_row)
 8011                        .take((start_row..end_row).len())
 8012                        .collect::<Vec<RowInfo>>();
 8013                    let is_row_soft_wrapped = |row: usize| {
 8014                        row_infos
 8015                            .get(row)
 8016                            .map_or(true, |info| info.buffer_row.is_none())
 8017                    };
 8018
 8019                    let start_anchor = if start_row == Default::default() {
 8020                        Anchor::min()
 8021                    } else {
 8022                        snapshot.buffer_snapshot.anchor_before(
 8023                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
 8024                        )
 8025                    };
 8026                    let end_anchor = if end_row > max_row {
 8027                        Anchor::max()
 8028                    } else {
 8029                        snapshot.buffer_snapshot.anchor_before(
 8030                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
 8031                        )
 8032                    };
 8033
 8034                    let mut highlighted_rows = self
 8035                        .editor
 8036                        .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
 8037
 8038                    let is_light = cx.theme().appearance().is_light();
 8039
 8040                    for (ix, row_info) in row_infos.iter().enumerate() {
 8041                        let Some(diff_status) = row_info.diff_status else {
 8042                            continue;
 8043                        };
 8044
 8045                        let background_color = match diff_status.kind {
 8046                            DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
 8047                            DiffHunkStatusKind::Deleted => {
 8048                                cx.theme().colors().version_control_deleted
 8049                            }
 8050                            DiffHunkStatusKind::Modified => {
 8051                                debug_panic!("modified diff status for row info");
 8052                                continue;
 8053                            }
 8054                        };
 8055
 8056                        let hunk_opacity = if is_light { 0.16 } else { 0.12 };
 8057
 8058                        let hollow_highlight = LineHighlight {
 8059                            background: (background_color.opacity(if is_light {
 8060                                0.08
 8061                            } else {
 8062                                0.06
 8063                            }))
 8064                            .into(),
 8065                            border: Some(if is_light {
 8066                                background_color.opacity(0.48)
 8067                            } else {
 8068                                background_color.opacity(0.36)
 8069                            }),
 8070                            include_gutter: true,
 8071                            type_id: None,
 8072                        };
 8073
 8074                        let filled_highlight = LineHighlight {
 8075                            background: solid_background(background_color.opacity(hunk_opacity)),
 8076                            border: None,
 8077                            include_gutter: true,
 8078                            type_id: None,
 8079                        };
 8080
 8081                        let background = if Self::diff_hunk_hollow(diff_status, cx) {
 8082                            hollow_highlight
 8083                        } else {
 8084                            filled_highlight
 8085                        };
 8086
 8087                        highlighted_rows
 8088                            .entry(start_row + DisplayRow(ix as u32))
 8089                            .or_insert(background);
 8090                    }
 8091
 8092                    let highlighted_ranges = self
 8093                        .editor_with_selections(cx)
 8094                        .map(|editor| {
 8095                            editor.read(cx).background_highlights_in_range(
 8096                                start_anchor..end_anchor,
 8097                                &snapshot.display_snapshot,
 8098                                cx.theme(),
 8099                            )
 8100                        })
 8101                        .unwrap_or_default();
 8102                    let highlighted_gutter_ranges =
 8103                        self.editor.read(cx).gutter_highlights_in_range(
 8104                            start_anchor..end_anchor,
 8105                            &snapshot.display_snapshot,
 8106                            cx,
 8107                        );
 8108
 8109                    let document_colors = self
 8110                        .editor
 8111                        .read(cx)
 8112                        .colors
 8113                        .as_ref()
 8114                        .map(|colors| colors.editor_display_highlights(&snapshot));
 8115                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
 8116                        start_anchor..end_anchor,
 8117                        &snapshot.display_snapshot,
 8118                        cx,
 8119                    );
 8120
 8121                    let (local_selections, selected_buffer_ids): (
 8122                        Vec<Selection<Point>>,
 8123                        Vec<BufferId>,
 8124                    ) = self
 8125                        .editor_with_selections(cx)
 8126                        .map(|editor| {
 8127                            editor.update(cx, |editor, cx| {
 8128                                let all_selections = editor.selections.all::<Point>(cx);
 8129                                let selected_buffer_ids = if editor.is_singleton(cx) {
 8130                                    Vec::new()
 8131                                } else {
 8132                                    let mut selected_buffer_ids =
 8133                                        Vec::with_capacity(all_selections.len());
 8134
 8135                                    for selection in all_selections {
 8136                                        for buffer_id in snapshot
 8137                                            .buffer_snapshot
 8138                                            .buffer_ids_for_range(selection.range())
 8139                                        {
 8140                                            if selected_buffer_ids.last() != Some(&buffer_id) {
 8141                                                selected_buffer_ids.push(buffer_id);
 8142                                            }
 8143                                        }
 8144                                    }
 8145
 8146                                    selected_buffer_ids
 8147                                };
 8148
 8149                                let mut selections = editor
 8150                                    .selections
 8151                                    .disjoint_in_range(start_anchor..end_anchor, cx);
 8152                                selections.extend(editor.selections.pending(cx));
 8153
 8154                                (selections, selected_buffer_ids)
 8155                            })
 8156                        })
 8157                        .unwrap_or_default();
 8158
 8159                    let (selections, mut active_rows, newest_selection_head) = self
 8160                        .layout_selections(
 8161                            start_anchor,
 8162                            end_anchor,
 8163                            &local_selections,
 8164                            &snapshot,
 8165                            start_row,
 8166                            end_row,
 8167                            window,
 8168                            cx,
 8169                        );
 8170                    let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
 8171                        editor.active_breakpoints(start_row..end_row, window, cx)
 8172                    });
 8173                    for (display_row, (_, bp, state)) in &breakpoint_rows {
 8174                        if bp.is_enabled() && state.is_none_or(|s| s.verified) {
 8175                            active_rows.entry(*display_row).or_default().breakpoint = true;
 8176                        }
 8177                    }
 8178
 8179                    let line_numbers = self.layout_line_numbers(
 8180                        Some(&gutter_hitbox),
 8181                        gutter_dimensions,
 8182                        line_height,
 8183                        scroll_position,
 8184                        start_row..end_row,
 8185                        &row_infos,
 8186                        &active_rows,
 8187                        newest_selection_head,
 8188                        &snapshot,
 8189                        window,
 8190                        cx,
 8191                    );
 8192
 8193                    // We add the gutter breakpoint indicator to breakpoint_rows after painting
 8194                    // line numbers so we don't paint a line number debug accent color if a user
 8195                    // has their mouse over that line when a breakpoint isn't there
 8196                    self.editor.update(cx, |editor, _| {
 8197                        if let Some(phantom_breakpoint) = &mut editor
 8198                            .gutter_breakpoint_indicator
 8199                            .0
 8200                            .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
 8201                        {
 8202                            // Is there a non-phantom breakpoint on this line?
 8203                            phantom_breakpoint.collides_with_existing_breakpoint = true;
 8204                            breakpoint_rows
 8205                                .entry(phantom_breakpoint.display_row)
 8206                                .or_insert_with(|| {
 8207                                    let position = snapshot.display_point_to_anchor(
 8208                                        DisplayPoint::new(phantom_breakpoint.display_row, 0),
 8209                                        Bias::Right,
 8210                                    );
 8211                                    let breakpoint = Breakpoint::new_standard();
 8212                                    phantom_breakpoint.collides_with_existing_breakpoint = false;
 8213                                    (position, breakpoint, None)
 8214                                });
 8215                        }
 8216                    });
 8217
 8218                    let mut expand_toggles =
 8219                        window.with_element_namespace("expand_toggles", |window| {
 8220                            self.layout_expand_toggles(
 8221                                &gutter_hitbox,
 8222                                gutter_dimensions,
 8223                                em_width,
 8224                                line_height,
 8225                                scroll_position,
 8226                                &row_infos,
 8227                                window,
 8228                                cx,
 8229                            )
 8230                        });
 8231
 8232                    let mut crease_toggles =
 8233                        window.with_element_namespace("crease_toggles", |window| {
 8234                            self.layout_crease_toggles(
 8235                                start_row..end_row,
 8236                                &row_infos,
 8237                                &active_rows,
 8238                                &snapshot,
 8239                                window,
 8240                                cx,
 8241                            )
 8242                        });
 8243                    let crease_trailers =
 8244                        window.with_element_namespace("crease_trailers", |window| {
 8245                            self.layout_crease_trailers(
 8246                                row_infos.iter().copied(),
 8247                                &snapshot,
 8248                                window,
 8249                                cx,
 8250                            )
 8251                        });
 8252
 8253                    let display_hunks = self.layout_gutter_diff_hunks(
 8254                        line_height,
 8255                        &gutter_hitbox,
 8256                        start_row..end_row,
 8257                        &snapshot,
 8258                        window,
 8259                        cx,
 8260                    );
 8261
 8262                    let mut line_layouts = Self::layout_lines(
 8263                        start_row..end_row,
 8264                        &snapshot,
 8265                        &self.style,
 8266                        editor_width,
 8267                        is_row_soft_wrapped,
 8268                        window,
 8269                        cx,
 8270                    );
 8271                    let new_fold_widths = line_layouts
 8272                        .iter()
 8273                        .flat_map(|layout| &layout.fragments)
 8274                        .filter_map(|fragment| {
 8275                            if let LineFragment::Element { id, size, .. } = fragment {
 8276                                Some((*id, size.width))
 8277                            } else {
 8278                                None
 8279                            }
 8280                        });
 8281                    if self.editor.update(cx, |editor, cx| {
 8282                        editor.update_fold_widths(new_fold_widths, cx)
 8283                    }) {
 8284                        // If the fold widths have changed, we need to prepaint
 8285                        // the element again to account for any changes in
 8286                        // wrapping.
 8287                        return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
 8288                    }
 8289
 8290                    let longest_line_blame_width = self
 8291                        .editor
 8292                        .update(cx, |editor, cx| {
 8293                            if !editor.show_git_blame_inline {
 8294                                return None;
 8295                            }
 8296                            let blame = editor.blame.as_ref()?;
 8297                            let blame_entry = blame
 8298                                .update(cx, |blame, cx| {
 8299                                    let row_infos =
 8300                                        snapshot.row_infos(snapshot.longest_row()).next()?;
 8301                                    blame.blame_for_rows(&[row_infos], cx).next()
 8302                                })
 8303                                .flatten()?;
 8304                            let mut element = render_inline_blame_entry(blame_entry, &style, cx)?;
 8305                            let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
 8306                            Some(
 8307                                element
 8308                                    .layout_as_root(AvailableSpace::min_size(), window, cx)
 8309                                    .width
 8310                                    + inline_blame_padding,
 8311                            )
 8312                        })
 8313                        .unwrap_or(Pixels::ZERO);
 8314
 8315                    let longest_line_width = layout_line(
 8316                        snapshot.longest_row(),
 8317                        &snapshot,
 8318                        &style,
 8319                        editor_width,
 8320                        is_row_soft_wrapped,
 8321                        window,
 8322                        cx,
 8323                    )
 8324                    .width;
 8325
 8326                    let scrollbar_layout_information = ScrollbarLayoutInformation::new(
 8327                        text_hitbox.bounds,
 8328                        glyph_grid_cell,
 8329                        size(longest_line_width, max_row.as_f32() * line_height),
 8330                        longest_line_blame_width,
 8331                        editor_width,
 8332                        EditorSettings::get_global(cx),
 8333                    );
 8334
 8335                    let mut scroll_width = scrollbar_layout_information.scroll_range.width;
 8336
 8337                    let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
 8338                        snapshot.sticky_header_excerpt(scroll_position.y)
 8339                    } else {
 8340                        None
 8341                    };
 8342                    let sticky_header_excerpt_id =
 8343                        sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
 8344
 8345                    let blocks = window.with_element_namespace("blocks", |window| {
 8346                        self.render_blocks(
 8347                            start_row..end_row,
 8348                            &snapshot,
 8349                            &hitbox,
 8350                            &text_hitbox,
 8351                            editor_width,
 8352                            &mut scroll_width,
 8353                            &editor_margins,
 8354                            em_width,
 8355                            gutter_dimensions.full_width(),
 8356                            line_height,
 8357                            &mut line_layouts,
 8358                            &local_selections,
 8359                            &selected_buffer_ids,
 8360                            is_row_soft_wrapped,
 8361                            sticky_header_excerpt_id,
 8362                            window,
 8363                            cx,
 8364                        )
 8365                    });
 8366                    let (mut blocks, row_block_types) = match blocks {
 8367                        Ok(blocks) => blocks,
 8368                        Err(resized_blocks) => {
 8369                            self.editor.update(cx, |editor, cx| {
 8370                                editor.resize_blocks(resized_blocks, autoscroll_request, cx)
 8371                            });
 8372                            return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
 8373                        }
 8374                    };
 8375
 8376                    let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
 8377                        window.with_element_namespace("blocks", |window| {
 8378                            self.layout_sticky_buffer_header(
 8379                                sticky_header_excerpt,
 8380                                scroll_position.y,
 8381                                line_height,
 8382                                right_margin,
 8383                                &snapshot,
 8384                                &hitbox,
 8385                                &selected_buffer_ids,
 8386                                &blocks,
 8387                                window,
 8388                                cx,
 8389                            )
 8390                        })
 8391                    });
 8392
 8393                    let start_buffer_row =
 8394                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
 8395                    let end_buffer_row =
 8396                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
 8397
 8398                    let scroll_max = point(
 8399                        ((scroll_width - editor_content_width) / em_advance).max(0.0),
 8400                        max_scroll_top,
 8401                    );
 8402
 8403                    self.editor.update(cx, |editor, cx| {
 8404                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
 8405
 8406                        let autoscrolled = if autoscroll_horizontally {
 8407                            editor.autoscroll_horizontally(
 8408                                start_row,
 8409                                editor_content_width,
 8410                                scroll_width,
 8411                                em_advance,
 8412                                &line_layouts,
 8413                                cx,
 8414                            )
 8415                        } else {
 8416                            false
 8417                        };
 8418
 8419                        if clamped || autoscrolled {
 8420                            snapshot = editor.snapshot(window, cx);
 8421                            scroll_position = snapshot.scroll_position();
 8422                        }
 8423                    });
 8424
 8425                    let scroll_pixel_position = point(
 8426                        scroll_position.x * em_advance,
 8427                        scroll_position.y * line_height,
 8428                    );
 8429                    let indent_guides = self.layout_indent_guides(
 8430                        content_origin,
 8431                        text_hitbox.origin,
 8432                        start_buffer_row..end_buffer_row,
 8433                        scroll_pixel_position,
 8434                        line_height,
 8435                        &snapshot,
 8436                        window,
 8437                        cx,
 8438                    );
 8439
 8440                    let crease_trailers =
 8441                        window.with_element_namespace("crease_trailers", |window| {
 8442                            self.prepaint_crease_trailers(
 8443                                crease_trailers,
 8444                                &line_layouts,
 8445                                line_height,
 8446                                content_origin,
 8447                                scroll_pixel_position,
 8448                                em_width,
 8449                                window,
 8450                                cx,
 8451                            )
 8452                        });
 8453
 8454                    let (inline_completion_popover, inline_completion_popover_origin) = self
 8455                        .editor
 8456                        .update(cx, |editor, cx| {
 8457                            editor.render_edit_prediction_popover(
 8458                                &text_hitbox.bounds,
 8459                                content_origin,
 8460                                right_margin,
 8461                                &snapshot,
 8462                                start_row..end_row,
 8463                                scroll_position.y,
 8464                                scroll_position.y + height_in_lines,
 8465                                &line_layouts,
 8466                                line_height,
 8467                                scroll_pixel_position,
 8468                                newest_selection_head,
 8469                                editor_width,
 8470                                &style,
 8471                                window,
 8472                                cx,
 8473                            )
 8474                        })
 8475                        .unzip();
 8476
 8477                    let mut inline_diagnostics = self.layout_inline_diagnostics(
 8478                        &line_layouts,
 8479                        &crease_trailers,
 8480                        &row_block_types,
 8481                        content_origin,
 8482                        scroll_pixel_position,
 8483                        inline_completion_popover_origin,
 8484                        start_row,
 8485                        end_row,
 8486                        line_height,
 8487                        em_width,
 8488                        &style,
 8489                        window,
 8490                        cx,
 8491                    );
 8492
 8493                    let mut inline_blame_layout = None;
 8494                    let mut inline_code_actions = None;
 8495                    if let Some(newest_selection_head) = newest_selection_head {
 8496                        let display_row = newest_selection_head.row();
 8497                        if (start_row..end_row).contains(&display_row)
 8498                            && !row_block_types.contains_key(&display_row)
 8499                        {
 8500                            inline_code_actions = self.layout_inline_code_actions(
 8501                                newest_selection_head,
 8502                                content_origin,
 8503                                scroll_pixel_position,
 8504                                line_height,
 8505                                &snapshot,
 8506                                window,
 8507                                cx,
 8508                            );
 8509
 8510                            let line_ix = display_row.minus(start_row) as usize;
 8511                            let row_info = &row_infos[line_ix];
 8512                            let line_layout = &line_layouts[line_ix];
 8513                            let crease_trailer_layout = crease_trailers[line_ix].as_ref();
 8514
 8515                            if let Some(layout) = self.layout_inline_blame(
 8516                                display_row,
 8517                                row_info,
 8518                                line_layout,
 8519                                crease_trailer_layout,
 8520                                em_width,
 8521                                content_origin,
 8522                                scroll_pixel_position,
 8523                                line_height,
 8524                                &text_hitbox,
 8525                                window,
 8526                                cx,
 8527                            ) {
 8528                                inline_blame_layout = Some(layout);
 8529                                // Blame overrides inline diagnostics
 8530                                inline_diagnostics.remove(&display_row);
 8531                            }
 8532                        }
 8533                    }
 8534
 8535                    let blamed_display_rows = self.layout_blame_entries(
 8536                        &row_infos,
 8537                        em_width,
 8538                        scroll_position,
 8539                        line_height,
 8540                        &gutter_hitbox,
 8541                        gutter_dimensions.git_blame_entries_width,
 8542                        window,
 8543                        cx,
 8544                    );
 8545
 8546                    self.editor.update(cx, |editor, cx| {
 8547                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
 8548
 8549                        let autoscrolled = if autoscroll_horizontally {
 8550                            editor.autoscroll_horizontally(
 8551                                start_row,
 8552                                editor_content_width,
 8553                                scroll_width,
 8554                                em_width,
 8555                                &line_layouts,
 8556                                cx,
 8557                            )
 8558                        } else {
 8559                            false
 8560                        };
 8561
 8562                        if clamped || autoscrolled {
 8563                            snapshot = editor.snapshot(window, cx);
 8564                            scroll_position = snapshot.scroll_position();
 8565                        }
 8566                    });
 8567
 8568                    let line_elements = self.prepaint_lines(
 8569                        start_row,
 8570                        &mut line_layouts,
 8571                        line_height,
 8572                        scroll_pixel_position,
 8573                        content_origin,
 8574                        window,
 8575                        cx,
 8576                    );
 8577
 8578                    window.with_element_namespace("blocks", |window| {
 8579                        self.layout_blocks(
 8580                            &mut blocks,
 8581                            &hitbox,
 8582                            line_height,
 8583                            scroll_pixel_position,
 8584                            window,
 8585                            cx,
 8586                        );
 8587                    });
 8588
 8589                    let cursors = self.collect_cursors(&snapshot, cx);
 8590                    let visible_row_range = start_row..end_row;
 8591                    let non_visible_cursors = cursors
 8592                        .iter()
 8593                        .any(|c| !visible_row_range.contains(&c.0.row()));
 8594
 8595                    let visible_cursors = self.layout_visible_cursors(
 8596                        &snapshot,
 8597                        &selections,
 8598                        &row_block_types,
 8599                        start_row..end_row,
 8600                        &line_layouts,
 8601                        &text_hitbox,
 8602                        content_origin,
 8603                        scroll_position,
 8604                        scroll_pixel_position,
 8605                        line_height,
 8606                        em_width,
 8607                        em_advance,
 8608                        autoscroll_containing_element,
 8609                        window,
 8610                        cx,
 8611                    );
 8612
 8613                    let scrollbars_layout = self.layout_scrollbars(
 8614                        &snapshot,
 8615                        &scrollbar_layout_information,
 8616                        content_offset,
 8617                        scroll_position,
 8618                        non_visible_cursors,
 8619                        right_margin,
 8620                        editor_width,
 8621                        window,
 8622                        cx,
 8623                    );
 8624
 8625                    let gutter_settings = EditorSettings::get_global(cx).gutter;
 8626
 8627                    let context_menu_layout =
 8628                        if let Some(newest_selection_head) = newest_selection_head {
 8629                            let newest_selection_point =
 8630                                newest_selection_head.to_point(&snapshot.display_snapshot);
 8631                            if (start_row..end_row).contains(&newest_selection_head.row()) {
 8632                                self.layout_cursor_popovers(
 8633                                    line_height,
 8634                                    &text_hitbox,
 8635                                    content_origin,
 8636                                    right_margin,
 8637                                    start_row,
 8638                                    scroll_pixel_position,
 8639                                    &line_layouts,
 8640                                    newest_selection_head,
 8641                                    newest_selection_point,
 8642                                    &style,
 8643                                    window,
 8644                                    cx,
 8645                                )
 8646                            } else {
 8647                                None
 8648                            }
 8649                        } else {
 8650                            None
 8651                        };
 8652
 8653                    self.layout_gutter_menu(
 8654                        line_height,
 8655                        &text_hitbox,
 8656                        content_origin,
 8657                        right_margin,
 8658                        scroll_pixel_position,
 8659                        gutter_dimensions.width - gutter_dimensions.left_padding,
 8660                        window,
 8661                        cx,
 8662                    );
 8663
 8664                    let test_indicators = if gutter_settings.runnables {
 8665                        self.layout_run_indicators(
 8666                            line_height,
 8667                            start_row..end_row,
 8668                            &row_infos,
 8669                            scroll_pixel_position,
 8670                            &gutter_dimensions,
 8671                            &gutter_hitbox,
 8672                            &display_hunks,
 8673                            &snapshot,
 8674                            &mut breakpoint_rows,
 8675                            window,
 8676                            cx,
 8677                        )
 8678                    } else {
 8679                        Vec::new()
 8680                    };
 8681
 8682                    let show_breakpoints = snapshot
 8683                        .show_breakpoints
 8684                        .unwrap_or(gutter_settings.breakpoints);
 8685                    let breakpoints = if show_breakpoints {
 8686                        self.layout_breakpoints(
 8687                            line_height,
 8688                            start_row..end_row,
 8689                            scroll_pixel_position,
 8690                            &gutter_dimensions,
 8691                            &gutter_hitbox,
 8692                            &display_hunks,
 8693                            &snapshot,
 8694                            breakpoint_rows,
 8695                            &row_infos,
 8696                            window,
 8697                            cx,
 8698                        )
 8699                    } else {
 8700                        Vec::new()
 8701                    };
 8702
 8703                    self.layout_signature_help(
 8704                        &hitbox,
 8705                        content_origin,
 8706                        scroll_pixel_position,
 8707                        newest_selection_head,
 8708                        start_row,
 8709                        &line_layouts,
 8710                        line_height,
 8711                        em_width,
 8712                        context_menu_layout,
 8713                        window,
 8714                        cx,
 8715                    );
 8716
 8717                    if !cx.has_active_drag() {
 8718                        self.layout_hover_popovers(
 8719                            &snapshot,
 8720                            &hitbox,
 8721                            start_row..end_row,
 8722                            content_origin,
 8723                            scroll_pixel_position,
 8724                            &line_layouts,
 8725                            line_height,
 8726                            em_width,
 8727                            context_menu_layout,
 8728                            window,
 8729                            cx,
 8730                        );
 8731                    }
 8732
 8733                    let mouse_context_menu = self.layout_mouse_context_menu(
 8734                        &snapshot,
 8735                        start_row..end_row,
 8736                        content_origin,
 8737                        window,
 8738                        cx,
 8739                    );
 8740
 8741                    window.with_element_namespace("crease_toggles", |window| {
 8742                        self.prepaint_crease_toggles(
 8743                            &mut crease_toggles,
 8744                            line_height,
 8745                            &gutter_dimensions,
 8746                            gutter_settings,
 8747                            scroll_pixel_position,
 8748                            &gutter_hitbox,
 8749                            window,
 8750                            cx,
 8751                        )
 8752                    });
 8753
 8754                    window.with_element_namespace("expand_toggles", |window| {
 8755                        self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
 8756                    });
 8757
 8758                    let minimap = window.with_element_namespace("minimap", |window| {
 8759                        self.layout_minimap(
 8760                            &snapshot,
 8761                            minimap_width,
 8762                            scroll_position,
 8763                            &scrollbar_layout_information,
 8764                            scrollbars_layout.as_ref(),
 8765                            window,
 8766                            cx,
 8767                        )
 8768                    });
 8769
 8770                    let invisible_symbol_font_size = font_size / 2.;
 8771                    let tab_invisible = window.text_system().shape_line(
 8772                        "".into(),
 8773                        invisible_symbol_font_size,
 8774                        &[TextRun {
 8775                            len: "".len(),
 8776                            font: self.style.text.font(),
 8777                            color: cx.theme().colors().editor_invisible,
 8778                            background_color: None,
 8779                            underline: None,
 8780                            strikethrough: None,
 8781                        }],
 8782                    );
 8783                    let space_invisible = window.text_system().shape_line(
 8784                        "".into(),
 8785                        invisible_symbol_font_size,
 8786                        &[TextRun {
 8787                            len: "".len(),
 8788                            font: self.style.text.font(),
 8789                            color: cx.theme().colors().editor_invisible,
 8790                            background_color: None,
 8791                            underline: None,
 8792                            strikethrough: None,
 8793                        }],
 8794                    );
 8795
 8796                    let mode = snapshot.mode.clone();
 8797
 8798                    let (diff_hunk_controls, diff_hunk_control_bounds) = if is_read_only {
 8799                        (vec![], vec![])
 8800                    } else {
 8801                        self.layout_diff_hunk_controls(
 8802                            start_row..end_row,
 8803                            &row_infos,
 8804                            &text_hitbox,
 8805                            newest_selection_head,
 8806                            line_height,
 8807                            right_margin,
 8808                            scroll_pixel_position,
 8809                            &display_hunks,
 8810                            &highlighted_rows,
 8811                            self.editor.clone(),
 8812                            window,
 8813                            cx,
 8814                        )
 8815                    };
 8816
 8817                    let position_map = Rc::new(PositionMap {
 8818                        size: bounds.size,
 8819                        visible_row_range,
 8820                        scroll_pixel_position,
 8821                        scroll_max,
 8822                        line_layouts,
 8823                        line_height,
 8824                        em_width,
 8825                        em_advance,
 8826                        snapshot,
 8827                        gutter_hitbox: gutter_hitbox.clone(),
 8828                        text_hitbox: text_hitbox.clone(),
 8829                        inline_blame_bounds: inline_blame_layout
 8830                            .as_ref()
 8831                            .map(|layout| (layout.bounds, layout.entry.clone())),
 8832                        display_hunks: display_hunks.clone(),
 8833                        diff_hunk_control_bounds: diff_hunk_control_bounds.clone(),
 8834                    });
 8835
 8836                    self.editor.update(cx, |editor, _| {
 8837                        editor.last_position_map = Some(position_map.clone())
 8838                    });
 8839
 8840                    EditorLayout {
 8841                        mode,
 8842                        position_map,
 8843                        visible_display_row_range: start_row..end_row,
 8844                        wrap_guides,
 8845                        indent_guides,
 8846                        hitbox,
 8847                        gutter_hitbox,
 8848                        display_hunks,
 8849                        content_origin,
 8850                        scrollbars_layout,
 8851                        minimap,
 8852                        active_rows,
 8853                        highlighted_rows,
 8854                        highlighted_ranges,
 8855                        highlighted_gutter_ranges,
 8856                        redacted_ranges,
 8857                        document_colors,
 8858                        line_elements,
 8859                        line_numbers,
 8860                        blamed_display_rows,
 8861                        inline_diagnostics,
 8862                        inline_blame_layout,
 8863                        inline_code_actions,
 8864                        blocks,
 8865                        cursors,
 8866                        visible_cursors,
 8867                        selections,
 8868                        inline_completion_popover,
 8869                        diff_hunk_controls,
 8870                        mouse_context_menu,
 8871                        test_indicators,
 8872                        breakpoints,
 8873                        crease_toggles,
 8874                        crease_trailers,
 8875                        tab_invisible,
 8876                        space_invisible,
 8877                        sticky_buffer_header,
 8878                        expand_toggles,
 8879                    }
 8880                })
 8881            })
 8882        })
 8883    }
 8884
 8885    fn paint(
 8886        &mut self,
 8887        _: Option<&GlobalElementId>,
 8888        _inspector_id: Option<&gpui::InspectorElementId>,
 8889        bounds: Bounds<gpui::Pixels>,
 8890        _: &mut Self::RequestLayoutState,
 8891        layout: &mut Self::PrepaintState,
 8892        window: &mut Window,
 8893        cx: &mut App,
 8894    ) {
 8895        let focus_handle = self.editor.focus_handle(cx);
 8896        let key_context = self
 8897            .editor
 8898            .update(cx, |editor, cx| editor.key_context(window, cx));
 8899
 8900        window.set_key_context(key_context);
 8901        window.handle_input(
 8902            &focus_handle,
 8903            ElementInputHandler::new(bounds, self.editor.clone()),
 8904            cx,
 8905        );
 8906        self.register_actions(window, cx);
 8907        self.register_key_listeners(window, cx, layout);
 8908
 8909        let text_style = TextStyleRefinement {
 8910            font_size: Some(self.style.text.font_size),
 8911            line_height: Some(self.style.text.line_height),
 8912            ..Default::default()
 8913        };
 8914        let rem_size = self.rem_size(cx);
 8915        window.with_rem_size(rem_size, |window| {
 8916            window.with_text_style(Some(text_style), |window| {
 8917                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 8918                    self.paint_mouse_listeners(layout, window, cx);
 8919                    self.paint_background(layout, window, cx);
 8920                    self.paint_indent_guides(layout, window, cx);
 8921
 8922                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
 8923                        self.paint_blamed_display_rows(layout, window, cx);
 8924                        self.paint_line_numbers(layout, window, cx);
 8925                    }
 8926
 8927                    self.paint_text(layout, window, cx);
 8928
 8929                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
 8930                        self.paint_gutter_highlights(layout, window, cx);
 8931                        self.paint_gutter_indicators(layout, window, cx);
 8932                    }
 8933
 8934                    if !layout.blocks.is_empty() {
 8935                        window.with_element_namespace("blocks", |window| {
 8936                            self.paint_blocks(layout, window, cx);
 8937                        });
 8938                    }
 8939
 8940                    window.with_element_namespace("blocks", |window| {
 8941                        if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
 8942                            sticky_header.paint(window, cx)
 8943                        }
 8944                    });
 8945
 8946                    self.paint_minimap(layout, window, cx);
 8947                    self.paint_scrollbars(layout, window, cx);
 8948                    self.paint_inline_completion_popover(layout, window, cx);
 8949                    self.paint_mouse_context_menu(layout, window, cx);
 8950                });
 8951            })
 8952        })
 8953    }
 8954}
 8955
 8956pub(super) fn gutter_bounds(
 8957    editor_bounds: Bounds<Pixels>,
 8958    gutter_dimensions: GutterDimensions,
 8959) -> Bounds<Pixels> {
 8960    Bounds {
 8961        origin: editor_bounds.origin,
 8962        size: size(gutter_dimensions.width, editor_bounds.size.height),
 8963    }
 8964}
 8965
 8966#[derive(Clone, Copy)]
 8967struct ContextMenuLayout {
 8968    y_flipped: bool,
 8969    bounds: Bounds<Pixels>,
 8970}
 8971
 8972/// Holds information required for layouting the editor scrollbars.
 8973struct ScrollbarLayoutInformation {
 8974    /// The bounds of the editor area (excluding the content offset).
 8975    editor_bounds: Bounds<Pixels>,
 8976    /// The available range to scroll within the document.
 8977    scroll_range: Size<Pixels>,
 8978    /// The space available for one glyph in the editor.
 8979    glyph_grid_cell: Size<Pixels>,
 8980}
 8981
 8982impl ScrollbarLayoutInformation {
 8983    pub fn new(
 8984        editor_bounds: Bounds<Pixels>,
 8985        glyph_grid_cell: Size<Pixels>,
 8986        document_size: Size<Pixels>,
 8987        longest_line_blame_width: Pixels,
 8988        editor_width: Pixels,
 8989        settings: &EditorSettings,
 8990    ) -> Self {
 8991        let vertical_overscroll = match settings.scroll_beyond_last_line {
 8992            ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
 8993            ScrollBeyondLastLine::Off => glyph_grid_cell.height,
 8994            ScrollBeyondLastLine::VerticalScrollMargin => {
 8995                (1.0 + settings.vertical_scroll_margin) * glyph_grid_cell.height
 8996            }
 8997        };
 8998
 8999        let right_margin = if document_size.width + longest_line_blame_width >= editor_width {
 9000            glyph_grid_cell.width
 9001        } else {
 9002            px(0.0)
 9003        };
 9004
 9005        let overscroll = size(right_margin + longest_line_blame_width, vertical_overscroll);
 9006
 9007        let scroll_range = document_size + overscroll;
 9008
 9009        ScrollbarLayoutInformation {
 9010            editor_bounds,
 9011            scroll_range,
 9012            glyph_grid_cell,
 9013        }
 9014    }
 9015}
 9016
 9017impl IntoElement for EditorElement {
 9018    type Element = Self;
 9019
 9020    fn into_element(self) -> Self::Element {
 9021        self
 9022    }
 9023}
 9024
 9025pub struct EditorLayout {
 9026    position_map: Rc<PositionMap>,
 9027    hitbox: Hitbox,
 9028    gutter_hitbox: Hitbox,
 9029    content_origin: gpui::Point<Pixels>,
 9030    scrollbars_layout: Option<EditorScrollbars>,
 9031    minimap: Option<MinimapLayout>,
 9032    mode: EditorMode,
 9033    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
 9034    indent_guides: Option<Vec<IndentGuideLayout>>,
 9035    visible_display_row_range: Range<DisplayRow>,
 9036    active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
 9037    highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
 9038    line_elements: SmallVec<[AnyElement; 1]>,
 9039    line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
 9040    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
 9041    blamed_display_rows: Option<Vec<AnyElement>>,
 9042    inline_diagnostics: HashMap<DisplayRow, AnyElement>,
 9043    inline_blame_layout: Option<InlineBlameLayout>,
 9044    inline_code_actions: Option<AnyElement>,
 9045    blocks: Vec<BlockLayout>,
 9046    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
 9047    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
 9048    redacted_ranges: Vec<Range<DisplayPoint>>,
 9049    cursors: Vec<(DisplayPoint, Hsla)>,
 9050    visible_cursors: Vec<CursorLayout>,
 9051    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
 9052    test_indicators: Vec<AnyElement>,
 9053    breakpoints: Vec<AnyElement>,
 9054    crease_toggles: Vec<Option<AnyElement>>,
 9055    expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
 9056    diff_hunk_controls: Vec<AnyElement>,
 9057    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
 9058    inline_completion_popover: Option<AnyElement>,
 9059    mouse_context_menu: Option<AnyElement>,
 9060    tab_invisible: ShapedLine,
 9061    space_invisible: ShapedLine,
 9062    sticky_buffer_header: Option<AnyElement>,
 9063    document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
 9064}
 9065
 9066impl EditorLayout {
 9067    fn line_end_overshoot(&self) -> Pixels {
 9068        0.15 * self.position_map.line_height
 9069    }
 9070}
 9071
 9072struct LineNumberLayout {
 9073    shaped_line: ShapedLine,
 9074    hitbox: Option<Hitbox>,
 9075}
 9076
 9077struct ColoredRange<T> {
 9078    start: T,
 9079    end: T,
 9080    color: Hsla,
 9081}
 9082
 9083impl Along for ScrollbarAxes {
 9084    type Unit = bool;
 9085
 9086    fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
 9087        match axis {
 9088            ScrollbarAxis::Horizontal => self.horizontal,
 9089            ScrollbarAxis::Vertical => self.vertical,
 9090        }
 9091    }
 9092
 9093    fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
 9094        match axis {
 9095            ScrollbarAxis::Horizontal => ScrollbarAxes {
 9096                horizontal: f(self.horizontal),
 9097                vertical: self.vertical,
 9098            },
 9099            ScrollbarAxis::Vertical => ScrollbarAxes {
 9100                horizontal: self.horizontal,
 9101                vertical: f(self.vertical),
 9102            },
 9103        }
 9104    }
 9105}
 9106
 9107#[derive(Clone)]
 9108struct EditorScrollbars {
 9109    pub vertical: Option<ScrollbarLayout>,
 9110    pub horizontal: Option<ScrollbarLayout>,
 9111    pub visible: bool,
 9112}
 9113
 9114impl EditorScrollbars {
 9115    pub fn from_scrollbar_axes(
 9116        settings_visibility: ScrollbarAxes,
 9117        layout_information: &ScrollbarLayoutInformation,
 9118        content_offset: gpui::Point<Pixels>,
 9119        scroll_position: gpui::Point<f32>,
 9120        scrollbar_width: Pixels,
 9121        right_margin: Pixels,
 9122        editor_width: Pixels,
 9123        show_scrollbars: bool,
 9124        scrollbar_state: Option<&ActiveScrollbarState>,
 9125        window: &mut Window,
 9126    ) -> Self {
 9127        let ScrollbarLayoutInformation {
 9128            editor_bounds,
 9129            scroll_range,
 9130            glyph_grid_cell,
 9131        } = layout_information;
 9132
 9133        let viewport_size = size(editor_width, editor_bounds.size.height);
 9134
 9135        let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
 9136            ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
 9137                Corner::BottomLeft,
 9138                editor_bounds.bottom_left(),
 9139                size(
 9140                    // The horizontal viewport size differs from the space available for the
 9141                    // horizontal scrollbar, so we have to manually stich it together here.
 9142                    editor_bounds.size.width - right_margin,
 9143                    scrollbar_width,
 9144                ),
 9145            ),
 9146            ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
 9147                Corner::TopRight,
 9148                editor_bounds.top_right(),
 9149                size(scrollbar_width, viewport_size.height),
 9150            ),
 9151        };
 9152
 9153        let mut create_scrollbar_layout = |axis| {
 9154            settings_visibility
 9155                .along(axis)
 9156                .then(|| {
 9157                    (
 9158                        viewport_size.along(axis) - content_offset.along(axis),
 9159                        scroll_range.along(axis),
 9160                    )
 9161                })
 9162                .filter(|(viewport_size, scroll_range)| {
 9163                    // The scrollbar should only be rendered if the content does
 9164                    // not entirely fit into the editor
 9165                    // However, this only applies to the horizontal scrollbar, as information about the
 9166                    // vertical scrollbar layout is always needed for scrollbar diagnostics.
 9167                    axis != ScrollbarAxis::Horizontal || viewport_size < scroll_range
 9168                })
 9169                .map(|(viewport_size, scroll_range)| {
 9170                    ScrollbarLayout::new(
 9171                        window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
 9172                        viewport_size,
 9173                        scroll_range,
 9174                        glyph_grid_cell.along(axis),
 9175                        content_offset.along(axis),
 9176                        scroll_position.along(axis),
 9177                        show_scrollbars,
 9178                        axis,
 9179                    )
 9180                    .with_thumb_state(
 9181                        scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
 9182                    )
 9183                })
 9184        };
 9185
 9186        Self {
 9187            vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
 9188            horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
 9189            visible: show_scrollbars,
 9190        }
 9191    }
 9192
 9193    pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
 9194        [
 9195            (&self.vertical, ScrollbarAxis::Vertical),
 9196            (&self.horizontal, ScrollbarAxis::Horizontal),
 9197        ]
 9198        .into_iter()
 9199        .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
 9200    }
 9201
 9202    /// Returns the currently hovered scrollbar axis, if any.
 9203    pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
 9204        self.iter_scrollbars()
 9205            .find(|s| s.0.hitbox.is_hovered(window))
 9206    }
 9207}
 9208
 9209#[derive(Clone)]
 9210struct ScrollbarLayout {
 9211    hitbox: Hitbox,
 9212    visible_range: Range<f32>,
 9213    text_unit_size: Pixels,
 9214    thumb_bounds: Option<Bounds<Pixels>>,
 9215    thumb_state: ScrollbarThumbState,
 9216}
 9217
 9218impl ScrollbarLayout {
 9219    const BORDER_WIDTH: Pixels = px(1.0);
 9220    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
 9221    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
 9222    const MIN_THUMB_SIZE: Pixels = px(25.0);
 9223
 9224    fn new(
 9225        scrollbar_track_hitbox: Hitbox,
 9226        viewport_size: Pixels,
 9227        scroll_range: Pixels,
 9228        glyph_space: Pixels,
 9229        content_offset: Pixels,
 9230        scroll_position: f32,
 9231        show_thumb: bool,
 9232        axis: ScrollbarAxis,
 9233    ) -> Self {
 9234        let track_bounds = scrollbar_track_hitbox.bounds;
 9235        // The length of the track available to the scrollbar thumb. We deliberately
 9236        // exclude the content size here so that the thumb aligns with the content.
 9237        let track_length = track_bounds.size.along(axis) - content_offset;
 9238
 9239        Self::new_with_hitbox_and_track_length(
 9240            scrollbar_track_hitbox,
 9241            track_length,
 9242            viewport_size,
 9243            scroll_range,
 9244            glyph_space,
 9245            content_offset,
 9246            scroll_position,
 9247            show_thumb,
 9248            axis,
 9249        )
 9250    }
 9251
 9252    fn for_minimap(
 9253        minimap_track_hitbox: Hitbox,
 9254        visible_lines: f32,
 9255        total_editor_lines: f32,
 9256        minimap_line_height: Pixels,
 9257        scroll_position: f32,
 9258        minimap_scroll_top: f32,
 9259        show_thumb: bool,
 9260    ) -> Self {
 9261        // The scrollbar thumb size is calculated as
 9262        // (visible_content/total_content) × scrollbar_track_length.
 9263        //
 9264        // For the minimap's thumb layout, we leverage this by setting the
 9265        // scrollbar track length to the entire document size (using minimap line
 9266        // height). This creates a thumb that exactly represents the editor
 9267        // viewport scaled to minimap proportions.
 9268        //
 9269        // We adjust the thumb position relative to `minimap_scroll_top` to
 9270        // accommodate for the deliberately oversized track.
 9271        //
 9272        // This approach ensures that the minimap thumb accurately reflects the
 9273        // editor's current scroll position whilst nicely synchronizing the minimap
 9274        // thumb and scrollbar thumb.
 9275        let scroll_range = total_editor_lines * minimap_line_height;
 9276        let viewport_size = visible_lines * minimap_line_height;
 9277
 9278        let track_top_offset = -minimap_scroll_top * minimap_line_height;
 9279
 9280        Self::new_with_hitbox_and_track_length(
 9281            minimap_track_hitbox,
 9282            scroll_range,
 9283            viewport_size,
 9284            scroll_range,
 9285            minimap_line_height,
 9286            track_top_offset,
 9287            scroll_position,
 9288            show_thumb,
 9289            ScrollbarAxis::Vertical,
 9290        )
 9291    }
 9292
 9293    fn new_with_hitbox_and_track_length(
 9294        scrollbar_track_hitbox: Hitbox,
 9295        track_length: Pixels,
 9296        viewport_size: Pixels,
 9297        scroll_range: Pixels,
 9298        glyph_space: Pixels,
 9299        content_offset: Pixels,
 9300        scroll_position: f32,
 9301        show_thumb: bool,
 9302        axis: ScrollbarAxis,
 9303    ) -> Self {
 9304        let text_units_per_page = viewport_size / glyph_space;
 9305        let visible_range = scroll_position..scroll_position + text_units_per_page;
 9306        let total_text_units = scroll_range / glyph_space;
 9307
 9308        let thumb_percentage = text_units_per_page / total_text_units;
 9309        let thumb_size = (track_length * thumb_percentage)
 9310            .max(ScrollbarLayout::MIN_THUMB_SIZE)
 9311            .min(track_length);
 9312
 9313        let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
 9314
 9315        let content_larger_than_viewport = text_unit_divisor > 0.;
 9316
 9317        let text_unit_size = if content_larger_than_viewport {
 9318            (track_length - thumb_size) / text_unit_divisor
 9319        } else {
 9320            glyph_space
 9321        };
 9322
 9323        let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
 9324            Self::thumb_bounds(
 9325                &scrollbar_track_hitbox,
 9326                content_offset,
 9327                visible_range.start,
 9328                text_unit_size,
 9329                thumb_size,
 9330                axis,
 9331            )
 9332        });
 9333
 9334        ScrollbarLayout {
 9335            hitbox: scrollbar_track_hitbox,
 9336            visible_range,
 9337            text_unit_size,
 9338            thumb_bounds,
 9339            thumb_state: Default::default(),
 9340        }
 9341    }
 9342
 9343    fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
 9344        if let Some(thumb_state) = thumb_state {
 9345            Self {
 9346                thumb_state,
 9347                ..self
 9348            }
 9349        } else {
 9350            self
 9351        }
 9352    }
 9353
 9354    fn thumb_bounds(
 9355        scrollbar_track: &Hitbox,
 9356        content_offset: Pixels,
 9357        visible_range_start: f32,
 9358        text_unit_size: Pixels,
 9359        thumb_size: Pixels,
 9360        axis: ScrollbarAxis,
 9361    ) -> Bounds<Pixels> {
 9362        let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
 9363            origin + content_offset + visible_range_start * text_unit_size
 9364        });
 9365        Bounds::new(
 9366            thumb_origin,
 9367            scrollbar_track.size.apply_along(axis, |_| thumb_size),
 9368        )
 9369    }
 9370
 9371    fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
 9372        self.thumb_bounds
 9373            .is_some_and(|bounds| bounds.contains(position))
 9374    }
 9375
 9376    fn marker_quads_for_ranges(
 9377        &self,
 9378        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
 9379        column: Option<usize>,
 9380    ) -> Vec<PaintQuad> {
 9381        struct MinMax {
 9382            min: Pixels,
 9383            max: Pixels,
 9384        }
 9385        let (x_range, height_limit) = if let Some(column) = column {
 9386            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
 9387            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
 9388            let end = start + column_width;
 9389            (
 9390                Range { start, end },
 9391                MinMax {
 9392                    min: Self::MIN_MARKER_HEIGHT,
 9393                    max: px(f32::MAX),
 9394                },
 9395            )
 9396        } else {
 9397            (
 9398                Range {
 9399                    start: Self::BORDER_WIDTH,
 9400                    end: self.hitbox.size.width,
 9401                },
 9402                MinMax {
 9403                    min: Self::LINE_MARKER_HEIGHT,
 9404                    max: Self::LINE_MARKER_HEIGHT,
 9405                },
 9406            )
 9407        };
 9408
 9409        let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
 9410        let mut pixel_ranges = row_ranges
 9411            .into_iter()
 9412            .map(|range| {
 9413                let start_y = row_to_y(range.start);
 9414                let end_y = row_to_y(range.end)
 9415                    + self
 9416                        .text_unit_size
 9417                        .max(height_limit.min)
 9418                        .min(height_limit.max);
 9419                ColoredRange {
 9420                    start: start_y,
 9421                    end: end_y,
 9422                    color: range.color,
 9423                }
 9424            })
 9425            .peekable();
 9426
 9427        let mut quads = Vec::new();
 9428        while let Some(mut pixel_range) = pixel_ranges.next() {
 9429            while let Some(next_pixel_range) = pixel_ranges.peek() {
 9430                if pixel_range.end >= next_pixel_range.start - px(1.0)
 9431                    && pixel_range.color == next_pixel_range.color
 9432                {
 9433                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
 9434                    pixel_ranges.next();
 9435                } else {
 9436                    break;
 9437                }
 9438            }
 9439
 9440            let bounds = Bounds::from_corners(
 9441                point(x_range.start, pixel_range.start),
 9442                point(x_range.end, pixel_range.end),
 9443            );
 9444            quads.push(quad(
 9445                bounds,
 9446                Corners::default(),
 9447                pixel_range.color,
 9448                Edges::default(),
 9449                Hsla::transparent_black(),
 9450                BorderStyle::default(),
 9451            ));
 9452        }
 9453
 9454        quads
 9455    }
 9456}
 9457
 9458struct MinimapLayout {
 9459    pub minimap: AnyElement,
 9460    pub thumb_layout: ScrollbarLayout,
 9461    pub minimap_scroll_top: f32,
 9462    pub minimap_line_height: Pixels,
 9463    pub thumb_border_style: MinimapThumbBorder,
 9464    pub max_scroll_top: f32,
 9465}
 9466
 9467impl MinimapLayout {
 9468    const MINIMAP_WIDTH: Pixels = px(100.);
 9469    /// Calculates the scroll top offset the minimap editor has to have based on the
 9470    /// current scroll progress.
 9471    fn calculate_minimap_top_offset(
 9472        document_lines: f32,
 9473        visible_editor_lines: f32,
 9474        visible_minimap_lines: f32,
 9475        scroll_position: f32,
 9476    ) -> f32 {
 9477        let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
 9478        if non_visible_document_lines == 0. {
 9479            0.
 9480        } else {
 9481            let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
 9482            scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
 9483        }
 9484    }
 9485}
 9486
 9487struct CreaseTrailerLayout {
 9488    element: AnyElement,
 9489    bounds: Bounds<Pixels>,
 9490}
 9491
 9492pub(crate) struct PositionMap {
 9493    pub size: Size<Pixels>,
 9494    pub line_height: Pixels,
 9495    pub scroll_pixel_position: gpui::Point<Pixels>,
 9496    pub scroll_max: gpui::Point<f32>,
 9497    pub em_width: Pixels,
 9498    pub em_advance: Pixels,
 9499    pub visible_row_range: Range<DisplayRow>,
 9500    pub line_layouts: Vec<LineWithInvisibles>,
 9501    pub snapshot: EditorSnapshot,
 9502    pub text_hitbox: Hitbox,
 9503    pub gutter_hitbox: Hitbox,
 9504    pub inline_blame_bounds: Option<(Bounds<Pixels>, BlameEntry)>,
 9505    pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
 9506    pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
 9507}
 9508
 9509#[derive(Debug, Copy, Clone)]
 9510pub struct PointForPosition {
 9511    pub previous_valid: DisplayPoint,
 9512    pub next_valid: DisplayPoint,
 9513    pub exact_unclipped: DisplayPoint,
 9514    pub column_overshoot_after_line_end: u32,
 9515}
 9516
 9517impl PointForPosition {
 9518    pub fn as_valid(&self) -> Option<DisplayPoint> {
 9519        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
 9520            Some(self.previous_valid)
 9521        } else {
 9522            None
 9523        }
 9524    }
 9525
 9526    pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
 9527        let Some(valid_point) = self.as_valid() else {
 9528            return false;
 9529        };
 9530        let range = selection.range();
 9531
 9532        let candidate_row = valid_point.row();
 9533        let candidate_col = valid_point.column();
 9534
 9535        let start_row = range.start.row();
 9536        let start_col = range.start.column();
 9537        let end_row = range.end.row();
 9538        let end_col = range.end.column();
 9539
 9540        if candidate_row < start_row || candidate_row > end_row {
 9541            false
 9542        } else if start_row == end_row {
 9543            candidate_col >= start_col && candidate_col < end_col
 9544        } else {
 9545            if candidate_row == start_row {
 9546                candidate_col >= start_col
 9547            } else if candidate_row == end_row {
 9548                candidate_col < end_col
 9549            } else {
 9550                true
 9551            }
 9552        }
 9553    }
 9554}
 9555
 9556impl PositionMap {
 9557    pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
 9558        let text_bounds = self.text_hitbox.bounds;
 9559        let scroll_position = self.snapshot.scroll_position();
 9560        let position = position - text_bounds.origin;
 9561        let y = position.y.max(px(0.)).min(self.size.height);
 9562        let x = position.x + (scroll_position.x * self.em_advance);
 9563        let row = ((y / self.line_height) + scroll_position.y) as u32;
 9564
 9565        let (column, x_overshoot_after_line_end) = if let Some(line) = self
 9566            .line_layouts
 9567            .get(row as usize - scroll_position.y as usize)
 9568        {
 9569            if let Some(ix) = line.index_for_x(x) {
 9570                (ix as u32, px(0.))
 9571            } else {
 9572                (line.len as u32, px(0.).max(x - line.width))
 9573            }
 9574        } else {
 9575            (0, x)
 9576        };
 9577
 9578        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
 9579        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
 9580        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
 9581
 9582        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
 9583        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
 9584        PointForPosition {
 9585            previous_valid,
 9586            next_valid,
 9587            exact_unclipped,
 9588            column_overshoot_after_line_end,
 9589        }
 9590    }
 9591}
 9592
 9593struct BlockLayout {
 9594    id: BlockId,
 9595    x_offset: Pixels,
 9596    row: Option<DisplayRow>,
 9597    element: AnyElement,
 9598    available_space: Size<AvailableSpace>,
 9599    style: BlockStyle,
 9600    overlaps_gutter: bool,
 9601    is_buffer_header: bool,
 9602}
 9603
 9604pub fn layout_line(
 9605    row: DisplayRow,
 9606    snapshot: &EditorSnapshot,
 9607    style: &EditorStyle,
 9608    text_width: Pixels,
 9609    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 9610    window: &mut Window,
 9611    cx: &mut App,
 9612) -> LineWithInvisibles {
 9613    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
 9614    LineWithInvisibles::from_chunks(
 9615        chunks,
 9616        &style,
 9617        MAX_LINE_LEN,
 9618        1,
 9619        &snapshot.mode,
 9620        text_width,
 9621        is_row_soft_wrapped,
 9622        window,
 9623        cx,
 9624    )
 9625    .pop()
 9626    .unwrap()
 9627}
 9628
 9629#[derive(Debug)]
 9630pub struct IndentGuideLayout {
 9631    origin: gpui::Point<Pixels>,
 9632    length: Pixels,
 9633    single_indent_width: Pixels,
 9634    depth: u32,
 9635    active: bool,
 9636    settings: IndentGuideSettings,
 9637}
 9638
 9639pub struct CursorLayout {
 9640    origin: gpui::Point<Pixels>,
 9641    block_width: Pixels,
 9642    line_height: Pixels,
 9643    color: Hsla,
 9644    shape: CursorShape,
 9645    block_text: Option<ShapedLine>,
 9646    cursor_name: Option<AnyElement>,
 9647}
 9648
 9649#[derive(Debug)]
 9650pub struct CursorName {
 9651    string: SharedString,
 9652    color: Hsla,
 9653    is_top_row: bool,
 9654}
 9655
 9656impl CursorLayout {
 9657    pub fn new(
 9658        origin: gpui::Point<Pixels>,
 9659        block_width: Pixels,
 9660        line_height: Pixels,
 9661        color: Hsla,
 9662        shape: CursorShape,
 9663        block_text: Option<ShapedLine>,
 9664    ) -> CursorLayout {
 9665        CursorLayout {
 9666            origin,
 9667            block_width,
 9668            line_height,
 9669            color,
 9670            shape,
 9671            block_text,
 9672            cursor_name: None,
 9673        }
 9674    }
 9675
 9676    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
 9677        Bounds {
 9678            origin: self.origin + origin,
 9679            size: size(self.block_width, self.line_height),
 9680        }
 9681    }
 9682
 9683    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
 9684        match self.shape {
 9685            CursorShape::Bar => Bounds {
 9686                origin: self.origin + origin,
 9687                size: size(px(2.0), self.line_height),
 9688            },
 9689            CursorShape::Block | CursorShape::Hollow => Bounds {
 9690                origin: self.origin + origin,
 9691                size: size(self.block_width, self.line_height),
 9692            },
 9693            CursorShape::Underline => Bounds {
 9694                origin: self.origin
 9695                    + origin
 9696                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
 9697                size: size(self.block_width, px(2.0)),
 9698            },
 9699        }
 9700    }
 9701
 9702    pub fn layout(
 9703        &mut self,
 9704        origin: gpui::Point<Pixels>,
 9705        cursor_name: Option<CursorName>,
 9706        window: &mut Window,
 9707        cx: &mut App,
 9708    ) {
 9709        if let Some(cursor_name) = cursor_name {
 9710            let bounds = self.bounds(origin);
 9711            let text_size = self.line_height / 1.5;
 9712
 9713            let name_origin = if cursor_name.is_top_row {
 9714                point(bounds.right() - px(1.), bounds.top())
 9715            } else {
 9716                match self.shape {
 9717                    CursorShape::Bar => point(
 9718                        bounds.right() - px(2.),
 9719                        bounds.top() - text_size / 2. - px(1.),
 9720                    ),
 9721                    _ => point(
 9722                        bounds.right() - px(1.),
 9723                        bounds.top() - text_size / 2. - px(1.),
 9724                    ),
 9725                }
 9726            };
 9727            let mut name_element = div()
 9728                .bg(self.color)
 9729                .text_size(text_size)
 9730                .px_0p5()
 9731                .line_height(text_size + px(2.))
 9732                .text_color(cursor_name.color)
 9733                .child(cursor_name.string.clone())
 9734                .into_any_element();
 9735
 9736            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
 9737
 9738            self.cursor_name = Some(name_element);
 9739        }
 9740    }
 9741
 9742    pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
 9743        let bounds = self.bounds(origin);
 9744
 9745        //Draw background or border quad
 9746        let cursor = if matches!(self.shape, CursorShape::Hollow) {
 9747            outline(bounds, self.color, BorderStyle::Solid)
 9748        } else {
 9749            fill(bounds, self.color)
 9750        };
 9751
 9752        if let Some(name) = &mut self.cursor_name {
 9753            name.paint(window, cx);
 9754        }
 9755
 9756        window.paint_quad(cursor);
 9757
 9758        if let Some(block_text) = &self.block_text {
 9759            block_text
 9760                .paint(self.origin + origin, self.line_height, window, cx)
 9761                .log_err();
 9762        }
 9763    }
 9764
 9765    pub fn shape(&self) -> CursorShape {
 9766        self.shape
 9767    }
 9768}
 9769
 9770#[derive(Debug)]
 9771pub struct HighlightedRange {
 9772    pub start_y: Pixels,
 9773    pub line_height: Pixels,
 9774    pub lines: Vec<HighlightedRangeLine>,
 9775    pub color: Hsla,
 9776    pub corner_radius: Pixels,
 9777}
 9778
 9779#[derive(Debug)]
 9780pub struct HighlightedRangeLine {
 9781    pub start_x: Pixels,
 9782    pub end_x: Pixels,
 9783}
 9784
 9785impl HighlightedRange {
 9786    pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
 9787        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
 9788            self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
 9789            self.paint_lines(
 9790                self.start_y + self.line_height,
 9791                &self.lines[1..],
 9792                fill,
 9793                bounds,
 9794                window,
 9795            );
 9796        } else {
 9797            self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
 9798        }
 9799    }
 9800
 9801    fn paint_lines(
 9802        &self,
 9803        start_y: Pixels,
 9804        lines: &[HighlightedRangeLine],
 9805        fill: bool,
 9806        _bounds: Bounds<Pixels>,
 9807        window: &mut Window,
 9808    ) {
 9809        if lines.is_empty() {
 9810            return;
 9811        }
 9812
 9813        let first_line = lines.first().unwrap();
 9814        let last_line = lines.last().unwrap();
 9815
 9816        let first_top_left = point(first_line.start_x, start_y);
 9817        let first_top_right = point(first_line.end_x, start_y);
 9818
 9819        let curve_height = point(Pixels::ZERO, self.corner_radius);
 9820        let curve_width = |start_x: Pixels, end_x: Pixels| {
 9821            let max = (end_x - start_x) / 2.;
 9822            let width = if max < self.corner_radius {
 9823                max
 9824            } else {
 9825                self.corner_radius
 9826            };
 9827
 9828            point(width, Pixels::ZERO)
 9829        };
 9830
 9831        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
 9832        let mut builder = if fill {
 9833            gpui::PathBuilder::fill()
 9834        } else {
 9835            gpui::PathBuilder::stroke(px(1.))
 9836        };
 9837        builder.move_to(first_top_right - top_curve_width);
 9838        builder.curve_to(first_top_right + curve_height, first_top_right);
 9839
 9840        let mut iter = lines.iter().enumerate().peekable();
 9841        while let Some((ix, line)) = iter.next() {
 9842            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
 9843
 9844            if let Some((_, next_line)) = iter.peek() {
 9845                let next_top_right = point(next_line.end_x, bottom_right.y);
 9846
 9847                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
 9848                    Ordering::Equal => {
 9849                        builder.line_to(bottom_right);
 9850                    }
 9851                    Ordering::Less => {
 9852                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
 9853                        builder.line_to(bottom_right - curve_height);
 9854                        if self.corner_radius > Pixels::ZERO {
 9855                            builder.curve_to(bottom_right - curve_width, bottom_right);
 9856                        }
 9857                        builder.line_to(next_top_right + curve_width);
 9858                        if self.corner_radius > Pixels::ZERO {
 9859                            builder.curve_to(next_top_right + curve_height, next_top_right);
 9860                        }
 9861                    }
 9862                    Ordering::Greater => {
 9863                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
 9864                        builder.line_to(bottom_right - curve_height);
 9865                        if self.corner_radius > Pixels::ZERO {
 9866                            builder.curve_to(bottom_right + curve_width, bottom_right);
 9867                        }
 9868                        builder.line_to(next_top_right - curve_width);
 9869                        if self.corner_radius > Pixels::ZERO {
 9870                            builder.curve_to(next_top_right + curve_height, next_top_right);
 9871                        }
 9872                    }
 9873                }
 9874            } else {
 9875                let curve_width = curve_width(line.start_x, line.end_x);
 9876                builder.line_to(bottom_right - curve_height);
 9877                if self.corner_radius > Pixels::ZERO {
 9878                    builder.curve_to(bottom_right - curve_width, bottom_right);
 9879                }
 9880
 9881                let bottom_left = point(line.start_x, bottom_right.y);
 9882                builder.line_to(bottom_left + curve_width);
 9883                if self.corner_radius > Pixels::ZERO {
 9884                    builder.curve_to(bottom_left - curve_height, bottom_left);
 9885                }
 9886            }
 9887        }
 9888
 9889        if first_line.start_x > last_line.start_x {
 9890            let curve_width = curve_width(last_line.start_x, first_line.start_x);
 9891            let second_top_left = point(last_line.start_x, start_y + self.line_height);
 9892            builder.line_to(second_top_left + curve_height);
 9893            if self.corner_radius > Pixels::ZERO {
 9894                builder.curve_to(second_top_left + curve_width, second_top_left);
 9895            }
 9896            let first_bottom_left = point(first_line.start_x, second_top_left.y);
 9897            builder.line_to(first_bottom_left - curve_width);
 9898            if self.corner_radius > Pixels::ZERO {
 9899                builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
 9900            }
 9901        }
 9902
 9903        builder.line_to(first_top_left + curve_height);
 9904        if self.corner_radius > Pixels::ZERO {
 9905            builder.curve_to(first_top_left + top_curve_width, first_top_left);
 9906        }
 9907        builder.line_to(first_top_right - top_curve_width);
 9908
 9909        if let Ok(path) = builder.build() {
 9910            window.paint_path(path, self.color);
 9911        }
 9912    }
 9913}
 9914
 9915enum CursorPopoverType {
 9916    CodeContextMenu,
 9917    EditPrediction,
 9918}
 9919
 9920pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
 9921    (delta.pow(1.2) / 100.0).min(px(3.0)).into()
 9922}
 9923
 9924fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
 9925    (delta.pow(1.2) / 300.0).into()
 9926}
 9927
 9928pub fn register_action<T: Action>(
 9929    editor: &Entity<Editor>,
 9930    window: &mut Window,
 9931    listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
 9932) {
 9933    let editor = editor.clone();
 9934    window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
 9935        let action = action.downcast_ref().unwrap();
 9936        if phase == DispatchPhase::Bubble {
 9937            editor.update(cx, |editor, cx| {
 9938                listener(editor, action, window, cx);
 9939            })
 9940        }
 9941    })
 9942}
 9943
 9944fn compute_auto_height_layout(
 9945    editor: &mut Editor,
 9946    min_lines: usize,
 9947    max_lines: usize,
 9948    max_line_number_width: Pixels,
 9949    known_dimensions: Size<Option<Pixels>>,
 9950    available_width: AvailableSpace,
 9951    window: &mut Window,
 9952    cx: &mut Context<Editor>,
 9953) -> Option<Size<Pixels>> {
 9954    let width = known_dimensions.width.or({
 9955        if let AvailableSpace::Definite(available_width) = available_width {
 9956            Some(available_width)
 9957        } else {
 9958            None
 9959        }
 9960    })?;
 9961    if let Some(height) = known_dimensions.height {
 9962        return Some(size(width, height));
 9963    }
 9964
 9965    let style = editor.style.as_ref().unwrap();
 9966    let font_id = window.text_system().resolve_font(&style.text.font());
 9967    let font_size = style.text.font_size.to_pixels(window.rem_size());
 9968    let line_height = style.text.line_height_in_pixels(window.rem_size());
 9969    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
 9970
 9971    let mut snapshot = editor.snapshot(window, cx);
 9972    let gutter_dimensions = snapshot
 9973        .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
 9974        .or_else(|| {
 9975            editor
 9976                .offset_content
 9977                .then(|| GutterDimensions::default_with_margin(font_id, font_size, cx))
 9978        })
 9979        .unwrap_or_default();
 9980
 9981    editor.gutter_dimensions = gutter_dimensions;
 9982    let text_width = width - gutter_dimensions.width;
 9983    let overscroll = size(em_width, px(0.));
 9984
 9985    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
 9986    if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None) {
 9987        if editor.set_wrap_width(Some(editor_width), cx) {
 9988            snapshot = editor.snapshot(window, cx);
 9989        }
 9990    }
 9991
 9992    let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
 9993    let height = scroll_height
 9994        .max(line_height * min_lines as f32)
 9995        .min(line_height * max_lines as f32);
 9996
 9997    Some(size(width, height))
 9998}
 9999
10000#[cfg(test)]
10001mod tests {
10002    use super::*;
10003    use crate::{
10004        Editor, MultiBuffer,
10005        display_map::{BlockPlacement, BlockProperties},
10006        editor_tests::{init_test, update_test_language_settings},
10007    };
10008    use gpui::{TestAppContext, VisualTestContext};
10009    use language::language_settings;
10010    use log::info;
10011    use std::num::NonZeroU32;
10012    use util::test::sample_text;
10013
10014    #[gpui::test]
10015    fn test_shape_line_numbers(cx: &mut TestAppContext) {
10016        init_test(cx, |_| {});
10017        let window = cx.add_window(|window, cx| {
10018            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
10019            Editor::new(EditorMode::full(), buffer, None, window, cx)
10020        });
10021
10022        let editor = window.root(cx).unwrap();
10023        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
10024        let line_height = window
10025            .update(cx, |_, window, _| {
10026                style.text.line_height_in_pixels(window.rem_size())
10027            })
10028            .unwrap();
10029        let element = EditorElement::new(&editor, style);
10030        let snapshot = window
10031            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
10032            .unwrap();
10033
10034        let layouts = cx
10035            .update_window(*window, |_, window, cx| {
10036                element.layout_line_numbers(
10037                    None,
10038                    GutterDimensions {
10039                        left_padding: Pixels::ZERO,
10040                        right_padding: Pixels::ZERO,
10041                        width: px(30.0),
10042                        margin: Pixels::ZERO,
10043                        git_blame_entries_width: None,
10044                    },
10045                    line_height,
10046                    gpui::Point::default(),
10047                    DisplayRow(0)..DisplayRow(6),
10048                    &(0..6)
10049                        .map(|row| RowInfo {
10050                            buffer_row: Some(row),
10051                            ..Default::default()
10052                        })
10053                        .collect::<Vec<_>>(),
10054                    &BTreeMap::default(),
10055                    Some(DisplayPoint::new(DisplayRow(0), 0)),
10056                    &snapshot,
10057                    window,
10058                    cx,
10059                )
10060            })
10061            .unwrap();
10062        assert_eq!(layouts.len(), 6);
10063
10064        let relative_rows = window
10065            .update(cx, |editor, window, cx| {
10066                let snapshot = editor.snapshot(window, cx);
10067                element.calculate_relative_line_numbers(
10068                    &snapshot,
10069                    &(DisplayRow(0)..DisplayRow(6)),
10070                    Some(DisplayRow(3)),
10071                )
10072            })
10073            .unwrap();
10074        assert_eq!(relative_rows[&DisplayRow(0)], 3);
10075        assert_eq!(relative_rows[&DisplayRow(1)], 2);
10076        assert_eq!(relative_rows[&DisplayRow(2)], 1);
10077        // current line has no relative number
10078        assert_eq!(relative_rows[&DisplayRow(4)], 1);
10079        assert_eq!(relative_rows[&DisplayRow(5)], 2);
10080
10081        // works if cursor is before screen
10082        let relative_rows = window
10083            .update(cx, |editor, window, cx| {
10084                let snapshot = editor.snapshot(window, cx);
10085                element.calculate_relative_line_numbers(
10086                    &snapshot,
10087                    &(DisplayRow(3)..DisplayRow(6)),
10088                    Some(DisplayRow(1)),
10089                )
10090            })
10091            .unwrap();
10092        assert_eq!(relative_rows.len(), 3);
10093        assert_eq!(relative_rows[&DisplayRow(3)], 2);
10094        assert_eq!(relative_rows[&DisplayRow(4)], 3);
10095        assert_eq!(relative_rows[&DisplayRow(5)], 4);
10096
10097        // works if cursor is after screen
10098        let relative_rows = window
10099            .update(cx, |editor, window, cx| {
10100                let snapshot = editor.snapshot(window, cx);
10101                element.calculate_relative_line_numbers(
10102                    &snapshot,
10103                    &(DisplayRow(0)..DisplayRow(3)),
10104                    Some(DisplayRow(6)),
10105                )
10106            })
10107            .unwrap();
10108        assert_eq!(relative_rows.len(), 3);
10109        assert_eq!(relative_rows[&DisplayRow(0)], 5);
10110        assert_eq!(relative_rows[&DisplayRow(1)], 4);
10111        assert_eq!(relative_rows[&DisplayRow(2)], 3);
10112    }
10113
10114    #[gpui::test]
10115    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
10116        init_test(cx, |_| {});
10117
10118        let window = cx.add_window(|window, cx| {
10119            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
10120            Editor::new(EditorMode::full(), buffer, None, window, cx)
10121        });
10122        let cx = &mut VisualTestContext::from_window(*window, cx);
10123        let editor = window.root(cx).unwrap();
10124        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10125
10126        window
10127            .update(cx, |editor, window, cx| {
10128                editor.cursor_shape = CursorShape::Block;
10129                editor.change_selections(None, window, cx, |s| {
10130                    s.select_ranges([
10131                        Point::new(0, 0)..Point::new(1, 0),
10132                        Point::new(3, 2)..Point::new(3, 3),
10133                        Point::new(5, 6)..Point::new(6, 0),
10134                    ]);
10135                });
10136            })
10137            .unwrap();
10138
10139        let (_, state) = cx.draw(
10140            point(px(500.), px(500.)),
10141            size(px(500.), px(500.)),
10142            |_, _| EditorElement::new(&editor, style),
10143        );
10144
10145        assert_eq!(state.selections.len(), 1);
10146        let local_selections = &state.selections[0].1;
10147        assert_eq!(local_selections.len(), 3);
10148        // moves cursor back one line
10149        assert_eq!(
10150            local_selections[0].head,
10151            DisplayPoint::new(DisplayRow(0), 6)
10152        );
10153        assert_eq!(
10154            local_selections[0].range,
10155            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
10156        );
10157
10158        // moves cursor back one column
10159        assert_eq!(
10160            local_selections[1].range,
10161            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
10162        );
10163        assert_eq!(
10164            local_selections[1].head,
10165            DisplayPoint::new(DisplayRow(3), 2)
10166        );
10167
10168        // leaves cursor on the max point
10169        assert_eq!(
10170            local_selections[2].range,
10171            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
10172        );
10173        assert_eq!(
10174            local_selections[2].head,
10175            DisplayPoint::new(DisplayRow(6), 0)
10176        );
10177
10178        // active lines does not include 1 (even though the range of the selection does)
10179        assert_eq!(
10180            state.active_rows.keys().cloned().collect::<Vec<_>>(),
10181            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
10182        );
10183    }
10184
10185    #[gpui::test]
10186    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
10187        init_test(cx, |_| {});
10188
10189        let window = cx.add_window(|window, cx| {
10190            let buffer = MultiBuffer::build_simple("", cx);
10191            Editor::new(EditorMode::full(), buffer, None, window, cx)
10192        });
10193        let cx = &mut VisualTestContext::from_window(*window, cx);
10194        let editor = window.root(cx).unwrap();
10195        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10196        window
10197            .update(cx, |editor, window, cx| {
10198                editor.set_placeholder_text("hello", cx);
10199                editor.insert_blocks(
10200                    [BlockProperties {
10201                        style: BlockStyle::Fixed,
10202                        placement: BlockPlacement::Above(Anchor::min()),
10203                        height: Some(3),
10204                        render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
10205                        priority: 0,
10206                        render_in_minimap: true,
10207                    }],
10208                    None,
10209                    cx,
10210                );
10211
10212                // Blur the editor so that it displays placeholder text.
10213                window.blur();
10214            })
10215            .unwrap();
10216
10217        let (_, state) = cx.draw(
10218            point(px(500.), px(500.)),
10219            size(px(500.), px(500.)),
10220            |_, _| EditorElement::new(&editor, style),
10221        );
10222        assert_eq!(state.position_map.line_layouts.len(), 4);
10223        assert_eq!(state.line_numbers.len(), 1);
10224        assert_eq!(
10225            state
10226                .line_numbers
10227                .get(&MultiBufferRow(0))
10228                .map(|line_number| line_number.shaped_line.text.as_ref()),
10229            Some("1")
10230        );
10231    }
10232
10233    #[gpui::test]
10234    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
10235        const TAB_SIZE: u32 = 4;
10236
10237        let input_text = "\t \t|\t| a b";
10238        let expected_invisibles = vec![
10239            Invisible::Tab {
10240                line_start_offset: 0,
10241                line_end_offset: TAB_SIZE as usize,
10242            },
10243            Invisible::Whitespace {
10244                line_offset: TAB_SIZE as usize,
10245            },
10246            Invisible::Tab {
10247                line_start_offset: TAB_SIZE as usize + 1,
10248                line_end_offset: TAB_SIZE as usize * 2,
10249            },
10250            Invisible::Tab {
10251                line_start_offset: TAB_SIZE as usize * 2 + 1,
10252                line_end_offset: TAB_SIZE as usize * 3,
10253            },
10254            Invisible::Whitespace {
10255                line_offset: TAB_SIZE as usize * 3 + 1,
10256            },
10257            Invisible::Whitespace {
10258                line_offset: TAB_SIZE as usize * 3 + 3,
10259            },
10260        ];
10261        assert_eq!(
10262            expected_invisibles.len(),
10263            input_text
10264                .chars()
10265                .filter(|initial_char| initial_char.is_whitespace())
10266                .count(),
10267            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10268        );
10269
10270        for show_line_numbers in [true, false] {
10271            init_test(cx, |s| {
10272                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10273                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
10274            });
10275
10276            let actual_invisibles = collect_invisibles_from_new_editor(
10277                cx,
10278                EditorMode::full(),
10279                input_text,
10280                px(500.0),
10281                show_line_numbers,
10282            );
10283
10284            assert_eq!(expected_invisibles, actual_invisibles);
10285        }
10286    }
10287
10288    #[gpui::test]
10289    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
10290        init_test(cx, |s| {
10291            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10292            s.defaults.tab_size = NonZeroU32::new(4);
10293        });
10294
10295        for editor_mode_without_invisibles in [
10296            EditorMode::SingleLine { auto_width: false },
10297            EditorMode::AutoHeight {
10298                min_lines: 1,
10299                max_lines: 100,
10300            },
10301        ] {
10302            for show_line_numbers in [true, false] {
10303                let invisibles = collect_invisibles_from_new_editor(
10304                    cx,
10305                    editor_mode_without_invisibles.clone(),
10306                    "\t\t\t| | a b",
10307                    px(500.0),
10308                    show_line_numbers,
10309                );
10310                assert!(
10311                    invisibles.is_empty(),
10312                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
10313                );
10314            }
10315        }
10316    }
10317
10318    #[gpui::test]
10319    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
10320        let tab_size = 4;
10321        let input_text = "a\tbcd     ".repeat(9);
10322        let repeated_invisibles = [
10323            Invisible::Tab {
10324                line_start_offset: 1,
10325                line_end_offset: tab_size as usize,
10326            },
10327            Invisible::Whitespace {
10328                line_offset: tab_size as usize + 3,
10329            },
10330            Invisible::Whitespace {
10331                line_offset: tab_size as usize + 4,
10332            },
10333            Invisible::Whitespace {
10334                line_offset: tab_size as usize + 5,
10335            },
10336            Invisible::Whitespace {
10337                line_offset: tab_size as usize + 6,
10338            },
10339            Invisible::Whitespace {
10340                line_offset: tab_size as usize + 7,
10341            },
10342        ];
10343        let expected_invisibles = std::iter::once(repeated_invisibles)
10344            .cycle()
10345            .take(9)
10346            .flatten()
10347            .collect::<Vec<_>>();
10348        assert_eq!(
10349            expected_invisibles.len(),
10350            input_text
10351                .chars()
10352                .filter(|initial_char| initial_char.is_whitespace())
10353                .count(),
10354            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10355        );
10356        info!("Expected invisibles: {expected_invisibles:?}");
10357
10358        init_test(cx, |_| {});
10359
10360        // Put the same string with repeating whitespace pattern into editors of various size,
10361        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
10362        let resize_step = 10.0;
10363        let mut editor_width = 200.0;
10364        while editor_width <= 1000.0 {
10365            for show_line_numbers in [true, false] {
10366                update_test_language_settings(cx, |s| {
10367                    s.defaults.tab_size = NonZeroU32::new(tab_size);
10368                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10369                    s.defaults.preferred_line_length = Some(editor_width as u32);
10370                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
10371                });
10372
10373                let actual_invisibles = collect_invisibles_from_new_editor(
10374                    cx,
10375                    EditorMode::full(),
10376                    &input_text,
10377                    px(editor_width),
10378                    show_line_numbers,
10379                );
10380
10381                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
10382                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
10383                let mut i = 0;
10384                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
10385                    i = actual_index;
10386                    match expected_invisibles.get(i) {
10387                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
10388                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
10389                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
10390                            _ => {
10391                                panic!(
10392                                    "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
10393                                )
10394                            }
10395                        },
10396                        None => {
10397                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
10398                        }
10399                    }
10400                }
10401                let missing_expected_invisibles = &expected_invisibles[i + 1..];
10402                assert!(
10403                    missing_expected_invisibles.is_empty(),
10404                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
10405                );
10406
10407                editor_width += resize_step;
10408            }
10409        }
10410    }
10411
10412    fn collect_invisibles_from_new_editor(
10413        cx: &mut TestAppContext,
10414        editor_mode: EditorMode,
10415        input_text: &str,
10416        editor_width: Pixels,
10417        show_line_numbers: bool,
10418    ) -> Vec<Invisible> {
10419        info!(
10420            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
10421            editor_width.0
10422        );
10423        let window = cx.add_window(|window, cx| {
10424            let buffer = MultiBuffer::build_simple(input_text, cx);
10425            Editor::new(editor_mode, buffer, None, window, cx)
10426        });
10427        let cx = &mut VisualTestContext::from_window(*window, cx);
10428        let editor = window.root(cx).unwrap();
10429
10430        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10431        window
10432            .update(cx, |editor, _, cx| {
10433                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10434                editor.set_wrap_width(Some(editor_width), cx);
10435                editor.set_show_line_numbers(show_line_numbers, cx);
10436            })
10437            .unwrap();
10438        let (_, state) = cx.draw(
10439            point(px(500.), px(500.)),
10440            size(px(500.), px(500.)),
10441            |_, _| EditorElement::new(&editor, style),
10442        );
10443        state
10444            .position_map
10445            .line_layouts
10446            .iter()
10447            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
10448            .cloned()
10449            .collect()
10450    }
10451}