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