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