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