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