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