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