element.rs

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