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        let git_gutter_width = Self::gutter_strip_width(line_height)
 3019            + gutter_dimensions
 3020                .git_blame_entries_width
 3021                .unwrap_or_default();
 3022        let available_width = gutter_dimensions.left_padding - git_gutter_width;
 3023
 3024        buffer_rows
 3025            .iter()
 3026            .enumerate()
 3027            .map(|(ix, row_info)| {
 3028                let ExpandInfo {
 3029                    excerpt_id,
 3030                    direction,
 3031                } = row_info.expand_info?;
 3032
 3033                let icon_name = match direction {
 3034                    ExpandExcerptDirection::Up => IconName::ExpandUp,
 3035                    ExpandExcerptDirection::Down => IconName::ExpandDown,
 3036                    ExpandExcerptDirection::UpAndDown => IconName::ExpandVertical,
 3037                };
 3038
 3039                let editor = self.editor.clone();
 3040                let is_wide = max_line_number_length
 3041                    >= EditorSettings::get_global(cx).gutter.min_line_number_digits as u32
 3042                    && row_info
 3043                        .buffer_row
 3044                        .is_some_and(|row| (row + 1).ilog10() + 1 == max_line_number_length)
 3045                    || gutter_dimensions.right_padding == px(0.);
 3046
 3047                let width = if is_wide {
 3048                    available_width - px(2.)
 3049                } else {
 3050                    available_width + em_width - px(2.)
 3051                };
 3052
 3053                let toggle = IconButton::new(("expand", ix), icon_name)
 3054                    .icon_color(Color::Custom(cx.theme().colors().editor_line_number))
 3055                    .selected_icon_color(Color::Custom(cx.theme().colors().editor_foreground))
 3056                    .icon_size(IconSize::Custom(rems(editor_font_size / window.rem_size())))
 3057                    .width(width)
 3058                    .on_click(move |_, window, cx| {
 3059                        editor.update(cx, |editor, cx| {
 3060                            editor.expand_excerpt(excerpt_id, direction, window, cx);
 3061                        });
 3062                    })
 3063                    .tooltip(Tooltip::for_action_title(
 3064                        "Expand Excerpt",
 3065                        &crate::actions::ExpandExcerpts::default(),
 3066                    ))
 3067                    .into_any_element();
 3068
 3069                let position = point(
 3070                    git_gutter_width + px(1.),
 3071                    ix as f32 * line_height - (scroll_top % line_height) + px(1.),
 3072                );
 3073                let origin = gutter_hitbox.origin + position;
 3074
 3075                Some((toggle, origin))
 3076            })
 3077            .collect()
 3078    }
 3079
 3080    fn calculate_relative_line_numbers(
 3081        &self,
 3082        snapshot: &EditorSnapshot,
 3083        rows: &Range<DisplayRow>,
 3084        relative_to: Option<DisplayRow>,
 3085    ) -> HashMap<DisplayRow, DisplayRowDelta> {
 3086        let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
 3087        let Some(relative_to) = relative_to else {
 3088            return relative_rows;
 3089        };
 3090
 3091        let start = rows.start.min(relative_to);
 3092        let end = rows.end.max(relative_to);
 3093
 3094        let buffer_rows = snapshot
 3095            .row_infos(start)
 3096            .take(1 + end.minus(start) as usize)
 3097            .collect::<Vec<_>>();
 3098
 3099        let head_idx = relative_to.minus(start);
 3100        let mut delta = 1;
 3101        let mut i = head_idx + 1;
 3102        while i < buffer_rows.len() as u32 {
 3103            if buffer_rows[i as usize].buffer_row.is_some() {
 3104                if rows.contains(&DisplayRow(i + start.0)) {
 3105                    relative_rows.insert(DisplayRow(i + start.0), delta);
 3106                }
 3107                delta += 1;
 3108            }
 3109            i += 1;
 3110        }
 3111        delta = 1;
 3112        i = head_idx.min(buffer_rows.len() as u32 - 1);
 3113        while i > 0 && buffer_rows[i as usize].buffer_row.is_none() {
 3114            i -= 1;
 3115        }
 3116
 3117        while i > 0 {
 3118            i -= 1;
 3119            if buffer_rows[i as usize].buffer_row.is_some() {
 3120                if rows.contains(&DisplayRow(i + start.0)) {
 3121                    relative_rows.insert(DisplayRow(i + start.0), delta);
 3122                }
 3123                delta += 1;
 3124            }
 3125        }
 3126
 3127        relative_rows
 3128    }
 3129
 3130    fn layout_line_numbers(
 3131        &self,
 3132        gutter_hitbox: Option<&Hitbox>,
 3133        gutter_dimensions: GutterDimensions,
 3134        line_height: Pixels,
 3135        scroll_position: gpui::Point<f32>,
 3136        rows: Range<DisplayRow>,
 3137        buffer_rows: &[RowInfo],
 3138        active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
 3139        newest_selection_head: Option<DisplayPoint>,
 3140        snapshot: &EditorSnapshot,
 3141        window: &mut Window,
 3142        cx: &mut App,
 3143    ) -> Arc<HashMap<MultiBufferRow, LineNumberLayout>> {
 3144        let include_line_numbers = snapshot
 3145            .show_line_numbers
 3146            .unwrap_or_else(|| EditorSettings::get_global(cx).gutter.line_numbers);
 3147        if !include_line_numbers {
 3148            return Arc::default();
 3149        }
 3150
 3151        let (newest_selection_head, is_relative) = self.editor.update(cx, |editor, cx| {
 3152            let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
 3153                let newest = editor.selections.newest::<Point>(cx);
 3154                SelectionLayout::new(
 3155                    newest,
 3156                    editor.selections.line_mode,
 3157                    editor.cursor_shape,
 3158                    &snapshot.display_snapshot,
 3159                    true,
 3160                    true,
 3161                    None,
 3162                )
 3163                .head
 3164            });
 3165            let is_relative = editor.should_use_relative_line_numbers(cx);
 3166            (newest_selection_head, is_relative)
 3167        });
 3168
 3169        let relative_to = if is_relative {
 3170            Some(newest_selection_head.row())
 3171        } else {
 3172            None
 3173        };
 3174        let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
 3175        let mut line_number = String::new();
 3176        let line_numbers = buffer_rows
 3177            .iter()
 3178            .enumerate()
 3179            .flat_map(|(ix, row_info)| {
 3180                let display_row = DisplayRow(rows.start.0 + ix as u32);
 3181                line_number.clear();
 3182                let non_relative_number = row_info.buffer_row? + 1;
 3183                let number = relative_rows
 3184                    .get(&display_row)
 3185                    .unwrap_or(&non_relative_number);
 3186                write!(&mut line_number, "{number}").unwrap();
 3187                if row_info
 3188                    .diff_status
 3189                    .is_some_and(|status| status.is_deleted())
 3190                {
 3191                    return None;
 3192                }
 3193
 3194                let color = active_rows
 3195                    .get(&display_row)
 3196                    .map(|spec| {
 3197                        if spec.breakpoint {
 3198                            cx.theme().colors().debugger_accent
 3199                        } else {
 3200                            cx.theme().colors().editor_active_line_number
 3201                        }
 3202                    })
 3203                    .unwrap_or_else(|| cx.theme().colors().editor_line_number);
 3204                let shaped_line =
 3205                    self.shape_line_number(SharedString::from(&line_number), color, window);
 3206                let scroll_top = scroll_position.y * line_height;
 3207                let line_origin = gutter_hitbox.map(|hitbox| {
 3208                    hitbox.origin
 3209                        + point(
 3210                            hitbox.size.width - shaped_line.width - gutter_dimensions.right_padding,
 3211                            ix as f32 * line_height - (scroll_top % line_height),
 3212                        )
 3213                });
 3214
 3215                #[cfg(not(test))]
 3216                let hitbox = line_origin.map(|line_origin| {
 3217                    window.insert_hitbox(
 3218                        Bounds::new(line_origin, size(shaped_line.width, line_height)),
 3219                        HitboxBehavior::Normal,
 3220                    )
 3221                });
 3222                #[cfg(test)]
 3223                let hitbox = {
 3224                    let _ = line_origin;
 3225                    None
 3226                };
 3227
 3228                let multi_buffer_row = DisplayPoint::new(display_row, 0).to_point(snapshot).row;
 3229                let multi_buffer_row = MultiBufferRow(multi_buffer_row);
 3230                let line_number = LineNumberLayout {
 3231                    shaped_line,
 3232                    hitbox,
 3233                };
 3234                Some((multi_buffer_row, line_number))
 3235            })
 3236            .collect();
 3237        Arc::new(line_numbers)
 3238    }
 3239
 3240    fn layout_crease_toggles(
 3241        &self,
 3242        rows: Range<DisplayRow>,
 3243        row_infos: &[RowInfo],
 3244        active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
 3245        snapshot: &EditorSnapshot,
 3246        window: &mut Window,
 3247        cx: &mut App,
 3248    ) -> Vec<Option<AnyElement>> {
 3249        let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
 3250            && snapshot.mode.is_full()
 3251            && self.editor.read(cx).is_singleton(cx);
 3252        if include_fold_statuses {
 3253            row_infos
 3254                .iter()
 3255                .enumerate()
 3256                .map(|(ix, info)| {
 3257                    if info.expand_info.is_some() {
 3258                        return None;
 3259                    }
 3260                    let row = info.multibuffer_row?;
 3261                    let display_row = DisplayRow(rows.start.0 + ix as u32);
 3262                    let active = active_rows.contains_key(&display_row);
 3263
 3264                    snapshot.render_crease_toggle(row, active, self.editor.clone(), window, cx)
 3265                })
 3266                .collect()
 3267        } else {
 3268            Vec::new()
 3269        }
 3270    }
 3271
 3272    fn layout_crease_trailers(
 3273        &self,
 3274        buffer_rows: impl IntoIterator<Item = RowInfo>,
 3275        snapshot: &EditorSnapshot,
 3276        window: &mut Window,
 3277        cx: &mut App,
 3278    ) -> Vec<Option<AnyElement>> {
 3279        buffer_rows
 3280            .into_iter()
 3281            .map(|row_info| {
 3282                if row_info.expand_info.is_some() {
 3283                    return None;
 3284                }
 3285                if let Some(row) = row_info.multibuffer_row {
 3286                    snapshot.render_crease_trailer(row, window, cx)
 3287                } else {
 3288                    None
 3289                }
 3290            })
 3291            .collect()
 3292    }
 3293
 3294    fn bg_segments_per_row(
 3295        rows: Range<DisplayRow>,
 3296        selections: &[(PlayerColor, Vec<SelectionLayout>)],
 3297        highlight_ranges: &[(Range<DisplayPoint>, Hsla)],
 3298        base_background: Hsla,
 3299    ) -> Vec<Vec<(Range<DisplayPoint>, Hsla)>> {
 3300        if rows.start >= rows.end {
 3301            return Vec::new();
 3302        }
 3303        if !base_background.is_opaque() {
 3304            // We don't actually know what color is behind this editor.
 3305            return Vec::new();
 3306        }
 3307        let highlight_iter = highlight_ranges.iter().cloned();
 3308        let selection_iter = selections.iter().flat_map(|(player_color, layouts)| {
 3309            let color = player_color.selection;
 3310            layouts.iter().filter_map(move |selection_layout| {
 3311                if selection_layout.range.start != selection_layout.range.end {
 3312                    Some((selection_layout.range.clone(), color))
 3313                } else {
 3314                    None
 3315                }
 3316            })
 3317        });
 3318        let mut per_row_map = vec![Vec::new(); rows.len()];
 3319        for (range, color) in highlight_iter.chain(selection_iter) {
 3320            let covered_rows = if range.end.column() == 0 {
 3321                cmp::max(range.start.row(), rows.start)..cmp::min(range.end.row(), rows.end)
 3322            } else {
 3323                cmp::max(range.start.row(), rows.start)
 3324                    ..cmp::min(range.end.row().next_row(), rows.end)
 3325            };
 3326            for row in covered_rows.iter_rows() {
 3327                let seg_start = if row == range.start.row() {
 3328                    range.start
 3329                } else {
 3330                    DisplayPoint::new(row, 0)
 3331                };
 3332                let seg_end = if row == range.end.row() && range.end.column() != 0 {
 3333                    range.end
 3334                } else {
 3335                    DisplayPoint::new(row, u32::MAX)
 3336                };
 3337                let ix = row.minus(rows.start) as usize;
 3338                debug_assert!(row >= rows.start && row < rows.end);
 3339                debug_assert!(ix < per_row_map.len());
 3340                per_row_map[ix].push((seg_start..seg_end, color));
 3341            }
 3342        }
 3343        for row_segments in per_row_map.iter_mut() {
 3344            if row_segments.is_empty() {
 3345                continue;
 3346            }
 3347            let segments = mem::take(row_segments);
 3348            let merged = Self::merge_overlapping_ranges(segments, base_background);
 3349            *row_segments = merged;
 3350        }
 3351        per_row_map
 3352    }
 3353
 3354    /// Merge overlapping ranges by splitting at all range boundaries and blending colors where
 3355    /// multiple ranges overlap. The result contains non-overlapping ranges ordered from left to right.
 3356    ///
 3357    /// Expects `start.row() == end.row()` for each range.
 3358    fn merge_overlapping_ranges(
 3359        ranges: Vec<(Range<DisplayPoint>, Hsla)>,
 3360        base_background: Hsla,
 3361    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
 3362        struct Boundary {
 3363            pos: DisplayPoint,
 3364            is_start: bool,
 3365            index: usize,
 3366            color: Hsla,
 3367        }
 3368
 3369        let mut boundaries: SmallVec<[Boundary; 16]> = SmallVec::with_capacity(ranges.len() * 2);
 3370        for (index, (range, color)) in ranges.iter().enumerate() {
 3371            debug_assert!(
 3372                range.start.row() == range.end.row(),
 3373                "expects single-row ranges"
 3374            );
 3375            if range.start < range.end {
 3376                boundaries.push(Boundary {
 3377                    pos: range.start,
 3378                    is_start: true,
 3379                    index,
 3380                    color: *color,
 3381                });
 3382                boundaries.push(Boundary {
 3383                    pos: range.end,
 3384                    is_start: false,
 3385                    index,
 3386                    color: *color,
 3387                });
 3388            }
 3389        }
 3390
 3391        if boundaries.is_empty() {
 3392            return Vec::new();
 3393        }
 3394
 3395        boundaries
 3396            .sort_unstable_by(|a, b| a.pos.cmp(&b.pos).then_with(|| a.is_start.cmp(&b.is_start)));
 3397
 3398        let mut processed_ranges: Vec<(Range<DisplayPoint>, Hsla)> = Vec::new();
 3399        let mut active_ranges: SmallVec<[(usize, Hsla); 8]> = SmallVec::new();
 3400
 3401        let mut i = 0;
 3402        let mut start_pos = boundaries[0].pos;
 3403
 3404        let boundaries_len = boundaries.len();
 3405        while i < boundaries_len {
 3406            let current_boundary_pos = boundaries[i].pos;
 3407            if start_pos < current_boundary_pos {
 3408                if !active_ranges.is_empty() {
 3409                    let mut color = base_background;
 3410                    for &(_, c) in &active_ranges {
 3411                        color = Hsla::blend(color, c);
 3412                    }
 3413                    if let Some((last_range, last_color)) = processed_ranges.last_mut() {
 3414                        if *last_color == color && last_range.end == start_pos {
 3415                            last_range.end = current_boundary_pos;
 3416                        } else {
 3417                            processed_ranges.push((start_pos..current_boundary_pos, color));
 3418                        }
 3419                    } else {
 3420                        processed_ranges.push((start_pos..current_boundary_pos, color));
 3421                    }
 3422                }
 3423            }
 3424            while i < boundaries_len && boundaries[i].pos == current_boundary_pos {
 3425                let active_range = &boundaries[i];
 3426                if active_range.is_start {
 3427                    let idx = active_range.index;
 3428                    let pos = active_ranges
 3429                        .binary_search_by_key(&idx, |(i, _)| *i)
 3430                        .unwrap_or_else(|p| p);
 3431                    active_ranges.insert(pos, (idx, active_range.color));
 3432                } else {
 3433                    let idx = active_range.index;
 3434                    if let Ok(pos) = active_ranges.binary_search_by_key(&idx, |(i, _)| *i) {
 3435                        active_ranges.remove(pos);
 3436                    }
 3437                }
 3438                i += 1;
 3439            }
 3440            start_pos = current_boundary_pos;
 3441        }
 3442
 3443        processed_ranges
 3444    }
 3445
 3446    fn layout_lines(
 3447        rows: Range<DisplayRow>,
 3448        snapshot: &EditorSnapshot,
 3449        style: &EditorStyle,
 3450        editor_width: Pixels,
 3451        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 3452        bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
 3453        window: &mut Window,
 3454        cx: &mut App,
 3455    ) -> Vec<LineWithInvisibles> {
 3456        if rows.start >= rows.end {
 3457            return Vec::new();
 3458        }
 3459
 3460        // Show the placeholder when the editor is empty
 3461        if snapshot.is_empty() {
 3462            let font_size = style.text.font_size.to_pixels(window.rem_size());
 3463            let placeholder_color = cx.theme().colors().text_placeholder;
 3464            let placeholder_text = snapshot.placeholder_text();
 3465
 3466            let placeholder_lines = placeholder_text
 3467                .as_ref()
 3468                .map_or(Vec::new(), |text| text.split('\n').collect::<Vec<_>>());
 3469
 3470            let placeholder_line_count = placeholder_lines.len();
 3471
 3472            placeholder_lines
 3473                .into_iter()
 3474                .skip(rows.start.0 as usize)
 3475                .chain(iter::repeat(""))
 3476                .take(cmp::max(rows.len(), placeholder_line_count))
 3477                .map(move |line| {
 3478                    let run = TextRun {
 3479                        len: line.len(),
 3480                        font: style.text.font(),
 3481                        color: placeholder_color,
 3482                        background_color: None,
 3483                        underline: None,
 3484                        strikethrough: None,
 3485                    };
 3486                    let line = window.text_system().shape_line(
 3487                        line.to_string().into(),
 3488                        font_size,
 3489                        &[run],
 3490                        None,
 3491                    );
 3492                    LineWithInvisibles {
 3493                        width: line.width,
 3494                        len: line.len,
 3495                        fragments: smallvec![LineFragment::Text(line)],
 3496                        invisibles: Vec::new(),
 3497                        font_size,
 3498                    }
 3499                })
 3500                .collect()
 3501        } else {
 3502            let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
 3503            LineWithInvisibles::from_chunks(
 3504                chunks,
 3505                style,
 3506                MAX_LINE_LEN,
 3507                rows.len(),
 3508                &snapshot.mode,
 3509                editor_width,
 3510                is_row_soft_wrapped,
 3511                bg_segments_per_row,
 3512                window,
 3513                cx,
 3514            )
 3515        }
 3516    }
 3517
 3518    fn prepaint_lines(
 3519        &self,
 3520        start_row: DisplayRow,
 3521        line_layouts: &mut [LineWithInvisibles],
 3522        line_height: Pixels,
 3523        scroll_pixel_position: gpui::Point<Pixels>,
 3524        content_origin: gpui::Point<Pixels>,
 3525        window: &mut Window,
 3526        cx: &mut App,
 3527    ) -> SmallVec<[AnyElement; 1]> {
 3528        let mut line_elements = SmallVec::new();
 3529        for (ix, line) in line_layouts.iter_mut().enumerate() {
 3530            let row = start_row + DisplayRow(ix as u32);
 3531            line.prepaint(
 3532                line_height,
 3533                scroll_pixel_position,
 3534                row,
 3535                content_origin,
 3536                &mut line_elements,
 3537                window,
 3538                cx,
 3539            );
 3540        }
 3541        line_elements
 3542    }
 3543
 3544    fn render_block(
 3545        &self,
 3546        block: &Block,
 3547        available_width: AvailableSpace,
 3548        block_id: BlockId,
 3549        block_row_start: DisplayRow,
 3550        snapshot: &EditorSnapshot,
 3551        text_x: Pixels,
 3552        rows: &Range<DisplayRow>,
 3553        line_layouts: &[LineWithInvisibles],
 3554        editor_margins: &EditorMargins,
 3555        line_height: Pixels,
 3556        em_width: Pixels,
 3557        text_hitbox: &Hitbox,
 3558        editor_width: Pixels,
 3559        scroll_width: &mut Pixels,
 3560        resized_blocks: &mut HashMap<CustomBlockId, u32>,
 3561        row_block_types: &mut HashMap<DisplayRow, bool>,
 3562        selections: &[Selection<Point>],
 3563        selected_buffer_ids: &Vec<BufferId>,
 3564        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 3565        sticky_header_excerpt_id: Option<ExcerptId>,
 3566        window: &mut Window,
 3567        cx: &mut App,
 3568    ) -> Option<(AnyElement, Size<Pixels>, DisplayRow, Pixels)> {
 3569        let mut x_position = None;
 3570        let mut element = match block {
 3571            Block::Custom(custom) => {
 3572                let block_start = custom.start().to_point(&snapshot.buffer_snapshot);
 3573                let block_end = custom.end().to_point(&snapshot.buffer_snapshot);
 3574                if block.place_near() && snapshot.is_line_folded(MultiBufferRow(block_start.row)) {
 3575                    return None;
 3576                }
 3577                let align_to = block_start.to_display_point(snapshot);
 3578                let x_and_width = |layout: &LineWithInvisibles| {
 3579                    Some((
 3580                        text_x + layout.x_for_index(align_to.column() as usize),
 3581                        text_x + layout.width,
 3582                    ))
 3583                };
 3584                let line_ix = align_to.row().0.checked_sub(rows.start.0);
 3585                x_position =
 3586                    if let Some(layout) = line_ix.and_then(|ix| line_layouts.get(ix as usize)) {
 3587                        x_and_width(layout)
 3588                    } else {
 3589                        x_and_width(&layout_line(
 3590                            align_to.row(),
 3591                            snapshot,
 3592                            &self.style,
 3593                            editor_width,
 3594                            is_row_soft_wrapped,
 3595                            window,
 3596                            cx,
 3597                        ))
 3598                    };
 3599
 3600                let anchor_x = x_position.unwrap().0;
 3601
 3602                let selected = selections
 3603                    .binary_search_by(|selection| {
 3604                        if selection.end <= block_start {
 3605                            Ordering::Less
 3606                        } else if selection.start >= block_end {
 3607                            Ordering::Greater
 3608                        } else {
 3609                            Ordering::Equal
 3610                        }
 3611                    })
 3612                    .is_ok();
 3613
 3614                div()
 3615                    .size_full()
 3616                    .child(custom.render(&mut BlockContext {
 3617                        window,
 3618                        app: cx,
 3619                        anchor_x,
 3620                        margins: editor_margins,
 3621                        line_height,
 3622                        em_width,
 3623                        block_id,
 3624                        selected,
 3625                        max_width: text_hitbox.size.width.max(*scroll_width),
 3626                        editor_style: &self.style,
 3627                    }))
 3628                    .into_any()
 3629            }
 3630
 3631            Block::FoldedBuffer {
 3632                first_excerpt,
 3633                height,
 3634                ..
 3635            } => {
 3636                let selected = selected_buffer_ids.contains(&first_excerpt.buffer_id);
 3637                let result = v_flex().id(block_id).w_full().pr(editor_margins.right);
 3638
 3639                let jump_data = header_jump_data(snapshot, block_row_start, *height, first_excerpt);
 3640                result
 3641                    .child(self.render_buffer_header(
 3642                        first_excerpt,
 3643                        true,
 3644                        selected,
 3645                        false,
 3646                        jump_data,
 3647                        window,
 3648                        cx,
 3649                    ))
 3650                    .into_any_element()
 3651            }
 3652
 3653            Block::ExcerptBoundary { .. } => {
 3654                let color = cx.theme().colors().clone();
 3655                let mut result = v_flex().id(block_id).w_full();
 3656
 3657                result = result.child(
 3658                    h_flex().relative().child(
 3659                        div()
 3660                            .top(line_height / 2.)
 3661                            .absolute()
 3662                            .w_full()
 3663                            .h_px()
 3664                            .bg(color.border_variant),
 3665                    ),
 3666                );
 3667
 3668                result.into_any()
 3669            }
 3670
 3671            Block::BufferHeader { excerpt, height } => {
 3672                let mut result = v_flex().id(block_id).w_full();
 3673
 3674                let jump_data = header_jump_data(snapshot, block_row_start, *height, excerpt);
 3675
 3676                if sticky_header_excerpt_id != Some(excerpt.id) {
 3677                    let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
 3678
 3679                    result = result.child(div().pr(editor_margins.right).child(
 3680                        self.render_buffer_header(
 3681                            excerpt, false, selected, false, jump_data, window, cx,
 3682                        ),
 3683                    ));
 3684                } else {
 3685                    result =
 3686                        result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
 3687                }
 3688
 3689                result.into_any()
 3690            }
 3691        };
 3692
 3693        // Discover the element's content height, then round up to the nearest multiple of line height.
 3694        let preliminary_size = element.layout_as_root(
 3695            size(available_width, AvailableSpace::MinContent),
 3696            window,
 3697            cx,
 3698        );
 3699        let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
 3700        let final_size = if preliminary_size.height == quantized_height {
 3701            preliminary_size
 3702        } else {
 3703            element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
 3704        };
 3705        let mut element_height_in_lines = ((final_size.height / line_height).ceil() as u32).max(1);
 3706
 3707        let mut row = block_row_start;
 3708        let mut x_offset = px(0.);
 3709        let mut is_block = true;
 3710
 3711        if let BlockId::Custom(custom_block_id) = block_id
 3712            && block.has_height()
 3713        {
 3714            if block.place_near()
 3715                && let Some((x_target, line_width)) = x_position
 3716            {
 3717                let margin = em_width * 2;
 3718                if line_width + final_size.width + margin
 3719                    < editor_width + editor_margins.gutter.full_width()
 3720                    && !row_block_types.contains_key(&(row - 1))
 3721                    && element_height_in_lines == 1
 3722                {
 3723                    x_offset = line_width + margin;
 3724                    row = row - 1;
 3725                    is_block = false;
 3726                    element_height_in_lines = 0;
 3727                    row_block_types.insert(row, is_block);
 3728                } else {
 3729                    let max_offset =
 3730                        editor_width + editor_margins.gutter.full_width() - final_size.width;
 3731                    let min_offset = (x_target + em_width - final_size.width)
 3732                        .max(editor_margins.gutter.full_width());
 3733                    x_offset = x_target.min(max_offset).max(min_offset);
 3734                }
 3735            };
 3736            if element_height_in_lines != block.height() {
 3737                resized_blocks.insert(custom_block_id, element_height_in_lines);
 3738            }
 3739        }
 3740        for i in 0..element_height_in_lines {
 3741            row_block_types.insert(row + i, is_block);
 3742        }
 3743
 3744        Some((element, final_size, row, x_offset))
 3745    }
 3746
 3747    fn render_buffer_header(
 3748        &self,
 3749        for_excerpt: &ExcerptInfo,
 3750        is_folded: bool,
 3751        is_selected: bool,
 3752        is_sticky: bool,
 3753        jump_data: JumpData,
 3754        window: &mut Window,
 3755        cx: &mut App,
 3756    ) -> impl IntoElement {
 3757        let editor = self.editor.read(cx);
 3758        let multi_buffer = editor.buffer.read(cx);
 3759        let file_status = multi_buffer
 3760            .all_diff_hunks_expanded()
 3761            .then(|| {
 3762                editor
 3763                    .project
 3764                    .as_ref()?
 3765                    .read(cx)
 3766                    .status_for_buffer_id(for_excerpt.buffer_id, cx)
 3767            })
 3768            .flatten();
 3769        let indicator = multi_buffer
 3770            .buffer(for_excerpt.buffer_id)
 3771            .and_then(|buffer| {
 3772                let buffer = buffer.read(cx);
 3773                let indicator_color = match (buffer.has_conflict(), buffer.is_dirty()) {
 3774                    (true, _) => Some(Color::Warning),
 3775                    (_, true) => Some(Color::Accent),
 3776                    (false, false) => None,
 3777                };
 3778                indicator_color.map(|indicator_color| Indicator::dot().color(indicator_color))
 3779            });
 3780
 3781        let include_root = editor
 3782            .project
 3783            .as_ref()
 3784            .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 3785            .unwrap_or_default();
 3786        let can_open_excerpts = Editor::can_open_excerpts_in_file(for_excerpt.buffer.file());
 3787        let relative_path = for_excerpt.buffer.resolve_file_path(cx, include_root);
 3788        let filename = relative_path
 3789            .as_ref()
 3790            .and_then(|path| Some(path.file_name()?.to_string_lossy().to_string()));
 3791        let parent_path = relative_path.as_ref().and_then(|path| {
 3792            Some(path.parent()?.to_string_lossy().to_string() + std::path::MAIN_SEPARATOR_STR)
 3793        });
 3794        let focus_handle = editor.focus_handle(cx);
 3795        let colors = cx.theme().colors();
 3796
 3797        let header = div()
 3798            .p_1()
 3799            .w_full()
 3800            .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
 3801            .child(
 3802                h_flex()
 3803                    .size_full()
 3804                    .gap_2()
 3805                    .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
 3806                    .pl_0p5()
 3807                    .pr_5()
 3808                    .rounded_sm()
 3809                    .when(is_sticky, |el| el.shadow_md())
 3810                    .border_1()
 3811                    .map(|div| {
 3812                        let border_color = if is_selected
 3813                            && is_folded
 3814                            && focus_handle.contains_focused(window, cx)
 3815                        {
 3816                            colors.border_focused
 3817                        } else {
 3818                            colors.border
 3819                        };
 3820                        div.border_color(border_color)
 3821                    })
 3822                    .bg(colors.editor_subheader_background)
 3823                    .hover(|style| style.bg(colors.element_hover))
 3824                    .map(|header| {
 3825                        let editor = self.editor.clone();
 3826                        let buffer_id = for_excerpt.buffer_id;
 3827                        let toggle_chevron_icon =
 3828                            FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
 3829                        header.child(
 3830                            div()
 3831                                .hover(|style| style.bg(colors.element_selected))
 3832                                .rounded_xs()
 3833                                .child(
 3834                                    ButtonLike::new("toggle-buffer-fold")
 3835                                        .style(ui::ButtonStyle::Transparent)
 3836                                        .height(px(28.).into())
 3837                                        .width(px(28.))
 3838                                        .children(toggle_chevron_icon)
 3839                                        .tooltip({
 3840                                            let focus_handle = focus_handle.clone();
 3841                                            move |window, cx| {
 3842                                                Tooltip::with_meta_in(
 3843                                                    "Toggle Excerpt Fold",
 3844                                                    Some(&ToggleFold),
 3845                                                    "Alt+click to toggle all",
 3846                                                    &focus_handle,
 3847                                                    window,
 3848                                                    cx,
 3849                                                )
 3850                                            }
 3851                                        })
 3852                                        .on_click(move |event, window, cx| {
 3853                                            if event.modifiers().alt {
 3854                                                // Alt+click toggles all buffers
 3855                                                editor.update(cx, |editor, cx| {
 3856                                                    editor.toggle_fold_all(
 3857                                                        &ToggleFoldAll,
 3858                                                        window,
 3859                                                        cx,
 3860                                                    );
 3861                                                });
 3862                                            } else {
 3863                                                // Regular click toggles single buffer
 3864                                                if is_folded {
 3865                                                    editor.update(cx, |editor, cx| {
 3866                                                        editor.unfold_buffer(buffer_id, cx);
 3867                                                    });
 3868                                                } else {
 3869                                                    editor.update(cx, |editor, cx| {
 3870                                                        editor.fold_buffer(buffer_id, cx);
 3871                                                    });
 3872                                                }
 3873                                            }
 3874                                        }),
 3875                                ),
 3876                        )
 3877                    })
 3878                    .children(
 3879                        editor
 3880                            .addons
 3881                            .values()
 3882                            .filter_map(|addon| {
 3883                                addon.render_buffer_header_controls(for_excerpt, window, cx)
 3884                            })
 3885                            .take(1),
 3886                    )
 3887                    .child(
 3888                        h_flex()
 3889                            .size(Pixels(12.0))
 3890                            .justify_center()
 3891                            .children(indicator),
 3892                    )
 3893                    .child(
 3894                        h_flex()
 3895                            .cursor_pointer()
 3896                            .id("path header block")
 3897                            .size_full()
 3898                            .justify_between()
 3899                            .overflow_hidden()
 3900                            .child(
 3901                                h_flex()
 3902                                    .gap_2()
 3903                                    .map(|path_header| {
 3904                                        let filename = filename
 3905                                            .map(SharedString::from)
 3906                                            .unwrap_or_else(|| "untitled".into());
 3907
 3908                                        path_header
 3909                                            .when(ItemSettings::get_global(cx).file_icons, |el| {
 3910                                                let path = path::Path::new(filename.as_str());
 3911                                                let icon = FileIcons::get_icon(path, cx)
 3912                                                    .unwrap_or_default();
 3913                                                let icon =
 3914                                                    Icon::from_path(icon).color(Color::Muted);
 3915                                                el.child(icon)
 3916                                            })
 3917                                            .child(Label::new(filename).single_line().when_some(
 3918                                                file_status,
 3919                                                |el, status| {
 3920                                                    el.color(if status.is_conflicted() {
 3921                                                        Color::Conflict
 3922                                                    } else if status.is_modified() {
 3923                                                        Color::Modified
 3924                                                    } else if status.is_deleted() {
 3925                                                        Color::Disabled
 3926                                                    } else {
 3927                                                        Color::Created
 3928                                                    })
 3929                                                    .when(status.is_deleted(), |el| {
 3930                                                        el.strikethrough()
 3931                                                    })
 3932                                                },
 3933                                            ))
 3934                                    })
 3935                                    .when_some(parent_path, |then, path| {
 3936                                        then.child(div().child(path).text_color(
 3937                                            if file_status.is_some_and(FileStatus::is_deleted) {
 3938                                                colors.text_disabled
 3939                                            } else {
 3940                                                colors.text_muted
 3941                                            },
 3942                                        ))
 3943                                    }),
 3944                            )
 3945                            .when(
 3946                                can_open_excerpts && is_selected && relative_path.is_some(),
 3947                                |el| {
 3948                                    el.child(
 3949                                        h_flex()
 3950                                            .id("jump-to-file-button")
 3951                                            .gap_2p5()
 3952                                            .child(Label::new("Jump To File"))
 3953                                            .children(
 3954                                                KeyBinding::for_action_in(
 3955                                                    &OpenExcerpts,
 3956                                                    &focus_handle,
 3957                                                    window,
 3958                                                    cx,
 3959                                                )
 3960                                                .map(|binding| binding.into_any_element()),
 3961                                            ),
 3962                                    )
 3963                                },
 3964                            )
 3965                            .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 3966                            .on_click(window.listener_for(&self.editor, {
 3967                                move |editor, e: &ClickEvent, window, cx| {
 3968                                    editor.open_excerpts_common(
 3969                                        Some(jump_data.clone()),
 3970                                        e.modifiers().secondary(),
 3971                                        window,
 3972                                        cx,
 3973                                    );
 3974                                }
 3975                            })),
 3976                    ),
 3977            );
 3978
 3979        let file = for_excerpt.buffer.file().cloned();
 3980        let editor = self.editor.clone();
 3981        right_click_menu("buffer-header-context-menu")
 3982            .trigger(move |_, _, _| header)
 3983            .menu(move |window, cx| {
 3984                let menu_context = focus_handle.clone();
 3985                let editor = editor.clone();
 3986                let file = file.clone();
 3987                ContextMenu::build(window, cx, move |mut menu, window, cx| {
 3988                    if let Some(file) = file
 3989                        && let Some(project) = editor.read(cx).project()
 3990                        && let Some(worktree) =
 3991                            project.read(cx).worktree_for_id(file.worktree_id(cx), cx)
 3992                    {
 3993                        let worktree = worktree.read(cx);
 3994                        let relative_path = file.path();
 3995                        let entry_for_path = worktree.entry_for_path(relative_path);
 3996                        let abs_path = entry_for_path.map(|e| {
 3997                            e.canonical_path.as_deref().map_or_else(
 3998                                || worktree.abs_path().join(relative_path),
 3999                                Path::to_path_buf,
 4000                            )
 4001                        });
 4002                        let has_relative_path = worktree.root_entry().is_some_and(Entry::is_dir);
 4003
 4004                        let parent_abs_path = abs_path
 4005                            .as_ref()
 4006                            .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
 4007                        let relative_path = has_relative_path
 4008                            .then_some(relative_path)
 4009                            .map(ToOwned::to_owned);
 4010
 4011                        let visible_in_project_panel =
 4012                            relative_path.is_some() && worktree.is_visible();
 4013                        let reveal_in_project_panel = entry_for_path
 4014                            .filter(|_| visible_in_project_panel)
 4015                            .map(|entry| entry.id);
 4016                        menu = menu
 4017                            .when_some(abs_path, |menu, abs_path| {
 4018                                menu.entry(
 4019                                    "Copy Path",
 4020                                    Some(Box::new(zed_actions::workspace::CopyPath)),
 4021                                    window.handler_for(&editor, move |_, _, cx| {
 4022                                        cx.write_to_clipboard(ClipboardItem::new_string(
 4023                                            abs_path.to_string_lossy().to_string(),
 4024                                        ));
 4025                                    }),
 4026                                )
 4027                            })
 4028                            .when_some(relative_path, |menu, relative_path| {
 4029                                menu.entry(
 4030                                    "Copy Relative Path",
 4031                                    Some(Box::new(zed_actions::workspace::CopyRelativePath)),
 4032                                    window.handler_for(&editor, move |_, _, cx| {
 4033                                        cx.write_to_clipboard(ClipboardItem::new_string(
 4034                                            relative_path.to_string_lossy().to_string(),
 4035                                        ));
 4036                                    }),
 4037                                )
 4038                            })
 4039                            .when(
 4040                                reveal_in_project_panel.is_some() || parent_abs_path.is_some(),
 4041                                |menu| menu.separator(),
 4042                            )
 4043                            .when_some(reveal_in_project_panel, |menu, entry_id| {
 4044                                menu.entry(
 4045                                    "Reveal In Project Panel",
 4046                                    Some(Box::new(RevealInProjectPanel::default())),
 4047                                    window.handler_for(&editor, move |editor, _, cx| {
 4048                                        if let Some(project) = &mut editor.project {
 4049                                            project.update(cx, |_, cx| {
 4050                                                cx.emit(project::Event::RevealInProjectPanel(
 4051                                                    entry_id,
 4052                                                ))
 4053                                            });
 4054                                        }
 4055                                    }),
 4056                                )
 4057                            })
 4058                            .when_some(parent_abs_path, |menu, parent_abs_path| {
 4059                                menu.entry(
 4060                                    "Open in Terminal",
 4061                                    Some(Box::new(OpenInTerminal)),
 4062                                    window.handler_for(&editor, move |_, window, cx| {
 4063                                        window.dispatch_action(
 4064                                            OpenTerminal {
 4065                                                working_directory: parent_abs_path.clone(),
 4066                                            }
 4067                                            .boxed_clone(),
 4068                                            cx,
 4069                                        );
 4070                                    }),
 4071                                )
 4072                            });
 4073                    }
 4074
 4075                    menu.context(menu_context)
 4076                })
 4077            })
 4078    }
 4079
 4080    fn render_blocks(
 4081        &self,
 4082        rows: Range<DisplayRow>,
 4083        snapshot: &EditorSnapshot,
 4084        hitbox: &Hitbox,
 4085        text_hitbox: &Hitbox,
 4086        editor_width: Pixels,
 4087        scroll_width: &mut Pixels,
 4088        editor_margins: &EditorMargins,
 4089        em_width: Pixels,
 4090        text_x: Pixels,
 4091        line_height: Pixels,
 4092        line_layouts: &mut [LineWithInvisibles],
 4093        selections: &[Selection<Point>],
 4094        selected_buffer_ids: &Vec<BufferId>,
 4095        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 4096        sticky_header_excerpt_id: Option<ExcerptId>,
 4097        window: &mut Window,
 4098        cx: &mut App,
 4099    ) -> Result<(Vec<BlockLayout>, HashMap<DisplayRow, bool>), HashMap<CustomBlockId, u32>> {
 4100        let (fixed_blocks, non_fixed_blocks) = snapshot
 4101            .blocks_in_range(rows.clone())
 4102            .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
 4103
 4104        let mut focused_block = self
 4105            .editor
 4106            .update(cx, |editor, _| editor.take_focused_block());
 4107        let mut fixed_block_max_width = Pixels::ZERO;
 4108        let mut blocks = Vec::new();
 4109        let mut resized_blocks = HashMap::default();
 4110        let mut row_block_types = HashMap::default();
 4111
 4112        for (row, block) in fixed_blocks {
 4113            let block_id = block.id();
 4114
 4115            if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
 4116                focused_block = None;
 4117            }
 4118
 4119            if let Some((element, element_size, row, x_offset)) = self.render_block(
 4120                block,
 4121                AvailableSpace::MinContent,
 4122                block_id,
 4123                row,
 4124                snapshot,
 4125                text_x,
 4126                &rows,
 4127                line_layouts,
 4128                editor_margins,
 4129                line_height,
 4130                em_width,
 4131                text_hitbox,
 4132                editor_width,
 4133                scroll_width,
 4134                &mut resized_blocks,
 4135                &mut row_block_types,
 4136                selections,
 4137                selected_buffer_ids,
 4138                is_row_soft_wrapped,
 4139                sticky_header_excerpt_id,
 4140                window,
 4141                cx,
 4142            ) {
 4143                fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
 4144                blocks.push(BlockLayout {
 4145                    id: block_id,
 4146                    x_offset,
 4147                    row: Some(row),
 4148                    element,
 4149                    available_space: size(AvailableSpace::MinContent, element_size.height.into()),
 4150                    style: BlockStyle::Fixed,
 4151                    overlaps_gutter: true,
 4152                    is_buffer_header: block.is_buffer_header(),
 4153                });
 4154            }
 4155        }
 4156
 4157        for (row, block) in non_fixed_blocks {
 4158            let style = block.style();
 4159            let width = match (style, block.place_near()) {
 4160                (_, true) => AvailableSpace::MinContent,
 4161                (BlockStyle::Sticky, _) => hitbox.size.width.into(),
 4162                (BlockStyle::Flex, _) => hitbox
 4163                    .size
 4164                    .width
 4165                    .max(fixed_block_max_width)
 4166                    .max(editor_margins.gutter.width + *scroll_width)
 4167                    .into(),
 4168                (BlockStyle::Fixed, _) => unreachable!(),
 4169            };
 4170            let block_id = block.id();
 4171
 4172            if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
 4173                focused_block = None;
 4174            }
 4175
 4176            if let Some((element, element_size, row, x_offset)) = self.render_block(
 4177                block,
 4178                width,
 4179                block_id,
 4180                row,
 4181                snapshot,
 4182                text_x,
 4183                &rows,
 4184                line_layouts,
 4185                editor_margins,
 4186                line_height,
 4187                em_width,
 4188                text_hitbox,
 4189                editor_width,
 4190                scroll_width,
 4191                &mut resized_blocks,
 4192                &mut row_block_types,
 4193                selections,
 4194                selected_buffer_ids,
 4195                is_row_soft_wrapped,
 4196                sticky_header_excerpt_id,
 4197                window,
 4198                cx,
 4199            ) {
 4200                blocks.push(BlockLayout {
 4201                    id: block_id,
 4202                    x_offset,
 4203                    row: Some(row),
 4204                    element,
 4205                    available_space: size(width, element_size.height.into()),
 4206                    style,
 4207                    overlaps_gutter: !block.place_near(),
 4208                    is_buffer_header: block.is_buffer_header(),
 4209                });
 4210            }
 4211        }
 4212
 4213        if let Some(focused_block) = focused_block
 4214            && let Some(focus_handle) = focused_block.focus_handle.upgrade()
 4215            && focus_handle.is_focused(window)
 4216            && let Some(block) = snapshot.block_for_id(focused_block.id)
 4217        {
 4218            let style = block.style();
 4219            let width = match style {
 4220                BlockStyle::Fixed => AvailableSpace::MinContent,
 4221                BlockStyle::Flex => AvailableSpace::Definite(
 4222                    hitbox
 4223                        .size
 4224                        .width
 4225                        .max(fixed_block_max_width)
 4226                        .max(editor_margins.gutter.width + *scroll_width),
 4227                ),
 4228                BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
 4229            };
 4230
 4231            if let Some((element, element_size, _, x_offset)) = self.render_block(
 4232                &block,
 4233                width,
 4234                focused_block.id,
 4235                rows.end,
 4236                snapshot,
 4237                text_x,
 4238                &rows,
 4239                line_layouts,
 4240                editor_margins,
 4241                line_height,
 4242                em_width,
 4243                text_hitbox,
 4244                editor_width,
 4245                scroll_width,
 4246                &mut resized_blocks,
 4247                &mut row_block_types,
 4248                selections,
 4249                selected_buffer_ids,
 4250                is_row_soft_wrapped,
 4251                sticky_header_excerpt_id,
 4252                window,
 4253                cx,
 4254            ) {
 4255                blocks.push(BlockLayout {
 4256                    id: block.id(),
 4257                    x_offset,
 4258                    row: None,
 4259                    element,
 4260                    available_space: size(width, element_size.height.into()),
 4261                    style,
 4262                    overlaps_gutter: true,
 4263                    is_buffer_header: block.is_buffer_header(),
 4264                });
 4265            }
 4266        }
 4267
 4268        if resized_blocks.is_empty() {
 4269            *scroll_width =
 4270                (*scroll_width).max(fixed_block_max_width - editor_margins.gutter.width);
 4271            Ok((blocks, row_block_types))
 4272        } else {
 4273            Err(resized_blocks)
 4274        }
 4275    }
 4276
 4277    fn layout_blocks(
 4278        &self,
 4279        blocks: &mut Vec<BlockLayout>,
 4280        hitbox: &Hitbox,
 4281        line_height: Pixels,
 4282        scroll_pixel_position: gpui::Point<Pixels>,
 4283        window: &mut Window,
 4284        cx: &mut App,
 4285    ) {
 4286        for block in blocks {
 4287            let mut origin = if let Some(row) = block.row {
 4288                hitbox.origin
 4289                    + point(
 4290                        block.x_offset,
 4291                        row.as_f32() * line_height - scroll_pixel_position.y,
 4292                    )
 4293            } else {
 4294                // Position the block outside the visible area
 4295                hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
 4296            };
 4297
 4298            if !matches!(block.style, BlockStyle::Sticky) {
 4299                origin += point(-scroll_pixel_position.x, Pixels::ZERO);
 4300            }
 4301
 4302            let focus_handle =
 4303                block
 4304                    .element
 4305                    .prepaint_as_root(origin, block.available_space, window, cx);
 4306
 4307            if let Some(focus_handle) = focus_handle {
 4308                self.editor.update(cx, |editor, _cx| {
 4309                    editor.set_focused_block(FocusedBlock {
 4310                        id: block.id,
 4311                        focus_handle: focus_handle.downgrade(),
 4312                    });
 4313                });
 4314            }
 4315        }
 4316    }
 4317
 4318    fn layout_sticky_buffer_header(
 4319        &self,
 4320        StickyHeaderExcerpt { excerpt }: StickyHeaderExcerpt<'_>,
 4321        scroll_position: f32,
 4322        line_height: Pixels,
 4323        right_margin: Pixels,
 4324        snapshot: &EditorSnapshot,
 4325        hitbox: &Hitbox,
 4326        selected_buffer_ids: &Vec<BufferId>,
 4327        blocks: &[BlockLayout],
 4328        window: &mut Window,
 4329        cx: &mut App,
 4330    ) -> AnyElement {
 4331        let jump_data = header_jump_data(
 4332            snapshot,
 4333            DisplayRow(scroll_position as u32),
 4334            FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 4335            excerpt,
 4336        );
 4337
 4338        let editor_bg_color = cx.theme().colors().editor_background;
 4339
 4340        let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
 4341
 4342        let available_width = hitbox.bounds.size.width - right_margin;
 4343
 4344        let mut header = v_flex()
 4345            .w_full()
 4346            .relative()
 4347            .child(
 4348                div()
 4349                    .w(available_width)
 4350                    .h(FILE_HEADER_HEIGHT as f32 * line_height)
 4351                    .bg(linear_gradient(
 4352                        0.,
 4353                        linear_color_stop(editor_bg_color.opacity(0.), 0.),
 4354                        linear_color_stop(editor_bg_color, 0.6),
 4355                    ))
 4356                    .absolute()
 4357                    .top_0(),
 4358            )
 4359            .child(
 4360                self.render_buffer_header(excerpt, false, selected, true, jump_data, window, cx)
 4361                    .into_any_element(),
 4362            )
 4363            .into_any_element();
 4364
 4365        let mut origin = hitbox.origin;
 4366        // Move floating header up to avoid colliding with the next buffer header.
 4367        for block in blocks.iter() {
 4368            if !block.is_buffer_header {
 4369                continue;
 4370            }
 4371
 4372            let Some(display_row) = block.row.filter(|row| row.0 > scroll_position as u32) else {
 4373                continue;
 4374            };
 4375
 4376            let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
 4377            let offset = scroll_position - max_row as f32;
 4378
 4379            if offset > 0.0 {
 4380                origin.y -= offset * line_height;
 4381            }
 4382            break;
 4383        }
 4384
 4385        let size = size(
 4386            AvailableSpace::Definite(available_width),
 4387            AvailableSpace::MinContent,
 4388        );
 4389
 4390        header.prepaint_as_root(origin, size, window, cx);
 4391
 4392        header
 4393    }
 4394
 4395    fn layout_cursor_popovers(
 4396        &self,
 4397        line_height: Pixels,
 4398        text_hitbox: &Hitbox,
 4399        content_origin: gpui::Point<Pixels>,
 4400        right_margin: Pixels,
 4401        start_row: DisplayRow,
 4402        scroll_pixel_position: gpui::Point<Pixels>,
 4403        line_layouts: &[LineWithInvisibles],
 4404        cursor: DisplayPoint,
 4405        cursor_point: Point,
 4406        style: &EditorStyle,
 4407        window: &mut Window,
 4408        cx: &mut App,
 4409    ) -> Option<ContextMenuLayout> {
 4410        let mut min_menu_height = Pixels::ZERO;
 4411        let mut max_menu_height = Pixels::ZERO;
 4412        let mut height_above_menu = Pixels::ZERO;
 4413        let height_below_menu = Pixels::ZERO;
 4414        let mut edit_prediction_popover_visible = false;
 4415        let mut context_menu_visible = false;
 4416        let context_menu_placement;
 4417
 4418        {
 4419            let editor = self.editor.read(cx);
 4420            if editor.edit_prediction_visible_in_cursor_popover(editor.has_active_edit_prediction())
 4421            {
 4422                height_above_menu +=
 4423                    editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
 4424                edit_prediction_popover_visible = true;
 4425            }
 4426
 4427            if editor.context_menu_visible()
 4428                && let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin()
 4429            {
 4430                let (min_height_in_lines, max_height_in_lines) = editor
 4431                    .context_menu_options
 4432                    .as_ref()
 4433                    .map_or((3, 12), |options| {
 4434                        (options.min_entries_visible, options.max_entries_visible)
 4435                    });
 4436
 4437                min_menu_height += line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
 4438                max_menu_height += line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
 4439                context_menu_visible = true;
 4440            }
 4441            context_menu_placement = editor
 4442                .context_menu_options
 4443                .as_ref()
 4444                .and_then(|options| options.placement.clone());
 4445        }
 4446
 4447        let visible = edit_prediction_popover_visible || context_menu_visible;
 4448        if !visible {
 4449            return None;
 4450        }
 4451
 4452        let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
 4453        let target_position = content_origin
 4454            + gpui::Point {
 4455                x: cmp::max(
 4456                    px(0.),
 4457                    cursor_row_layout.x_for_index(cursor.column() as usize)
 4458                        - scroll_pixel_position.x,
 4459                ),
 4460                y: cmp::max(
 4461                    px(0.),
 4462                    cursor.row().next_row().as_f32() * line_height - scroll_pixel_position.y,
 4463                ),
 4464            };
 4465
 4466        let viewport_bounds =
 4467            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 4468                right: -right_margin - MENU_GAP,
 4469                ..Default::default()
 4470            });
 4471
 4472        let min_height = height_above_menu + min_menu_height + height_below_menu;
 4473        let max_height = height_above_menu + max_menu_height + height_below_menu;
 4474        let (laid_out_popovers, y_flipped) = self.layout_popovers_above_or_below_line(
 4475            target_position,
 4476            line_height,
 4477            min_height,
 4478            max_height,
 4479            context_menu_placement,
 4480            text_hitbox,
 4481            viewport_bounds,
 4482            window,
 4483            cx,
 4484            |height, max_width_for_stable_x, y_flipped, window, cx| {
 4485                // First layout the menu to get its size - others can be at least this wide.
 4486                let context_menu = if context_menu_visible {
 4487                    let menu_height = if y_flipped {
 4488                        height - height_below_menu
 4489                    } else {
 4490                        height - height_above_menu
 4491                    };
 4492                    let mut element = self
 4493                        .render_context_menu(line_height, menu_height, window, cx)
 4494                        .expect("Visible context menu should always render.");
 4495                    let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 4496                    Some((CursorPopoverType::CodeContextMenu, element, size))
 4497                } else {
 4498                    None
 4499                };
 4500                let min_width = context_menu
 4501                    .as_ref()
 4502                    .map_or(px(0.), |(_, _, size)| size.width);
 4503                let max_width = max_width_for_stable_x.max(
 4504                    context_menu
 4505                        .as_ref()
 4506                        .map_or(px(0.), |(_, _, size)| size.width),
 4507                );
 4508
 4509                let edit_prediction = if edit_prediction_popover_visible {
 4510                    self.editor.update(cx, move |editor, cx| {
 4511                        let accept_binding =
 4512                            editor.accept_edit_prediction_keybind(false, window, cx);
 4513                        let mut element = editor.render_edit_prediction_cursor_popover(
 4514                            min_width,
 4515                            max_width,
 4516                            cursor_point,
 4517                            style,
 4518                            accept_binding.keystroke(),
 4519                            window,
 4520                            cx,
 4521                        )?;
 4522                        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 4523                        Some((CursorPopoverType::EditPrediction, element, size))
 4524                    })
 4525                } else {
 4526                    None
 4527                };
 4528                vec![edit_prediction, context_menu]
 4529                    .into_iter()
 4530                    .flatten()
 4531                    .collect::<Vec<_>>()
 4532            },
 4533        )?;
 4534
 4535        let (menu_ix, (_, menu_bounds)) = laid_out_popovers
 4536            .iter()
 4537            .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))?;
 4538        let last_ix = laid_out_popovers.len() - 1;
 4539        let menu_is_last = menu_ix == last_ix;
 4540        let first_popover_bounds = laid_out_popovers[0].1;
 4541        let last_popover_bounds = laid_out_popovers[last_ix].1;
 4542
 4543        // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
 4544        // right, and otherwise it goes below or to the right.
 4545        let mut target_bounds = Bounds::from_corners(
 4546            first_popover_bounds.origin,
 4547            last_popover_bounds.bottom_right(),
 4548        );
 4549        target_bounds.size.width = menu_bounds.size.width;
 4550
 4551        // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
 4552        // based on this is preferred for layout stability.
 4553        let mut max_target_bounds = target_bounds;
 4554        max_target_bounds.size.height = max_height;
 4555        if y_flipped {
 4556            max_target_bounds.origin.y -= max_height - target_bounds.size.height;
 4557        }
 4558
 4559        // Add spacing around `target_bounds` and `max_target_bounds`.
 4560        let mut extend_amount = Edges::all(MENU_GAP);
 4561        if y_flipped {
 4562            extend_amount.bottom = line_height;
 4563        } else {
 4564            extend_amount.top = line_height;
 4565        }
 4566        let target_bounds = target_bounds.extend(extend_amount);
 4567        let max_target_bounds = max_target_bounds.extend(extend_amount);
 4568
 4569        let must_place_above_or_below =
 4570            if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
 4571                laid_out_popovers[menu_ix + 1..]
 4572                    .iter()
 4573                    .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
 4574            } else {
 4575                false
 4576            };
 4577
 4578        let aside_bounds = self.layout_context_menu_aside(
 4579            y_flipped,
 4580            *menu_bounds,
 4581            target_bounds,
 4582            max_target_bounds,
 4583            max_menu_height,
 4584            must_place_above_or_below,
 4585            text_hitbox,
 4586            viewport_bounds,
 4587            window,
 4588            cx,
 4589        );
 4590
 4591        if let Some(menu_bounds) = laid_out_popovers.iter().find_map(|(popover_type, bounds)| {
 4592            if matches!(popover_type, CursorPopoverType::CodeContextMenu) {
 4593                Some(*bounds)
 4594            } else {
 4595                None
 4596            }
 4597        }) {
 4598            let bounds = if let Some(aside_bounds) = aside_bounds {
 4599                menu_bounds.union(&aside_bounds)
 4600            } else {
 4601                menu_bounds
 4602            };
 4603            return Some(ContextMenuLayout { y_flipped, bounds });
 4604        }
 4605
 4606        None
 4607    }
 4608
 4609    fn layout_gutter_menu(
 4610        &self,
 4611        line_height: Pixels,
 4612        text_hitbox: &Hitbox,
 4613        content_origin: gpui::Point<Pixels>,
 4614        right_margin: Pixels,
 4615        scroll_pixel_position: gpui::Point<Pixels>,
 4616        gutter_overshoot: Pixels,
 4617        window: &mut Window,
 4618        cx: &mut App,
 4619    ) {
 4620        let editor = self.editor.read(cx);
 4621        if !editor.context_menu_visible() {
 4622            return;
 4623        }
 4624        let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
 4625            editor.context_menu_origin()
 4626        else {
 4627            return;
 4628        };
 4629        // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
 4630        // indicator than just a plain first column of the text field.
 4631        let target_position = content_origin
 4632            + gpui::Point {
 4633                x: -gutter_overshoot,
 4634                y: gutter_row.next_row().as_f32() * line_height - scroll_pixel_position.y,
 4635            };
 4636
 4637        let (min_height_in_lines, max_height_in_lines) = editor
 4638            .context_menu_options
 4639            .as_ref()
 4640            .map_or((3, 12), |options| {
 4641                (options.min_entries_visible, options.max_entries_visible)
 4642            });
 4643
 4644        let min_height = line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
 4645        let max_height = line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
 4646        let viewport_bounds =
 4647            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 4648                right: -right_margin - MENU_GAP,
 4649                ..Default::default()
 4650            });
 4651        self.layout_popovers_above_or_below_line(
 4652            target_position,
 4653            line_height,
 4654            min_height,
 4655            max_height,
 4656            editor
 4657                .context_menu_options
 4658                .as_ref()
 4659                .and_then(|options| options.placement.clone()),
 4660            text_hitbox,
 4661            viewport_bounds,
 4662            window,
 4663            cx,
 4664            move |height, _max_width_for_stable_x, _, window, cx| {
 4665                let mut element = self
 4666                    .render_context_menu(line_height, height, window, cx)
 4667                    .expect("Visible context menu should always render.");
 4668                let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 4669                vec![(CursorPopoverType::CodeContextMenu, element, size)]
 4670            },
 4671        );
 4672    }
 4673
 4674    fn layout_popovers_above_or_below_line(
 4675        &self,
 4676        target_position: gpui::Point<Pixels>,
 4677        line_height: Pixels,
 4678        min_height: Pixels,
 4679        max_height: Pixels,
 4680        placement: Option<ContextMenuPlacement>,
 4681        text_hitbox: &Hitbox,
 4682        viewport_bounds: Bounds<Pixels>,
 4683        window: &mut Window,
 4684        cx: &mut App,
 4685        make_sized_popovers: impl FnOnce(
 4686            Pixels,
 4687            Pixels,
 4688            bool,
 4689            &mut Window,
 4690            &mut App,
 4691        ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
 4692    ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
 4693        let text_style = TextStyleRefinement {
 4694            line_height: Some(DefiniteLength::Fraction(
 4695                BufferLineHeight::Comfortable.value(),
 4696            )),
 4697            ..Default::default()
 4698        };
 4699        window.with_text_style(Some(text_style), |window| {
 4700            // If the max height won't fit below and there is more space above, put it above the line.
 4701            let bottom_y_when_flipped = target_position.y - line_height;
 4702            let available_above = bottom_y_when_flipped - text_hitbox.top();
 4703            let available_below = text_hitbox.bottom() - target_position.y;
 4704            let y_overflows_below = max_height > available_below;
 4705            let mut y_flipped = match placement {
 4706                Some(ContextMenuPlacement::Above) => true,
 4707                Some(ContextMenuPlacement::Below) => false,
 4708                None => y_overflows_below && available_above > available_below,
 4709            };
 4710            let mut height = cmp::min(
 4711                max_height,
 4712                if y_flipped {
 4713                    available_above
 4714                } else {
 4715                    available_below
 4716                },
 4717            );
 4718
 4719            // If the min height doesn't fit within text bounds, instead fit within the window.
 4720            if height < min_height {
 4721                let available_above = bottom_y_when_flipped;
 4722                let available_below = viewport_bounds.bottom() - target_position.y;
 4723                let (y_flipped_override, height_override) = match placement {
 4724                    Some(ContextMenuPlacement::Above) => {
 4725                        (true, cmp::min(available_above, min_height))
 4726                    }
 4727                    Some(ContextMenuPlacement::Below) => {
 4728                        (false, cmp::min(available_below, min_height))
 4729                    }
 4730                    None => {
 4731                        if available_below > min_height {
 4732                            (false, min_height)
 4733                        } else if available_above > min_height {
 4734                            (true, min_height)
 4735                        } else if available_above > available_below {
 4736                            (true, available_above)
 4737                        } else {
 4738                            (false, available_below)
 4739                        }
 4740                    }
 4741                };
 4742                y_flipped = y_flipped_override;
 4743                height = height_override;
 4744            }
 4745
 4746            let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
 4747
 4748            // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
 4749            // for very narrow windows.
 4750            let popovers =
 4751                make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
 4752            if popovers.is_empty() {
 4753                return None;
 4754            }
 4755
 4756            let max_width = popovers
 4757                .iter()
 4758                .map(|(_, _, size)| size.width)
 4759                .max()
 4760                .unwrap_or_default();
 4761
 4762            let mut current_position = gpui::Point {
 4763                // Snap the right edge of the list to the right edge of the window if its horizontal bounds
 4764                // overflow. Include space for the scrollbar.
 4765                x: target_position
 4766                    .x
 4767                    .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
 4768                y: if y_flipped {
 4769                    bottom_y_when_flipped
 4770                } else {
 4771                    target_position.y
 4772                },
 4773            };
 4774
 4775            let mut laid_out_popovers = popovers
 4776                .into_iter()
 4777                .map(|(popover_type, element, size)| {
 4778                    if y_flipped {
 4779                        current_position.y -= size.height;
 4780                    }
 4781                    let position = current_position;
 4782                    window.defer_draw(element, current_position, 1);
 4783                    if !y_flipped {
 4784                        current_position.y += size.height + MENU_GAP;
 4785                    } else {
 4786                        current_position.y -= MENU_GAP;
 4787                    }
 4788                    (popover_type, Bounds::new(position, size))
 4789                })
 4790                .collect::<Vec<_>>();
 4791
 4792            if y_flipped {
 4793                laid_out_popovers.reverse();
 4794            }
 4795
 4796            Some((laid_out_popovers, y_flipped))
 4797        })
 4798    }
 4799
 4800    fn layout_context_menu_aside(
 4801        &self,
 4802        y_flipped: bool,
 4803        menu_bounds: Bounds<Pixels>,
 4804        target_bounds: Bounds<Pixels>,
 4805        max_target_bounds: Bounds<Pixels>,
 4806        max_height: Pixels,
 4807        must_place_above_or_below: bool,
 4808        text_hitbox: &Hitbox,
 4809        viewport_bounds: Bounds<Pixels>,
 4810        window: &mut Window,
 4811        cx: &mut App,
 4812    ) -> Option<Bounds<Pixels>> {
 4813        let available_within_viewport = target_bounds.space_within(&viewport_bounds);
 4814        let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
 4815            && !must_place_above_or_below
 4816        {
 4817            let max_width = cmp::min(
 4818                available_within_viewport.right - px(1.),
 4819                MENU_ASIDE_MAX_WIDTH,
 4820            );
 4821            let mut aside = self.render_context_menu_aside(
 4822                size(max_width, max_height - POPOVER_Y_PADDING),
 4823                window,
 4824                cx,
 4825            )?;
 4826            let size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
 4827            let right_position = point(target_bounds.right(), menu_bounds.origin.y);
 4828            Some((aside, right_position, size))
 4829        } else {
 4830            let max_size = size(
 4831                // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
 4832                // won't be needed here.
 4833                cmp::min(
 4834                    cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
 4835                    viewport_bounds.right(),
 4836                ),
 4837                cmp::min(
 4838                    max_height,
 4839                    cmp::max(
 4840                        available_within_viewport.top,
 4841                        available_within_viewport.bottom,
 4842                    ),
 4843                ) - POPOVER_Y_PADDING,
 4844            );
 4845            let mut aside = self.render_context_menu_aside(max_size, window, cx)?;
 4846            let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
 4847
 4848            let top_position = point(
 4849                menu_bounds.origin.x,
 4850                target_bounds.top() - actual_size.height,
 4851            );
 4852            let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
 4853
 4854            let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
 4855                // Prefer to fit on the same side of the line as the menu, then on the other side of
 4856                // the line.
 4857                if !y_flipped && wanted.height < available.bottom {
 4858                    Some(bottom_position)
 4859                } else if !y_flipped && wanted.height < available.top {
 4860                    Some(top_position)
 4861                } else if y_flipped && wanted.height < available.top {
 4862                    Some(top_position)
 4863                } else if y_flipped && wanted.height < available.bottom {
 4864                    Some(bottom_position)
 4865                } else {
 4866                    None
 4867                }
 4868            };
 4869
 4870            // Prefer choosing a direction using max sizes rather than actual size for stability.
 4871            let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
 4872            let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
 4873            let aside_position = fit_within(available_within_text, wanted)
 4874                // Fallback: fit max size in window.
 4875                .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
 4876                // Fallback: fit actual size in window.
 4877                .or_else(|| fit_within(available_within_viewport, actual_size));
 4878
 4879            aside_position.map(|position| (aside, position, actual_size))
 4880        };
 4881
 4882        // Skip drawing if it doesn't fit anywhere.
 4883        if let Some((aside, position, size)) = positioned_aside {
 4884            let aside_bounds = Bounds::new(position, size);
 4885            window.defer_draw(aside, position, 2);
 4886            return Some(aside_bounds);
 4887        }
 4888
 4889        None
 4890    }
 4891
 4892    fn render_context_menu(
 4893        &self,
 4894        line_height: Pixels,
 4895        height: Pixels,
 4896        window: &mut Window,
 4897        cx: &mut App,
 4898    ) -> Option<AnyElement> {
 4899        let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
 4900        self.editor.update(cx, |editor, cx| {
 4901            editor.render_context_menu(&self.style, max_height_in_lines, window, cx)
 4902        })
 4903    }
 4904
 4905    fn render_context_menu_aside(
 4906        &self,
 4907        max_size: Size<Pixels>,
 4908        window: &mut Window,
 4909        cx: &mut App,
 4910    ) -> Option<AnyElement> {
 4911        if max_size.width < px(100.) || max_size.height < px(12.) {
 4912            None
 4913        } else {
 4914            self.editor.update(cx, |editor, cx| {
 4915                editor.render_context_menu_aside(max_size, window, cx)
 4916            })
 4917        }
 4918    }
 4919
 4920    fn layout_mouse_context_menu(
 4921        &self,
 4922        editor_snapshot: &EditorSnapshot,
 4923        visible_range: Range<DisplayRow>,
 4924        content_origin: gpui::Point<Pixels>,
 4925        window: &mut Window,
 4926        cx: &mut App,
 4927    ) -> Option<AnyElement> {
 4928        let position = self.editor.update(cx, |editor, _cx| {
 4929            let visible_start_point = editor.display_to_pixel_point(
 4930                DisplayPoint::new(visible_range.start, 0),
 4931                editor_snapshot,
 4932                window,
 4933            )?;
 4934            let visible_end_point = editor.display_to_pixel_point(
 4935                DisplayPoint::new(visible_range.end, 0),
 4936                editor_snapshot,
 4937                window,
 4938            )?;
 4939
 4940            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
 4941            let (source_display_point, position) = match mouse_context_menu.position {
 4942                MenuPosition::PinnedToScreen(point) => (None, point),
 4943                MenuPosition::PinnedToEditor { source, offset } => {
 4944                    let source_display_point = source.to_display_point(editor_snapshot);
 4945                    let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
 4946                    let position = content_origin + source_point + offset;
 4947                    (Some(source_display_point), position)
 4948                }
 4949            };
 4950
 4951            let source_included = source_display_point.is_none_or(|source_display_point| {
 4952                visible_range
 4953                    .to_inclusive()
 4954                    .contains(&source_display_point.row())
 4955            });
 4956            let position_included =
 4957                visible_start_point.y <= position.y && position.y <= visible_end_point.y;
 4958            if !source_included && !position_included {
 4959                None
 4960            } else {
 4961                Some(position)
 4962            }
 4963        })?;
 4964
 4965        let text_style = TextStyleRefinement {
 4966            line_height: Some(DefiniteLength::Fraction(
 4967                BufferLineHeight::Comfortable.value(),
 4968            )),
 4969            ..Default::default()
 4970        };
 4971        window.with_text_style(Some(text_style), |window| {
 4972            let mut element = self.editor.read_with(cx, |editor, _| {
 4973                let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
 4974                let context_menu = mouse_context_menu.context_menu.clone();
 4975
 4976                Some(
 4977                    deferred(
 4978                        anchored()
 4979                            .position(position)
 4980                            .child(context_menu)
 4981                            .anchor(Corner::TopLeft)
 4982                            .snap_to_window_with_margin(px(8.)),
 4983                    )
 4984                    .with_priority(1)
 4985                    .into_any(),
 4986                )
 4987            })?;
 4988
 4989            element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
 4990            Some(element)
 4991        })
 4992    }
 4993
 4994    fn layout_hover_popovers(
 4995        &self,
 4996        snapshot: &EditorSnapshot,
 4997        hitbox: &Hitbox,
 4998        visible_display_row_range: Range<DisplayRow>,
 4999        content_origin: gpui::Point<Pixels>,
 5000        scroll_pixel_position: gpui::Point<Pixels>,
 5001        line_layouts: &[LineWithInvisibles],
 5002        line_height: Pixels,
 5003        em_width: Pixels,
 5004        context_menu_layout: Option<ContextMenuLayout>,
 5005        window: &mut Window,
 5006        cx: &mut App,
 5007    ) {
 5008        struct MeasuredHoverPopover {
 5009            element: AnyElement,
 5010            size: Size<Pixels>,
 5011            horizontal_offset: Pixels,
 5012        }
 5013
 5014        let max_size = size(
 5015            (120. * em_width) // Default size
 5016                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
 5017                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
 5018            (16. * line_height) // Default size
 5019                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
 5020                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
 5021        );
 5022
 5023        let hover_popovers = self.editor.update(cx, |editor, cx| {
 5024            editor.hover_state.render(
 5025                snapshot,
 5026                visible_display_row_range.clone(),
 5027                max_size,
 5028                window,
 5029                cx,
 5030            )
 5031        });
 5032        let Some((position, hover_popovers)) = hover_popovers else {
 5033            return;
 5034        };
 5035
 5036        // This is safe because we check on layout whether the required row is available
 5037        let hovered_row_layout =
 5038            &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
 5039
 5040        // Compute Hovered Point
 5041        let x =
 5042            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
 5043        let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
 5044        let hovered_point = content_origin + point(x, y);
 5045
 5046        let mut overall_height = Pixels::ZERO;
 5047        let mut measured_hover_popovers = Vec::new();
 5048        for (position, mut hover_popover) in hover_popovers.into_iter().with_position() {
 5049            let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
 5050            let horizontal_offset =
 5051                (hitbox.top_right().x - POPOVER_RIGHT_OFFSET - (hovered_point.x + size.width))
 5052                    .min(Pixels::ZERO);
 5053            match position {
 5054                itertools::Position::Middle | itertools::Position::Last => {
 5055                    overall_height += HOVER_POPOVER_GAP
 5056                }
 5057                _ => {}
 5058            }
 5059            overall_height += size.height;
 5060            measured_hover_popovers.push(MeasuredHoverPopover {
 5061                element: hover_popover,
 5062                size,
 5063                horizontal_offset,
 5064            });
 5065        }
 5066
 5067        fn draw_occluder(
 5068            width: Pixels,
 5069            origin: gpui::Point<Pixels>,
 5070            window: &mut Window,
 5071            cx: &mut App,
 5072        ) {
 5073            let mut occlusion = div()
 5074                .size_full()
 5075                .occlude()
 5076                .on_mouse_move(|_, _, cx| cx.stop_propagation())
 5077                .into_any_element();
 5078            occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
 5079            window.defer_draw(occlusion, origin, 2);
 5080        }
 5081
 5082        fn place_popovers_above(
 5083            hovered_point: gpui::Point<Pixels>,
 5084            measured_hover_popovers: Vec<MeasuredHoverPopover>,
 5085            window: &mut Window,
 5086            cx: &mut App,
 5087        ) {
 5088            let mut current_y = hovered_point.y;
 5089            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 5090                let size = popover.size;
 5091                let popover_origin = point(
 5092                    hovered_point.x + popover.horizontal_offset,
 5093                    current_y - size.height,
 5094                );
 5095
 5096                window.defer_draw(popover.element, popover_origin, 2);
 5097                if position != itertools::Position::Last {
 5098                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
 5099                    draw_occluder(size.width, origin, window, cx);
 5100                }
 5101
 5102                current_y = popover_origin.y - HOVER_POPOVER_GAP;
 5103            }
 5104        }
 5105
 5106        fn place_popovers_below(
 5107            hovered_point: gpui::Point<Pixels>,
 5108            measured_hover_popovers: Vec<MeasuredHoverPopover>,
 5109            line_height: Pixels,
 5110            window: &mut Window,
 5111            cx: &mut App,
 5112        ) {
 5113            let mut current_y = hovered_point.y + line_height;
 5114            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 5115                let size = popover.size;
 5116                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
 5117
 5118                window.defer_draw(popover.element, popover_origin, 2);
 5119                if position != itertools::Position::Last {
 5120                    let origin = point(popover_origin.x, popover_origin.y + size.height);
 5121                    draw_occluder(size.width, origin, window, cx);
 5122                }
 5123
 5124                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 5125            }
 5126        }
 5127
 5128        let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
 5129            context_menu_layout
 5130                .as_ref()
 5131                .is_some_and(|menu| bounds.intersects(&menu.bounds))
 5132        };
 5133
 5134        let can_place_above = {
 5135            let mut bounds_above = Vec::new();
 5136            let mut current_y = hovered_point.y;
 5137            for popover in &measured_hover_popovers {
 5138                let size = popover.size;
 5139                let popover_origin = point(
 5140                    hovered_point.x + popover.horizontal_offset,
 5141                    current_y - size.height,
 5142                );
 5143                bounds_above.push(Bounds::new(popover_origin, size));
 5144                current_y = popover_origin.y - HOVER_POPOVER_GAP;
 5145            }
 5146            bounds_above
 5147                .iter()
 5148                .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
 5149        };
 5150
 5151        let can_place_below = || {
 5152            let mut bounds_below = Vec::new();
 5153            let mut current_y = hovered_point.y + line_height;
 5154            for popover in &measured_hover_popovers {
 5155                let size = popover.size;
 5156                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
 5157                bounds_below.push(Bounds::new(popover_origin, size));
 5158                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 5159            }
 5160            bounds_below
 5161                .iter()
 5162                .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
 5163        };
 5164
 5165        if can_place_above {
 5166            // try placing above hovered point
 5167            place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
 5168        } else if can_place_below() {
 5169            // try placing below hovered point
 5170            place_popovers_below(
 5171                hovered_point,
 5172                measured_hover_popovers,
 5173                line_height,
 5174                window,
 5175                cx,
 5176            );
 5177        } else {
 5178            // try to place popovers around the context menu
 5179            let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
 5180                let total_width = measured_hover_popovers
 5181                    .iter()
 5182                    .map(|p| p.size.width)
 5183                    .max()
 5184                    .unwrap_or(Pixels::ZERO);
 5185                let y_for_horizontal_positioning = if menu.y_flipped {
 5186                    menu.bounds.bottom() - overall_height
 5187                } else {
 5188                    menu.bounds.top()
 5189                };
 5190                let possible_origins = vec![
 5191                    // left of context menu
 5192                    point(
 5193                        menu.bounds.left() - total_width - HOVER_POPOVER_GAP,
 5194                        y_for_horizontal_positioning,
 5195                    ),
 5196                    // right of context menu
 5197                    point(
 5198                        menu.bounds.right() + HOVER_POPOVER_GAP,
 5199                        y_for_horizontal_positioning,
 5200                    ),
 5201                    // top of context menu
 5202                    point(
 5203                        menu.bounds.left(),
 5204                        menu.bounds.top() - overall_height - HOVER_POPOVER_GAP,
 5205                    ),
 5206                    // bottom of context menu
 5207                    point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
 5208                ];
 5209                possible_origins.into_iter().find(|&origin| {
 5210                    Bounds::new(origin, size(total_width, overall_height))
 5211                        .is_contained_within(hitbox)
 5212                })
 5213            });
 5214            if let Some(origin) = origin_surrounding_menu {
 5215                let mut current_y = origin.y;
 5216                for (position, popover) in measured_hover_popovers.into_iter().with_position() {
 5217                    let size = popover.size;
 5218                    let popover_origin = point(origin.x, current_y);
 5219
 5220                    window.defer_draw(popover.element, popover_origin, 2);
 5221                    if position != itertools::Position::Last {
 5222                        let origin = point(popover_origin.x, popover_origin.y + size.height);
 5223                        draw_occluder(size.width, origin, window, cx);
 5224                    }
 5225
 5226                    current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
 5227                }
 5228            } else {
 5229                // fallback to existing above/below cursor logic
 5230                // this might overlap menu or overflow in rare case
 5231                if can_place_above {
 5232                    place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
 5233                } else {
 5234                    place_popovers_below(
 5235                        hovered_point,
 5236                        measured_hover_popovers,
 5237                        line_height,
 5238                        window,
 5239                        cx,
 5240                    );
 5241                }
 5242            }
 5243        }
 5244    }
 5245
 5246    fn layout_diff_hunk_controls(
 5247        &self,
 5248        row_range: Range<DisplayRow>,
 5249        row_infos: &[RowInfo],
 5250        text_hitbox: &Hitbox,
 5251        newest_cursor_position: Option<DisplayPoint>,
 5252        line_height: Pixels,
 5253        right_margin: Pixels,
 5254        scroll_pixel_position: gpui::Point<Pixels>,
 5255        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 5256        highlighted_rows: &BTreeMap<DisplayRow, LineHighlight>,
 5257        editor: Entity<Editor>,
 5258        window: &mut Window,
 5259        cx: &mut App,
 5260    ) -> (Vec<AnyElement>, Vec<(DisplayRow, Bounds<Pixels>)>) {
 5261        let render_diff_hunk_controls = editor.read(cx).render_diff_hunk_controls.clone();
 5262        let hovered_diff_hunk_row = editor.read(cx).hovered_diff_hunk_row;
 5263
 5264        let mut controls = vec![];
 5265        let mut control_bounds = vec![];
 5266
 5267        let active_positions = [
 5268            hovered_diff_hunk_row.map(|row| DisplayPoint::new(row, 0)),
 5269            newest_cursor_position,
 5270        ];
 5271
 5272        for (hunk, _) in display_hunks {
 5273            if let DisplayDiffHunk::Unfolded {
 5274                display_row_range,
 5275                multi_buffer_range,
 5276                status,
 5277                is_created_file,
 5278                ..
 5279            } = &hunk
 5280            {
 5281                if display_row_range.start < row_range.start
 5282                    || display_row_range.start >= row_range.end
 5283                {
 5284                    continue;
 5285                }
 5286                if highlighted_rows
 5287                    .get(&display_row_range.start)
 5288                    .and_then(|highlight| highlight.type_id)
 5289                    .is_some_and(|type_id| {
 5290                        [
 5291                            TypeId::of::<ConflictsOuter>(),
 5292                            TypeId::of::<ConflictsOursMarker>(),
 5293                            TypeId::of::<ConflictsOurs>(),
 5294                            TypeId::of::<ConflictsTheirs>(),
 5295                            TypeId::of::<ConflictsTheirsMarker>(),
 5296                        ]
 5297                        .contains(&type_id)
 5298                    })
 5299                {
 5300                    continue;
 5301                }
 5302                let row_ix = (display_row_range.start - row_range.start).0 as usize;
 5303                if row_infos[row_ix].diff_status.is_none() {
 5304                    continue;
 5305                }
 5306                if row_infos[row_ix]
 5307                    .diff_status
 5308                    .is_some_and(|status| status.is_added())
 5309                    && !status.is_added()
 5310                {
 5311                    continue;
 5312                }
 5313
 5314                if active_positions
 5315                    .iter()
 5316                    .any(|p| p.is_some_and(|p| display_row_range.contains(&p.row())))
 5317                {
 5318                    let y = display_row_range.start.as_f32() * line_height
 5319                        + text_hitbox.bounds.top()
 5320                        - scroll_pixel_position.y;
 5321
 5322                    let mut element = render_diff_hunk_controls(
 5323                        display_row_range.start.0,
 5324                        status,
 5325                        multi_buffer_range.clone(),
 5326                        *is_created_file,
 5327                        line_height,
 5328                        &editor,
 5329                        window,
 5330                        cx,
 5331                    );
 5332                    let size =
 5333                        element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
 5334
 5335                    let x = text_hitbox.bounds.right() - right_margin - px(10.) - size.width;
 5336
 5337                    let bounds = Bounds::new(gpui::Point::new(x, y), size);
 5338                    control_bounds.push((display_row_range.start, bounds));
 5339
 5340                    window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
 5341                        element.prepaint(window, cx)
 5342                    });
 5343                    controls.push(element);
 5344                }
 5345            }
 5346        }
 5347
 5348        (controls, control_bounds)
 5349    }
 5350
 5351    fn layout_signature_help(
 5352        &self,
 5353        hitbox: &Hitbox,
 5354        content_origin: gpui::Point<Pixels>,
 5355        scroll_pixel_position: gpui::Point<Pixels>,
 5356        newest_selection_head: Option<DisplayPoint>,
 5357        start_row: DisplayRow,
 5358        line_layouts: &[LineWithInvisibles],
 5359        line_height: Pixels,
 5360        em_width: Pixels,
 5361        context_menu_layout: Option<ContextMenuLayout>,
 5362        window: &mut Window,
 5363        cx: &mut App,
 5364    ) {
 5365        if !self.editor.focus_handle(cx).is_focused(window) {
 5366            return;
 5367        }
 5368        let Some(newest_selection_head) = newest_selection_head else {
 5369            return;
 5370        };
 5371
 5372        let max_size = size(
 5373            (120. * em_width) // Default size
 5374                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
 5375                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
 5376            (16. * line_height) // Default size
 5377                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
 5378                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
 5379        );
 5380
 5381        let maybe_element = self.editor.update(cx, |editor, cx| {
 5382            if let Some(popover) = editor.signature_help_state.popover_mut() {
 5383                let element = popover.render(max_size, window, cx);
 5384                Some(element)
 5385            } else {
 5386                None
 5387            }
 5388        });
 5389        let Some(mut element) = maybe_element else {
 5390            return;
 5391        };
 5392
 5393        let selection_row = newest_selection_head.row();
 5394        let Some(cursor_row_layout) = (selection_row >= start_row)
 5395            .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
 5396            .flatten()
 5397        else {
 5398            return;
 5399        };
 5400
 5401        let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
 5402            - scroll_pixel_position.x;
 5403        let target_y = selection_row.as_f32() * line_height - scroll_pixel_position.y;
 5404        let target_point = content_origin + point(target_x, target_y);
 5405
 5406        let actual_size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
 5407
 5408        let (popover_bounds_above, popover_bounds_below) = {
 5409            let horizontal_offset = (hitbox.top_right().x
 5410                - POPOVER_RIGHT_OFFSET
 5411                - (target_point.x + actual_size.width))
 5412                .min(Pixels::ZERO);
 5413            let initial_x = target_point.x + horizontal_offset;
 5414            (
 5415                Bounds::new(
 5416                    point(initial_x, target_point.y - actual_size.height),
 5417                    actual_size,
 5418                ),
 5419                Bounds::new(
 5420                    point(initial_x, target_point.y + line_height + HOVER_POPOVER_GAP),
 5421                    actual_size,
 5422                ),
 5423            )
 5424        };
 5425
 5426        let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
 5427            context_menu_layout
 5428                .as_ref()
 5429                .is_some_and(|menu| bounds.intersects(&menu.bounds))
 5430        };
 5431
 5432        let final_origin = if popover_bounds_above.is_contained_within(hitbox)
 5433            && !intersects_menu(popover_bounds_above)
 5434        {
 5435            // try placing above cursor
 5436            popover_bounds_above.origin
 5437        } else if popover_bounds_below.is_contained_within(hitbox)
 5438            && !intersects_menu(popover_bounds_below)
 5439        {
 5440            // try placing below cursor
 5441            popover_bounds_below.origin
 5442        } else {
 5443            // try surrounding context menu if exists
 5444            let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
 5445                let y_for_horizontal_positioning = if menu.y_flipped {
 5446                    menu.bounds.bottom() - actual_size.height
 5447                } else {
 5448                    menu.bounds.top()
 5449                };
 5450                let possible_origins = vec![
 5451                    // left of context menu
 5452                    point(
 5453                        menu.bounds.left() - actual_size.width - HOVER_POPOVER_GAP,
 5454                        y_for_horizontal_positioning,
 5455                    ),
 5456                    // right of context menu
 5457                    point(
 5458                        menu.bounds.right() + HOVER_POPOVER_GAP,
 5459                        y_for_horizontal_positioning,
 5460                    ),
 5461                    // top of context menu
 5462                    point(
 5463                        menu.bounds.left(),
 5464                        menu.bounds.top() - actual_size.height - HOVER_POPOVER_GAP,
 5465                    ),
 5466                    // bottom of context menu
 5467                    point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
 5468                ];
 5469                possible_origins
 5470                    .into_iter()
 5471                    .find(|&origin| Bounds::new(origin, actual_size).is_contained_within(hitbox))
 5472            });
 5473            origin_surrounding_menu.unwrap_or_else(|| {
 5474                // fallback to existing above/below cursor logic
 5475                // this might overlap menu or overflow in rare case
 5476                if popover_bounds_above.is_contained_within(hitbox) {
 5477                    popover_bounds_above.origin
 5478                } else {
 5479                    popover_bounds_below.origin
 5480                }
 5481            })
 5482        };
 5483
 5484        window.defer_draw(element, final_origin, 2);
 5485    }
 5486
 5487    fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
 5488        window.paint_layer(layout.hitbox.bounds, |window| {
 5489            let scroll_top = layout.position_map.snapshot.scroll_position().y;
 5490            let gutter_bg = cx.theme().colors().editor_gutter_background;
 5491            window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
 5492            window.paint_quad(fill(
 5493                layout.position_map.text_hitbox.bounds,
 5494                self.style.background,
 5495            ));
 5496
 5497            if matches!(
 5498                layout.mode,
 5499                EditorMode::Full { .. } | EditorMode::Minimap { .. }
 5500            ) {
 5501                let show_active_line_background = match layout.mode {
 5502                    EditorMode::Full {
 5503                        show_active_line_background,
 5504                        ..
 5505                    } => show_active_line_background,
 5506                    EditorMode::Minimap { .. } => true,
 5507                    _ => false,
 5508                };
 5509                let mut active_rows = layout.active_rows.iter().peekable();
 5510                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
 5511                    let mut end_row = start_row.0;
 5512                    while active_rows
 5513                        .peek()
 5514                        .is_some_and(|(active_row, has_selection)| {
 5515                            active_row.0 == end_row + 1
 5516                                && has_selection.selection == contains_non_empty_selection.selection
 5517                        })
 5518                    {
 5519                        active_rows.next().unwrap();
 5520                        end_row += 1;
 5521                    }
 5522
 5523                    if show_active_line_background && !contains_non_empty_selection.selection {
 5524                        let highlight_h_range =
 5525                            match layout.position_map.snapshot.current_line_highlight {
 5526                                CurrentLineHighlight::Gutter => Some(Range {
 5527                                    start: layout.hitbox.left(),
 5528                                    end: layout.gutter_hitbox.right(),
 5529                                }),
 5530                                CurrentLineHighlight::Line => Some(Range {
 5531                                    start: layout.position_map.text_hitbox.bounds.left(),
 5532                                    end: layout.position_map.text_hitbox.bounds.right(),
 5533                                }),
 5534                                CurrentLineHighlight::All => Some(Range {
 5535                                    start: layout.hitbox.left(),
 5536                                    end: layout.hitbox.right(),
 5537                                }),
 5538                                CurrentLineHighlight::None => None,
 5539                            };
 5540                        if let Some(range) = highlight_h_range {
 5541                            let active_line_bg = cx.theme().colors().editor_active_line_background;
 5542                            let bounds = Bounds {
 5543                                origin: point(
 5544                                    range.start,
 5545                                    layout.hitbox.origin.y
 5546                                        + (start_row.as_f32() - scroll_top)
 5547                                            * layout.position_map.line_height,
 5548                                ),
 5549                                size: size(
 5550                                    range.end - range.start,
 5551                                    layout.position_map.line_height
 5552                                        * (end_row - start_row.0 + 1) as f32,
 5553                                ),
 5554                            };
 5555                            window.paint_quad(fill(bounds, active_line_bg));
 5556                        }
 5557                    }
 5558                }
 5559
 5560                let mut paint_highlight = |highlight_row_start: DisplayRow,
 5561                                           highlight_row_end: DisplayRow,
 5562                                           highlight: crate::LineHighlight,
 5563                                           edges| {
 5564                    let mut origin_x = layout.hitbox.left();
 5565                    let mut width = layout.hitbox.size.width;
 5566                    if !highlight.include_gutter {
 5567                        origin_x += layout.gutter_hitbox.size.width;
 5568                        width -= layout.gutter_hitbox.size.width;
 5569                    }
 5570
 5571                    let origin = point(
 5572                        origin_x,
 5573                        layout.hitbox.origin.y
 5574                            + (highlight_row_start.as_f32() - scroll_top)
 5575                                * layout.position_map.line_height,
 5576                    );
 5577                    let size = size(
 5578                        width,
 5579                        layout.position_map.line_height
 5580                            * highlight_row_end.next_row().minus(highlight_row_start) as f32,
 5581                    );
 5582                    let mut quad = fill(Bounds { origin, size }, highlight.background);
 5583                    if let Some(border_color) = highlight.border {
 5584                        quad.border_color = border_color;
 5585                        quad.border_widths = edges
 5586                    }
 5587                    window.paint_quad(quad);
 5588                };
 5589
 5590                let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
 5591                    None;
 5592                for (&new_row, &new_background) in &layout.highlighted_rows {
 5593                    match &mut current_paint {
 5594                        &mut Some((current_background, ref mut current_range, mut edges)) => {
 5595                            let new_range_started = current_background != new_background
 5596                                || current_range.end.next_row() != new_row;
 5597                            if new_range_started {
 5598                                if current_range.end.next_row() == new_row {
 5599                                    edges.bottom = px(0.);
 5600                                };
 5601                                paint_highlight(
 5602                                    current_range.start,
 5603                                    current_range.end,
 5604                                    current_background,
 5605                                    edges,
 5606                                );
 5607                                let edges = Edges {
 5608                                    top: if current_range.end.next_row() != new_row {
 5609                                        px(1.)
 5610                                    } else {
 5611                                        px(0.)
 5612                                    },
 5613                                    bottom: px(1.),
 5614                                    ..Default::default()
 5615                                };
 5616                                current_paint = Some((new_background, new_row..new_row, edges));
 5617                                continue;
 5618                            } else {
 5619                                current_range.end = current_range.end.next_row();
 5620                            }
 5621                        }
 5622                        None => {
 5623                            let edges = Edges {
 5624                                top: px(1.),
 5625                                bottom: px(1.),
 5626                                ..Default::default()
 5627                            };
 5628                            current_paint = Some((new_background, new_row..new_row, edges))
 5629                        }
 5630                    };
 5631                }
 5632                if let Some((color, range, edges)) = current_paint {
 5633                    paint_highlight(range.start, range.end, color, edges);
 5634                }
 5635
 5636                for (guide_x, active) in layout.wrap_guides.iter() {
 5637                    let color = if *active {
 5638                        cx.theme().colors().editor_active_wrap_guide
 5639                    } else {
 5640                        cx.theme().colors().editor_wrap_guide
 5641                    };
 5642                    window.paint_quad(fill(
 5643                        Bounds {
 5644                            origin: point(*guide_x, layout.position_map.text_hitbox.origin.y),
 5645                            size: size(px(1.), layout.position_map.text_hitbox.size.height),
 5646                        },
 5647                        color,
 5648                    ));
 5649                }
 5650            }
 5651        })
 5652    }
 5653
 5654    fn paint_indent_guides(
 5655        &mut self,
 5656        layout: &mut EditorLayout,
 5657        window: &mut Window,
 5658        cx: &mut App,
 5659    ) {
 5660        let Some(indent_guides) = &layout.indent_guides else {
 5661            return;
 5662        };
 5663
 5664        let faded_color = |color: Hsla, alpha: f32| {
 5665            let mut faded = color;
 5666            faded.a = alpha;
 5667            faded
 5668        };
 5669
 5670        for indent_guide in indent_guides {
 5671            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
 5672            let settings = indent_guide.settings;
 5673
 5674            // TODO fixed for now, expose them through themes later
 5675            const INDENT_AWARE_ALPHA: f32 = 0.2;
 5676            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
 5677            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
 5678            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
 5679
 5680            let line_color = match (settings.coloring, indent_guide.active) {
 5681                (IndentGuideColoring::Disabled, _) => None,
 5682                (IndentGuideColoring::Fixed, false) => {
 5683                    Some(cx.theme().colors().editor_indent_guide)
 5684                }
 5685                (IndentGuideColoring::Fixed, true) => {
 5686                    Some(cx.theme().colors().editor_indent_guide_active)
 5687                }
 5688                (IndentGuideColoring::IndentAware, false) => {
 5689                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
 5690                }
 5691                (IndentGuideColoring::IndentAware, true) => {
 5692                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
 5693                }
 5694            };
 5695
 5696            let background_color = match (settings.background_coloring, indent_guide.active) {
 5697                (IndentGuideBackgroundColoring::Disabled, _) => None,
 5698                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
 5699                    indent_accent_colors,
 5700                    INDENT_AWARE_BACKGROUND_ALPHA,
 5701                )),
 5702                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
 5703                    indent_accent_colors,
 5704                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
 5705                )),
 5706            };
 5707
 5708            let requested_line_width = if indent_guide.active {
 5709                settings.active_line_width
 5710            } else {
 5711                settings.line_width
 5712            }
 5713            .clamp(1, 10);
 5714            let mut line_indicator_width = 0.;
 5715            if let Some(color) = line_color {
 5716                window.paint_quad(fill(
 5717                    Bounds {
 5718                        origin: indent_guide.origin,
 5719                        size: size(px(requested_line_width as f32), indent_guide.length),
 5720                    },
 5721                    color,
 5722                ));
 5723                line_indicator_width = requested_line_width as f32;
 5724            }
 5725
 5726            if let Some(color) = background_color {
 5727                let width = indent_guide.single_indent_width - px(line_indicator_width);
 5728                window.paint_quad(fill(
 5729                    Bounds {
 5730                        origin: point(
 5731                            indent_guide.origin.x + px(line_indicator_width),
 5732                            indent_guide.origin.y,
 5733                        ),
 5734                        size: size(width, indent_guide.length),
 5735                    },
 5736                    color,
 5737                ));
 5738            }
 5739        }
 5740    }
 5741
 5742    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 5743        let is_singleton = self.editor.read(cx).is_singleton(cx);
 5744
 5745        let line_height = layout.position_map.line_height;
 5746        window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
 5747
 5748        for LineNumberLayout {
 5749            shaped_line,
 5750            hitbox,
 5751        } in layout.line_numbers.values()
 5752        {
 5753            let Some(hitbox) = hitbox else {
 5754                continue;
 5755            };
 5756
 5757            let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
 5758                let color = cx.theme().colors().editor_hover_line_number;
 5759
 5760                let line = self.shape_line_number(shaped_line.text.clone(), color, window);
 5761                line.paint(hitbox.origin, line_height, window, cx).log_err()
 5762            } else {
 5763                shaped_line
 5764                    .paint(hitbox.origin, line_height, window, cx)
 5765                    .log_err()
 5766            }) else {
 5767                continue;
 5768            };
 5769
 5770            // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
 5771            // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
 5772            if is_singleton {
 5773                window.set_cursor_style(CursorStyle::IBeam, hitbox);
 5774            } else {
 5775                window.set_cursor_style(CursorStyle::PointingHand, hitbox);
 5776            }
 5777        }
 5778    }
 5779
 5780    fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 5781        if layout.display_hunks.is_empty() {
 5782            return;
 5783        }
 5784
 5785        let line_height = layout.position_map.line_height;
 5786        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 5787            for (hunk, hitbox) in &layout.display_hunks {
 5788                let hunk_to_paint = match hunk {
 5789                    DisplayDiffHunk::Folded { .. } => {
 5790                        let hunk_bounds = Self::diff_hunk_bounds(
 5791                            &layout.position_map.snapshot,
 5792                            line_height,
 5793                            layout.gutter_hitbox.bounds,
 5794                            hunk,
 5795                        );
 5796                        Some((
 5797                            hunk_bounds,
 5798                            cx.theme().colors().version_control_modified,
 5799                            Corners::all(px(0.)),
 5800                            DiffHunkStatus::modified_none(),
 5801                        ))
 5802                    }
 5803                    DisplayDiffHunk::Unfolded {
 5804                        status,
 5805                        display_row_range,
 5806                        ..
 5807                    } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
 5808                        DiffHunkStatusKind::Added => (
 5809                            hunk_hitbox.bounds,
 5810                            cx.theme().colors().version_control_added,
 5811                            Corners::all(px(0.)),
 5812                            *status,
 5813                        ),
 5814                        DiffHunkStatusKind::Modified => (
 5815                            hunk_hitbox.bounds,
 5816                            cx.theme().colors().version_control_modified,
 5817                            Corners::all(px(0.)),
 5818                            *status,
 5819                        ),
 5820                        DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
 5821                            hunk_hitbox.bounds,
 5822                            cx.theme().colors().version_control_deleted,
 5823                            Corners::all(px(0.)),
 5824                            *status,
 5825                        ),
 5826                        DiffHunkStatusKind::Deleted => (
 5827                            Bounds::new(
 5828                                point(
 5829                                    hunk_hitbox.origin.x - hunk_hitbox.size.width,
 5830                                    hunk_hitbox.origin.y,
 5831                                ),
 5832                                size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
 5833                            ),
 5834                            cx.theme().colors().version_control_deleted,
 5835                            Corners::all(1. * line_height),
 5836                            *status,
 5837                        ),
 5838                    }),
 5839                };
 5840
 5841                if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
 5842                    // Flatten the background color with the editor color to prevent
 5843                    // elements below transparent hunks from showing through
 5844                    let flattened_background_color = cx
 5845                        .theme()
 5846                        .colors()
 5847                        .editor_background
 5848                        .blend(background_color);
 5849
 5850                    if !Self::diff_hunk_hollow(status, cx) {
 5851                        window.paint_quad(quad(
 5852                            hunk_bounds,
 5853                            corner_radii,
 5854                            flattened_background_color,
 5855                            Edges::default(),
 5856                            transparent_black(),
 5857                            BorderStyle::default(),
 5858                        ));
 5859                    } else {
 5860                        let flattened_unstaged_background_color = cx
 5861                            .theme()
 5862                            .colors()
 5863                            .editor_background
 5864                            .blend(background_color.opacity(0.3));
 5865
 5866                        window.paint_quad(quad(
 5867                            hunk_bounds,
 5868                            corner_radii,
 5869                            flattened_unstaged_background_color,
 5870                            Edges::all(Pixels(1.0)),
 5871                            flattened_background_color,
 5872                            BorderStyle::Solid,
 5873                        ));
 5874                    }
 5875                }
 5876            }
 5877        });
 5878    }
 5879
 5880    fn gutter_strip_width(line_height: Pixels) -> Pixels {
 5881        (0.275 * line_height).floor()
 5882    }
 5883
 5884    fn diff_hunk_bounds(
 5885        snapshot: &EditorSnapshot,
 5886        line_height: Pixels,
 5887        gutter_bounds: Bounds<Pixels>,
 5888        hunk: &DisplayDiffHunk,
 5889    ) -> Bounds<Pixels> {
 5890        let scroll_position = snapshot.scroll_position();
 5891        let scroll_top = scroll_position.y * line_height;
 5892        let gutter_strip_width = Self::gutter_strip_width(line_height);
 5893
 5894        match hunk {
 5895            DisplayDiffHunk::Folded { display_row, .. } => {
 5896                let start_y = display_row.as_f32() * line_height - scroll_top;
 5897                let end_y = start_y + line_height;
 5898                let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 5899                let highlight_size = size(gutter_strip_width, end_y - start_y);
 5900                Bounds::new(highlight_origin, highlight_size)
 5901            }
 5902            DisplayDiffHunk::Unfolded {
 5903                display_row_range,
 5904                status,
 5905                ..
 5906            } => {
 5907                if status.is_deleted() && display_row_range.is_empty() {
 5908                    let row = display_row_range.start;
 5909
 5910                    let offset = line_height / 2.;
 5911                    let start_y = row.as_f32() * line_height - offset - scroll_top;
 5912                    let end_y = start_y + line_height;
 5913
 5914                    let width = (0.35 * line_height).floor();
 5915                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 5916                    let highlight_size = size(width, end_y - start_y);
 5917                    Bounds::new(highlight_origin, highlight_size)
 5918                } else {
 5919                    let start_row = display_row_range.start;
 5920                    let end_row = display_row_range.end;
 5921                    // If we're in a multibuffer, row range span might include an
 5922                    // excerpt header, so if we were to draw the marker straight away,
 5923                    // the hunk might include the rows of that header.
 5924                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
 5925                    // Instead, we simply check whether the range we're dealing with includes
 5926                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
 5927                    let end_row_in_current_excerpt = snapshot
 5928                        .blocks_in_range(start_row..end_row)
 5929                        .find_map(|(start_row, block)| {
 5930                            if matches!(
 5931                                block,
 5932                                Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
 5933                            ) {
 5934                                Some(start_row)
 5935                            } else {
 5936                                None
 5937                            }
 5938                        })
 5939                        .unwrap_or(end_row);
 5940
 5941                    let start_y = start_row.as_f32() * line_height - scroll_top;
 5942                    let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
 5943
 5944                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 5945                    let highlight_size = size(gutter_strip_width, end_y - start_y);
 5946                    Bounds::new(highlight_origin, highlight_size)
 5947                }
 5948            }
 5949        }
 5950    }
 5951
 5952    fn paint_gutter_indicators(
 5953        &self,
 5954        layout: &mut EditorLayout,
 5955        window: &mut Window,
 5956        cx: &mut App,
 5957    ) {
 5958        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 5959            window.with_element_namespace("crease_toggles", |window| {
 5960                for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
 5961                    crease_toggle.paint(window, cx);
 5962                }
 5963            });
 5964
 5965            window.with_element_namespace("expand_toggles", |window| {
 5966                for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
 5967                    expand_toggle.paint(window, cx);
 5968                }
 5969            });
 5970
 5971            for breakpoint in layout.breakpoints.iter_mut() {
 5972                breakpoint.paint(window, cx);
 5973            }
 5974
 5975            for test_indicator in layout.test_indicators.iter_mut() {
 5976                test_indicator.paint(window, cx);
 5977            }
 5978        });
 5979    }
 5980
 5981    fn paint_gutter_highlights(
 5982        &self,
 5983        layout: &mut EditorLayout,
 5984        window: &mut Window,
 5985        cx: &mut App,
 5986    ) {
 5987        for (_, hunk_hitbox) in &layout.display_hunks {
 5988            if let Some(hunk_hitbox) = hunk_hitbox
 5989                && !self
 5990                    .editor
 5991                    .read(cx)
 5992                    .buffer()
 5993                    .read(cx)
 5994                    .all_diff_hunks_expanded()
 5995            {
 5996                window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
 5997            }
 5998        }
 5999
 6000        let show_git_gutter = layout
 6001            .position_map
 6002            .snapshot
 6003            .show_git_diff_gutter
 6004            .unwrap_or_else(|| {
 6005                matches!(
 6006                    ProjectSettings::get_global(cx).git.git_gutter,
 6007                    Some(GitGutterSetting::TrackedFiles)
 6008                )
 6009            });
 6010        if show_git_gutter {
 6011            Self::paint_gutter_diff_hunks(layout, window, cx)
 6012        }
 6013
 6014        let highlight_width = 0.275 * layout.position_map.line_height;
 6015        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
 6016        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6017            for (range, color) in &layout.highlighted_gutter_ranges {
 6018                let start_row = if range.start.row() < layout.visible_display_row_range.start {
 6019                    layout.visible_display_row_range.start - DisplayRow(1)
 6020                } else {
 6021                    range.start.row()
 6022                };
 6023                let end_row = if range.end.row() > layout.visible_display_row_range.end {
 6024                    layout.visible_display_row_range.end + DisplayRow(1)
 6025                } else {
 6026                    range.end.row()
 6027                };
 6028
 6029                let start_y = layout.gutter_hitbox.top()
 6030                    + start_row.0 as f32 * layout.position_map.line_height
 6031                    - layout.position_map.scroll_pixel_position.y;
 6032                let end_y = layout.gutter_hitbox.top()
 6033                    + (end_row.0 + 1) as f32 * layout.position_map.line_height
 6034                    - layout.position_map.scroll_pixel_position.y;
 6035                let bounds = Bounds::from_corners(
 6036                    point(layout.gutter_hitbox.left(), start_y),
 6037                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
 6038                );
 6039                window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
 6040            }
 6041        });
 6042    }
 6043
 6044    fn paint_blamed_display_rows(
 6045        &self,
 6046        layout: &mut EditorLayout,
 6047        window: &mut Window,
 6048        cx: &mut App,
 6049    ) {
 6050        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
 6051            return;
 6052        };
 6053
 6054        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6055            for mut blame_element in blamed_display_rows.into_iter() {
 6056                blame_element.paint(window, cx);
 6057            }
 6058        })
 6059    }
 6060
 6061    fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6062        window.with_content_mask(
 6063            Some(ContentMask {
 6064                bounds: layout.position_map.text_hitbox.bounds,
 6065            }),
 6066            |window| {
 6067                let editor = self.editor.read(cx);
 6068                if editor.mouse_cursor_hidden {
 6069                    window.set_window_cursor_style(CursorStyle::None);
 6070                } else if let SelectionDragState::ReadyToDrag {
 6071                    mouse_down_time, ..
 6072                } = &editor.selection_drag_state
 6073                {
 6074                    let drag_and_drop_delay = Duration::from_millis(
 6075                        EditorSettings::get_global(cx).drag_and_drop_selection.delay,
 6076                    );
 6077                    if mouse_down_time.elapsed() >= drag_and_drop_delay {
 6078                        window.set_cursor_style(
 6079                            CursorStyle::DragCopy,
 6080                            &layout.position_map.text_hitbox,
 6081                        );
 6082                    }
 6083                } else if matches!(
 6084                    editor.selection_drag_state,
 6085                    SelectionDragState::Dragging { .. }
 6086                ) {
 6087                    window
 6088                        .set_cursor_style(CursorStyle::DragCopy, &layout.position_map.text_hitbox);
 6089                } else if editor
 6090                    .hovered_link_state
 6091                    .as_ref()
 6092                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
 6093                {
 6094                    window.set_cursor_style(
 6095                        CursorStyle::PointingHand,
 6096                        &layout.position_map.text_hitbox,
 6097                    );
 6098                } else {
 6099                    window.set_cursor_style(CursorStyle::IBeam, &layout.position_map.text_hitbox);
 6100                };
 6101
 6102                self.paint_lines_background(layout, window, cx);
 6103                let invisible_display_ranges = self.paint_highlights(layout, window, cx);
 6104                self.paint_document_colors(layout, window);
 6105                self.paint_lines(&invisible_display_ranges, layout, window, cx);
 6106                self.paint_redactions(layout, window);
 6107                self.paint_cursors(layout, window, cx);
 6108                self.paint_inline_diagnostics(layout, window, cx);
 6109                self.paint_inline_blame(layout, window, cx);
 6110                self.paint_inline_code_actions(layout, window, cx);
 6111                self.paint_diff_hunk_controls(layout, window, cx);
 6112                window.with_element_namespace("crease_trailers", |window| {
 6113                    for trailer in layout.crease_trailers.iter_mut().flatten() {
 6114                        trailer.element.paint(window, cx);
 6115                    }
 6116                });
 6117            },
 6118        )
 6119    }
 6120
 6121    fn paint_highlights(
 6122        &mut self,
 6123        layout: &mut EditorLayout,
 6124        window: &mut Window,
 6125        cx: &mut App,
 6126    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
 6127        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6128            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
 6129            let line_end_overshoot = 0.15 * layout.position_map.line_height;
 6130            for (range, color) in &layout.highlighted_ranges {
 6131                self.paint_highlighted_range(
 6132                    range.clone(),
 6133                    true,
 6134                    *color,
 6135                    Pixels::ZERO,
 6136                    line_end_overshoot,
 6137                    layout,
 6138                    window,
 6139                );
 6140            }
 6141
 6142            let corner_radius = if EditorSettings::get_global(cx).rounded_selection {
 6143                0.15 * layout.position_map.line_height
 6144            } else {
 6145                Pixels::ZERO
 6146            };
 6147
 6148            for (player_color, selections) in &layout.selections {
 6149                for selection in selections.iter() {
 6150                    self.paint_highlighted_range(
 6151                        selection.range.clone(),
 6152                        true,
 6153                        player_color.selection,
 6154                        corner_radius,
 6155                        corner_radius * 2.,
 6156                        layout,
 6157                        window,
 6158                    );
 6159
 6160                    if selection.is_local && !selection.range.is_empty() {
 6161                        invisible_display_ranges.push(selection.range.clone());
 6162                    }
 6163                }
 6164            }
 6165            invisible_display_ranges
 6166        })
 6167    }
 6168
 6169    fn paint_lines(
 6170        &mut self,
 6171        invisible_display_ranges: &[Range<DisplayPoint>],
 6172        layout: &mut EditorLayout,
 6173        window: &mut Window,
 6174        cx: &mut App,
 6175    ) {
 6176        let whitespace_setting = self
 6177            .editor
 6178            .read(cx)
 6179            .buffer
 6180            .read(cx)
 6181            .language_settings(cx)
 6182            .show_whitespaces;
 6183
 6184        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
 6185            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
 6186            line_with_invisibles.draw(
 6187                layout,
 6188                row,
 6189                layout.content_origin,
 6190                whitespace_setting,
 6191                invisible_display_ranges,
 6192                window,
 6193                cx,
 6194            )
 6195        }
 6196
 6197        for line_element in &mut layout.line_elements {
 6198            line_element.paint(window, cx);
 6199        }
 6200    }
 6201
 6202    fn paint_lines_background(
 6203        &mut self,
 6204        layout: &mut EditorLayout,
 6205        window: &mut Window,
 6206        cx: &mut App,
 6207    ) {
 6208        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
 6209            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
 6210            line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
 6211        }
 6212    }
 6213
 6214    fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
 6215        if layout.redacted_ranges.is_empty() {
 6216            return;
 6217        }
 6218
 6219        let line_end_overshoot = layout.line_end_overshoot();
 6220
 6221        // A softer than perfect black
 6222        let redaction_color = gpui::rgb(0x0e1111);
 6223
 6224        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6225            for range in layout.redacted_ranges.iter() {
 6226                self.paint_highlighted_range(
 6227                    range.clone(),
 6228                    true,
 6229                    redaction_color.into(),
 6230                    Pixels::ZERO,
 6231                    line_end_overshoot,
 6232                    layout,
 6233                    window,
 6234                );
 6235            }
 6236        });
 6237    }
 6238
 6239    fn paint_document_colors(&self, layout: &mut EditorLayout, window: &mut Window) {
 6240        let Some((colors_render_mode, image_colors)) = &layout.document_colors else {
 6241            return;
 6242        };
 6243        if image_colors.is_empty()
 6244            || colors_render_mode == &DocumentColorsRenderMode::None
 6245            || colors_render_mode == &DocumentColorsRenderMode::Inlay
 6246        {
 6247            return;
 6248        }
 6249
 6250        let line_end_overshoot = layout.line_end_overshoot();
 6251
 6252        for (range, color) in image_colors {
 6253            match colors_render_mode {
 6254                DocumentColorsRenderMode::Inlay | DocumentColorsRenderMode::None => return,
 6255                DocumentColorsRenderMode::Background => {
 6256                    self.paint_highlighted_range(
 6257                        range.clone(),
 6258                        true,
 6259                        *color,
 6260                        Pixels::ZERO,
 6261                        line_end_overshoot,
 6262                        layout,
 6263                        window,
 6264                    );
 6265                }
 6266                DocumentColorsRenderMode::Border => {
 6267                    self.paint_highlighted_range(
 6268                        range.clone(),
 6269                        false,
 6270                        *color,
 6271                        Pixels::ZERO,
 6272                        line_end_overshoot,
 6273                        layout,
 6274                        window,
 6275                    );
 6276                }
 6277            }
 6278        }
 6279    }
 6280
 6281    fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6282        for cursor in &mut layout.visible_cursors {
 6283            cursor.paint(layout.content_origin, window, cx);
 6284        }
 6285    }
 6286
 6287    fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6288        let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
 6289            return;
 6290        };
 6291        let any_scrollbar_dragged = self.editor.read(cx).scroll_manager.any_scrollbar_dragged();
 6292
 6293        for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
 6294            let hitbox = &scrollbar_layout.hitbox;
 6295            if scrollbars_layout.visible {
 6296                let scrollbar_edges = match axis {
 6297                    ScrollbarAxis::Horizontal => Edges {
 6298                        top: Pixels::ZERO,
 6299                        right: Pixels::ZERO,
 6300                        bottom: Pixels::ZERO,
 6301                        left: Pixels::ZERO,
 6302                    },
 6303                    ScrollbarAxis::Vertical => Edges {
 6304                        top: Pixels::ZERO,
 6305                        right: Pixels::ZERO,
 6306                        bottom: Pixels::ZERO,
 6307                        left: ScrollbarLayout::BORDER_WIDTH,
 6308                    },
 6309                };
 6310
 6311                window.paint_layer(hitbox.bounds, |window| {
 6312                    window.paint_quad(quad(
 6313                        hitbox.bounds,
 6314                        Corners::default(),
 6315                        cx.theme().colors().scrollbar_track_background,
 6316                        scrollbar_edges,
 6317                        cx.theme().colors().scrollbar_track_border,
 6318                        BorderStyle::Solid,
 6319                    ));
 6320
 6321                    if axis == ScrollbarAxis::Vertical {
 6322                        let fast_markers =
 6323                            self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
 6324                        // Refresh slow scrollbar markers in the background. Below, we
 6325                        // paint whatever markers have already been computed.
 6326                        self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, window, cx);
 6327
 6328                        let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
 6329                        for marker in markers.iter().chain(&fast_markers) {
 6330                            let mut marker = marker.clone();
 6331                            marker.bounds.origin += hitbox.origin;
 6332                            window.paint_quad(marker);
 6333                        }
 6334                    }
 6335
 6336                    if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
 6337                        let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
 6338                            ScrollbarThumbState::Dragging => {
 6339                                cx.theme().colors().scrollbar_thumb_active_background
 6340                            }
 6341                            ScrollbarThumbState::Hovered => {
 6342                                cx.theme().colors().scrollbar_thumb_hover_background
 6343                            }
 6344                            ScrollbarThumbState::Idle => {
 6345                                cx.theme().colors().scrollbar_thumb_background
 6346                            }
 6347                        };
 6348                        window.paint_quad(quad(
 6349                            thumb_bounds,
 6350                            Corners::default(),
 6351                            scrollbar_thumb_color,
 6352                            scrollbar_edges,
 6353                            cx.theme().colors().scrollbar_thumb_border,
 6354                            BorderStyle::Solid,
 6355                        ));
 6356
 6357                        if any_scrollbar_dragged {
 6358                            window.set_window_cursor_style(CursorStyle::Arrow);
 6359                        } else {
 6360                            window.set_cursor_style(CursorStyle::Arrow, hitbox);
 6361                        }
 6362                    }
 6363                })
 6364            }
 6365        }
 6366
 6367        window.on_mouse_event({
 6368            let editor = self.editor.clone();
 6369            let scrollbars_layout = scrollbars_layout.clone();
 6370
 6371            let mut mouse_position = window.mouse_position();
 6372            move |event: &MouseMoveEvent, phase, window, cx| {
 6373                if phase == DispatchPhase::Capture {
 6374                    return;
 6375                }
 6376
 6377                editor.update(cx, |editor, cx| {
 6378                    if let Some((scrollbar_layout, axis)) = event
 6379                        .pressed_button
 6380                        .filter(|button| *button == MouseButton::Left)
 6381                        .and(editor.scroll_manager.dragging_scrollbar_axis())
 6382                        .and_then(|axis| {
 6383                            scrollbars_layout
 6384                                .iter_scrollbars()
 6385                                .find(|(_, a)| *a == axis)
 6386                        })
 6387                    {
 6388                        let ScrollbarLayout {
 6389                            hitbox,
 6390                            text_unit_size,
 6391                            ..
 6392                        } = scrollbar_layout;
 6393
 6394                        let old_position = mouse_position.along(axis);
 6395                        let new_position = event.position.along(axis);
 6396                        if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
 6397                            .contains(&old_position)
 6398                        {
 6399                            let position = editor.scroll_position(cx).apply_along(axis, |p| {
 6400                                (p + (new_position - old_position) / *text_unit_size).max(0.)
 6401                            });
 6402                            editor.set_scroll_position(position, window, cx);
 6403                        }
 6404
 6405                        editor.scroll_manager.show_scrollbars(window, cx);
 6406                        cx.stop_propagation();
 6407                    } else if let Some((layout, axis)) = scrollbars_layout
 6408                        .get_hovered_axis(window)
 6409                        .filter(|_| !event.dragging())
 6410                    {
 6411                        if layout.thumb_hovered(&event.position) {
 6412                            editor
 6413                                .scroll_manager
 6414                                .set_hovered_scroll_thumb_axis(axis, cx);
 6415                        } else {
 6416                            editor.scroll_manager.reset_scrollbar_state(cx);
 6417                        }
 6418
 6419                        editor.scroll_manager.show_scrollbars(window, cx);
 6420                    } else {
 6421                        editor.scroll_manager.reset_scrollbar_state(cx);
 6422                    }
 6423
 6424                    mouse_position = event.position;
 6425                })
 6426            }
 6427        });
 6428
 6429        if any_scrollbar_dragged {
 6430            window.on_mouse_event({
 6431                let editor = self.editor.clone();
 6432                move |_: &MouseUpEvent, phase, window, cx| {
 6433                    if phase == DispatchPhase::Capture {
 6434                        return;
 6435                    }
 6436
 6437                    editor.update(cx, |editor, cx| {
 6438                        if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
 6439                            editor
 6440                                .scroll_manager
 6441                                .set_hovered_scroll_thumb_axis(axis, cx);
 6442                        } else {
 6443                            editor.scroll_manager.reset_scrollbar_state(cx);
 6444                        }
 6445                        cx.stop_propagation();
 6446                    });
 6447                }
 6448            });
 6449        } else {
 6450            window.on_mouse_event({
 6451                let editor = self.editor.clone();
 6452
 6453                move |event: &MouseDownEvent, phase, window, cx| {
 6454                    if phase == DispatchPhase::Capture {
 6455                        return;
 6456                    }
 6457                    let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
 6458                    else {
 6459                        return;
 6460                    };
 6461
 6462                    let ScrollbarLayout {
 6463                        hitbox,
 6464                        visible_range,
 6465                        text_unit_size,
 6466                        thumb_bounds,
 6467                        ..
 6468                    } = scrollbar_layout;
 6469
 6470                    let Some(thumb_bounds) = thumb_bounds else {
 6471                        return;
 6472                    };
 6473
 6474                    editor.update(cx, |editor, cx| {
 6475                        editor
 6476                            .scroll_manager
 6477                            .set_dragged_scroll_thumb_axis(axis, cx);
 6478
 6479                        let event_position = event.position.along(axis);
 6480
 6481                        if event_position < thumb_bounds.origin.along(axis)
 6482                            || thumb_bounds.bottom_right().along(axis) < event_position
 6483                        {
 6484                            let center_position = ((event_position - hitbox.origin.along(axis))
 6485                                / *text_unit_size)
 6486                                .round() as u32;
 6487                            let start_position = center_position.saturating_sub(
 6488                                (visible_range.end - visible_range.start) as u32 / 2,
 6489                            );
 6490
 6491                            let position = editor
 6492                                .scroll_position(cx)
 6493                                .apply_along(axis, |_| start_position as f32);
 6494
 6495                            editor.set_scroll_position(position, window, cx);
 6496                        } else {
 6497                            editor.scroll_manager.show_scrollbars(window, cx);
 6498                        }
 6499
 6500                        cx.stop_propagation();
 6501                    });
 6502                }
 6503            });
 6504        }
 6505    }
 6506
 6507    fn collect_fast_scrollbar_markers(
 6508        &self,
 6509        layout: &EditorLayout,
 6510        scrollbar_layout: &ScrollbarLayout,
 6511        cx: &mut App,
 6512    ) -> Vec<PaintQuad> {
 6513        const LIMIT: usize = 100;
 6514        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
 6515            return vec![];
 6516        }
 6517        let cursor_ranges = layout
 6518            .cursors
 6519            .iter()
 6520            .map(|(point, color)| ColoredRange {
 6521                start: point.row(),
 6522                end: point.row(),
 6523                color: *color,
 6524            })
 6525            .collect_vec();
 6526        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
 6527    }
 6528
 6529    fn refresh_slow_scrollbar_markers(
 6530        &self,
 6531        layout: &EditorLayout,
 6532        scrollbar_layout: &ScrollbarLayout,
 6533        window: &mut Window,
 6534        cx: &mut App,
 6535    ) {
 6536        self.editor.update(cx, |editor, cx| {
 6537            if !editor.is_singleton(cx)
 6538                || !editor
 6539                    .scrollbar_marker_state
 6540                    .should_refresh(scrollbar_layout.hitbox.size)
 6541            {
 6542                return;
 6543            }
 6544
 6545            let scrollbar_layout = scrollbar_layout.clone();
 6546            let background_highlights = editor.background_highlights.clone();
 6547            let snapshot = layout.position_map.snapshot.clone();
 6548            let theme = cx.theme().clone();
 6549            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
 6550
 6551            editor.scrollbar_marker_state.dirty = false;
 6552            editor.scrollbar_marker_state.pending_refresh =
 6553                Some(cx.spawn_in(window, async move |editor, cx| {
 6554                    let scrollbar_size = scrollbar_layout.hitbox.size;
 6555                    let scrollbar_markers = cx
 6556                        .background_spawn(async move {
 6557                            let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
 6558                            let mut marker_quads = Vec::new();
 6559                            if scrollbar_settings.git_diff {
 6560                                let marker_row_ranges =
 6561                                    snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
 6562                                        let start_display_row =
 6563                                            MultiBufferPoint::new(hunk.row_range.start.0, 0)
 6564                                                .to_display_point(&snapshot.display_snapshot)
 6565                                                .row();
 6566                                        let mut end_display_row =
 6567                                            MultiBufferPoint::new(hunk.row_range.end.0, 0)
 6568                                                .to_display_point(&snapshot.display_snapshot)
 6569                                                .row();
 6570                                        if end_display_row != start_display_row {
 6571                                            end_display_row.0 -= 1;
 6572                                        }
 6573                                        let color = match &hunk.status().kind {
 6574                                            DiffHunkStatusKind::Added => {
 6575                                                theme.colors().version_control_added
 6576                                            }
 6577                                            DiffHunkStatusKind::Modified => {
 6578                                                theme.colors().version_control_modified
 6579                                            }
 6580                                            DiffHunkStatusKind::Deleted => {
 6581                                                theme.colors().version_control_deleted
 6582                                            }
 6583                                        };
 6584                                        ColoredRange {
 6585                                            start: start_display_row,
 6586                                            end: end_display_row,
 6587                                            color,
 6588                                        }
 6589                                    });
 6590
 6591                                marker_quads.extend(
 6592                                    scrollbar_layout
 6593                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
 6594                                );
 6595                            }
 6596
 6597                            for (background_highlight_id, (_, background_ranges)) in
 6598                                background_highlights.iter()
 6599                            {
 6600                                let is_search_highlights = *background_highlight_id
 6601                                    == HighlightKey::Type(TypeId::of::<BufferSearchHighlights>());
 6602                                let is_text_highlights = *background_highlight_id
 6603                                    == HighlightKey::Type(TypeId::of::<SelectedTextHighlight>());
 6604                                let is_symbol_occurrences = *background_highlight_id
 6605                                    == HighlightKey::Type(TypeId::of::<DocumentHighlightRead>())
 6606                                    || *background_highlight_id
 6607                                        == HighlightKey::Type(
 6608                                            TypeId::of::<DocumentHighlightWrite>(),
 6609                                        );
 6610                                if (is_search_highlights && scrollbar_settings.search_results)
 6611                                    || (is_text_highlights && scrollbar_settings.selected_text)
 6612                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
 6613                                {
 6614                                    let mut color = theme.status().info;
 6615                                    if is_symbol_occurrences {
 6616                                        color.fade_out(0.5);
 6617                                    }
 6618                                    let marker_row_ranges = background_ranges.iter().map(|range| {
 6619                                        let display_start = range
 6620                                            .start
 6621                                            .to_display_point(&snapshot.display_snapshot);
 6622                                        let display_end =
 6623                                            range.end.to_display_point(&snapshot.display_snapshot);
 6624                                        ColoredRange {
 6625                                            start: display_start.row(),
 6626                                            end: display_end.row(),
 6627                                            color,
 6628                                        }
 6629                                    });
 6630                                    marker_quads.extend(
 6631                                        scrollbar_layout
 6632                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
 6633                                    );
 6634                                }
 6635                            }
 6636
 6637                            if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
 6638                                let diagnostics = snapshot
 6639                                    .buffer_snapshot
 6640                                    .diagnostics_in_range::<Point>(Point::zero()..max_point)
 6641                                    // Don't show diagnostics the user doesn't care about
 6642                                    .filter(|diagnostic| {
 6643                                        match (
 6644                                            scrollbar_settings.diagnostics,
 6645                                            diagnostic.diagnostic.severity,
 6646                                        ) {
 6647                                            (ScrollbarDiagnostics::All, _) => true,
 6648                                            (
 6649                                                ScrollbarDiagnostics::Error,
 6650                                                lsp::DiagnosticSeverity::ERROR,
 6651                                            ) => true,
 6652                                            (
 6653                                                ScrollbarDiagnostics::Warning,
 6654                                                lsp::DiagnosticSeverity::ERROR
 6655                                                | lsp::DiagnosticSeverity::WARNING,
 6656                                            ) => true,
 6657                                            (
 6658                                                ScrollbarDiagnostics::Information,
 6659                                                lsp::DiagnosticSeverity::ERROR
 6660                                                | lsp::DiagnosticSeverity::WARNING
 6661                                                | lsp::DiagnosticSeverity::INFORMATION,
 6662                                            ) => true,
 6663                                            (_, _) => false,
 6664                                        }
 6665                                    })
 6666                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
 6667                                    .sorted_by_key(|diagnostic| {
 6668                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
 6669                                    });
 6670
 6671                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
 6672                                    let start_display = diagnostic
 6673                                        .range
 6674                                        .start
 6675                                        .to_display_point(&snapshot.display_snapshot);
 6676                                    let end_display = diagnostic
 6677                                        .range
 6678                                        .end
 6679                                        .to_display_point(&snapshot.display_snapshot);
 6680                                    let color = match diagnostic.diagnostic.severity {
 6681                                        lsp::DiagnosticSeverity::ERROR => theme.status().error,
 6682                                        lsp::DiagnosticSeverity::WARNING => theme.status().warning,
 6683                                        lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
 6684                                        _ => theme.status().hint,
 6685                                    };
 6686                                    ColoredRange {
 6687                                        start: start_display.row(),
 6688                                        end: end_display.row(),
 6689                                        color,
 6690                                    }
 6691                                });
 6692                                marker_quads.extend(
 6693                                    scrollbar_layout
 6694                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
 6695                                );
 6696                            }
 6697
 6698                            Arc::from(marker_quads)
 6699                        })
 6700                        .await;
 6701
 6702                    editor.update(cx, |editor, cx| {
 6703                        editor.scrollbar_marker_state.markers = scrollbar_markers;
 6704                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
 6705                        editor.scrollbar_marker_state.pending_refresh = None;
 6706                        cx.notify();
 6707                    })?;
 6708
 6709                    Ok(())
 6710                }));
 6711        });
 6712    }
 6713
 6714    fn paint_highlighted_range(
 6715        &self,
 6716        range: Range<DisplayPoint>,
 6717        fill: bool,
 6718        color: Hsla,
 6719        corner_radius: Pixels,
 6720        line_end_overshoot: Pixels,
 6721        layout: &EditorLayout,
 6722        window: &mut Window,
 6723    ) {
 6724        let start_row = layout.visible_display_row_range.start;
 6725        let end_row = layout.visible_display_row_range.end;
 6726        if range.start != range.end {
 6727            let row_range = if range.end.column() == 0 {
 6728                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
 6729            } else {
 6730                cmp::max(range.start.row(), start_row)
 6731                    ..cmp::min(range.end.row().next_row(), end_row)
 6732            };
 6733
 6734            let highlighted_range = HighlightedRange {
 6735                color,
 6736                line_height: layout.position_map.line_height,
 6737                corner_radius,
 6738                start_y: layout.content_origin.y
 6739                    + row_range.start.as_f32() * layout.position_map.line_height
 6740                    - layout.position_map.scroll_pixel_position.y,
 6741                lines: row_range
 6742                    .iter_rows()
 6743                    .map(|row| {
 6744                        let line_layout =
 6745                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
 6746                        HighlightedRangeLine {
 6747                            start_x: if row == range.start.row() {
 6748                                layout.content_origin.x
 6749                                    + line_layout.x_for_index(range.start.column() as usize)
 6750                                    - layout.position_map.scroll_pixel_position.x
 6751                            } else {
 6752                                layout.content_origin.x
 6753                                    - layout.position_map.scroll_pixel_position.x
 6754                            },
 6755                            end_x: if row == range.end.row() {
 6756                                layout.content_origin.x
 6757                                    + line_layout.x_for_index(range.end.column() as usize)
 6758                                    - layout.position_map.scroll_pixel_position.x
 6759                            } else {
 6760                                layout.content_origin.x + line_layout.width + line_end_overshoot
 6761                                    - layout.position_map.scroll_pixel_position.x
 6762                            },
 6763                        }
 6764                    })
 6765                    .collect(),
 6766            };
 6767
 6768            highlighted_range.paint(fill, layout.position_map.text_hitbox.bounds, window);
 6769        }
 6770    }
 6771
 6772    fn paint_inline_diagnostics(
 6773        &mut self,
 6774        layout: &mut EditorLayout,
 6775        window: &mut Window,
 6776        cx: &mut App,
 6777    ) {
 6778        for mut inline_diagnostic in layout.inline_diagnostics.drain() {
 6779            inline_diagnostic.1.paint(window, cx);
 6780        }
 6781    }
 6782
 6783    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6784        if let Some(mut blame_layout) = layout.inline_blame_layout.take() {
 6785            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6786                blame_layout.element.paint(window, cx);
 6787            })
 6788        }
 6789    }
 6790
 6791    fn paint_inline_code_actions(
 6792        &mut self,
 6793        layout: &mut EditorLayout,
 6794        window: &mut Window,
 6795        cx: &mut App,
 6796    ) {
 6797        if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
 6798            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6799                inline_code_actions.paint(window, cx);
 6800            })
 6801        }
 6802    }
 6803
 6804    fn paint_diff_hunk_controls(
 6805        &mut self,
 6806        layout: &mut EditorLayout,
 6807        window: &mut Window,
 6808        cx: &mut App,
 6809    ) {
 6810        for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
 6811            diff_hunk_control.paint(window, cx);
 6812        }
 6813    }
 6814
 6815    fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6816        if let Some(mut layout) = layout.minimap.take() {
 6817            let minimap_hitbox = layout.thumb_layout.hitbox.clone();
 6818            let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
 6819
 6820            window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
 6821                window.with_element_namespace("minimap", |window| {
 6822                    layout.minimap.paint(window, cx);
 6823                    if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
 6824                        let minimap_thumb_color = match layout.thumb_layout.thumb_state {
 6825                            ScrollbarThumbState::Idle => {
 6826                                cx.theme().colors().minimap_thumb_background
 6827                            }
 6828                            ScrollbarThumbState::Hovered => {
 6829                                cx.theme().colors().minimap_thumb_hover_background
 6830                            }
 6831                            ScrollbarThumbState::Dragging => {
 6832                                cx.theme().colors().minimap_thumb_active_background
 6833                            }
 6834                        };
 6835                        let minimap_thumb_border = match layout.thumb_border_style {
 6836                            MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
 6837                            MinimapThumbBorder::LeftOnly => Edges {
 6838                                left: ScrollbarLayout::BORDER_WIDTH,
 6839                                ..Default::default()
 6840                            },
 6841                            MinimapThumbBorder::LeftOpen => Edges {
 6842                                right: ScrollbarLayout::BORDER_WIDTH,
 6843                                top: ScrollbarLayout::BORDER_WIDTH,
 6844                                bottom: ScrollbarLayout::BORDER_WIDTH,
 6845                                ..Default::default()
 6846                            },
 6847                            MinimapThumbBorder::RightOpen => Edges {
 6848                                left: ScrollbarLayout::BORDER_WIDTH,
 6849                                top: ScrollbarLayout::BORDER_WIDTH,
 6850                                bottom: ScrollbarLayout::BORDER_WIDTH,
 6851                                ..Default::default()
 6852                            },
 6853                            MinimapThumbBorder::None => Default::default(),
 6854                        };
 6855
 6856                        window.paint_layer(minimap_hitbox.bounds, |window| {
 6857                            window.paint_quad(quad(
 6858                                thumb_bounds,
 6859                                Corners::default(),
 6860                                minimap_thumb_color,
 6861                                minimap_thumb_border,
 6862                                cx.theme().colors().minimap_thumb_border,
 6863                                BorderStyle::Solid,
 6864                            ));
 6865                        });
 6866                    }
 6867                });
 6868            });
 6869
 6870            if dragging_minimap {
 6871                window.set_window_cursor_style(CursorStyle::Arrow);
 6872            } else {
 6873                window.set_cursor_style(CursorStyle::Arrow, &minimap_hitbox);
 6874            }
 6875
 6876            let minimap_axis = ScrollbarAxis::Vertical;
 6877            let pixels_per_line = (minimap_hitbox.size.height / layout.max_scroll_top)
 6878                .min(layout.minimap_line_height);
 6879
 6880            let mut mouse_position = window.mouse_position();
 6881
 6882            window.on_mouse_event({
 6883                let editor = self.editor.clone();
 6884
 6885                let minimap_hitbox = minimap_hitbox.clone();
 6886
 6887                move |event: &MouseMoveEvent, phase, window, cx| {
 6888                    if phase == DispatchPhase::Capture {
 6889                        return;
 6890                    }
 6891
 6892                    editor.update(cx, |editor, cx| {
 6893                        if event.pressed_button == Some(MouseButton::Left)
 6894                            && editor.scroll_manager.is_dragging_minimap()
 6895                        {
 6896                            let old_position = mouse_position.along(minimap_axis);
 6897                            let new_position = event.position.along(minimap_axis);
 6898                            if (minimap_hitbox.origin.along(minimap_axis)
 6899                                ..minimap_hitbox.bottom_right().along(minimap_axis))
 6900                                .contains(&old_position)
 6901                            {
 6902                                let position =
 6903                                    editor.scroll_position(cx).apply_along(minimap_axis, |p| {
 6904                                        (p + (new_position - old_position) / pixels_per_line)
 6905                                            .max(0.)
 6906                                    });
 6907                                editor.set_scroll_position(position, window, cx);
 6908                            }
 6909                            cx.stop_propagation();
 6910                        } else if minimap_hitbox.is_hovered(window) {
 6911                            editor.scroll_manager.set_is_hovering_minimap_thumb(
 6912                                !event.dragging()
 6913                                    && layout
 6914                                        .thumb_layout
 6915                                        .thumb_bounds
 6916                                        .is_some_and(|bounds| bounds.contains(&event.position)),
 6917                                cx,
 6918                            );
 6919
 6920                            // Stop hover events from propagating to the
 6921                            // underlying editor if the minimap hitbox is hovered
 6922                            if !event.dragging() {
 6923                                cx.stop_propagation();
 6924                            }
 6925                        } else {
 6926                            editor.scroll_manager.hide_minimap_thumb(cx);
 6927                        }
 6928                        mouse_position = event.position;
 6929                    });
 6930                }
 6931            });
 6932
 6933            if dragging_minimap {
 6934                window.on_mouse_event({
 6935                    let editor = self.editor.clone();
 6936                    move |event: &MouseUpEvent, phase, window, cx| {
 6937                        if phase == DispatchPhase::Capture {
 6938                            return;
 6939                        }
 6940
 6941                        editor.update(cx, |editor, cx| {
 6942                            if minimap_hitbox.is_hovered(window) {
 6943                                editor.scroll_manager.set_is_hovering_minimap_thumb(
 6944                                    layout
 6945                                        .thumb_layout
 6946                                        .thumb_bounds
 6947                                        .is_some_and(|bounds| bounds.contains(&event.position)),
 6948                                    cx,
 6949                                );
 6950                            } else {
 6951                                editor.scroll_manager.hide_minimap_thumb(cx);
 6952                            }
 6953                            cx.stop_propagation();
 6954                        });
 6955                    }
 6956                });
 6957            } else {
 6958                window.on_mouse_event({
 6959                    let editor = self.editor.clone();
 6960
 6961                    move |event: &MouseDownEvent, phase, window, cx| {
 6962                        if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
 6963                            return;
 6964                        }
 6965
 6966                        let event_position = event.position;
 6967
 6968                        let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
 6969                            return;
 6970                        };
 6971
 6972                        editor.update(cx, |editor, cx| {
 6973                            if !thumb_bounds.contains(&event_position) {
 6974                                let click_position =
 6975                                    event_position.relative_to(&minimap_hitbox.origin).y;
 6976
 6977                                let top_position = (click_position
 6978                                    - thumb_bounds.size.along(minimap_axis) / 2.0)
 6979                                    .max(Pixels::ZERO);
 6980
 6981                                let scroll_offset = (layout.minimap_scroll_top
 6982                                    + top_position / layout.minimap_line_height)
 6983                                    .min(layout.max_scroll_top);
 6984
 6985                                let scroll_position = editor
 6986                                    .scroll_position(cx)
 6987                                    .apply_along(minimap_axis, |_| scroll_offset);
 6988                                editor.set_scroll_position(scroll_position, window, cx);
 6989                            }
 6990
 6991                            editor.scroll_manager.set_is_dragging_minimap(cx);
 6992                            cx.stop_propagation();
 6993                        });
 6994                    }
 6995                });
 6996            }
 6997        }
 6998    }
 6999
 7000    fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 7001        for mut block in layout.blocks.drain(..) {
 7002            if block.overlaps_gutter {
 7003                block.element.paint(window, cx);
 7004            } else {
 7005                let mut bounds = layout.hitbox.bounds;
 7006                bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
 7007                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 7008                    block.element.paint(window, cx);
 7009                })
 7010            }
 7011        }
 7012    }
 7013
 7014    fn paint_edit_prediction_popover(
 7015        &mut self,
 7016        layout: &mut EditorLayout,
 7017        window: &mut Window,
 7018        cx: &mut App,
 7019    ) {
 7020        if let Some(edit_prediction_popover) = layout.edit_prediction_popover.as_mut() {
 7021            edit_prediction_popover.paint(window, cx);
 7022        }
 7023    }
 7024
 7025    fn paint_mouse_context_menu(
 7026        &mut self,
 7027        layout: &mut EditorLayout,
 7028        window: &mut Window,
 7029        cx: &mut App,
 7030    ) {
 7031        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
 7032            mouse_context_menu.paint(window, cx);
 7033        }
 7034    }
 7035
 7036    fn paint_scroll_wheel_listener(
 7037        &mut self,
 7038        layout: &EditorLayout,
 7039        window: &mut Window,
 7040        cx: &mut App,
 7041    ) {
 7042        window.on_mouse_event({
 7043            let position_map = layout.position_map.clone();
 7044            let editor = self.editor.clone();
 7045            let hitbox = layout.hitbox.clone();
 7046            let mut delta = ScrollDelta::default();
 7047
 7048            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
 7049            // accidentally turn off their scrolling.
 7050            let base_scroll_sensitivity =
 7051                EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
 7052
 7053            // Use a minimum fast_scroll_sensitivity for same reason above
 7054            let fast_scroll_sensitivity = EditorSettings::get_global(cx)
 7055                .fast_scroll_sensitivity
 7056                .max(0.01);
 7057
 7058            move |event: &ScrollWheelEvent, phase, window, cx| {
 7059                let scroll_sensitivity = {
 7060                    if event.modifiers.alt {
 7061                        fast_scroll_sensitivity
 7062                    } else {
 7063                        base_scroll_sensitivity
 7064                    }
 7065                };
 7066
 7067                if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
 7068                    delta = delta.coalesce(event.delta);
 7069                    editor.update(cx, |editor, cx| {
 7070                        let position_map: &PositionMap = &position_map;
 7071
 7072                        let line_height = position_map.line_height;
 7073                        let max_glyph_advance = position_map.em_advance;
 7074                        let (delta, axis) = match delta {
 7075                            gpui::ScrollDelta::Pixels(mut pixels) => {
 7076                                //Trackpad
 7077                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
 7078                                (pixels, axis)
 7079                            }
 7080
 7081                            gpui::ScrollDelta::Lines(lines) => {
 7082                                //Not trackpad
 7083                                let pixels =
 7084                                    point(lines.x * max_glyph_advance, lines.y * line_height);
 7085                                (pixels, None)
 7086                            }
 7087                        };
 7088
 7089                        let current_scroll_position = position_map.snapshot.scroll_position();
 7090                        let x = (current_scroll_position.x * max_glyph_advance
 7091                            - (delta.x * scroll_sensitivity))
 7092                            / max_glyph_advance;
 7093                        let y = (current_scroll_position.y * line_height
 7094                            - (delta.y * scroll_sensitivity))
 7095                            / line_height;
 7096                        let mut scroll_position =
 7097                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
 7098                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
 7099                        if forbid_vertical_scroll {
 7100                            scroll_position.y = current_scroll_position.y;
 7101                        }
 7102
 7103                        if scroll_position != current_scroll_position {
 7104                            editor.scroll(scroll_position, axis, window, cx);
 7105                            cx.stop_propagation();
 7106                        } else if y < 0. {
 7107                            // Due to clamping, we may fail to detect cases of overscroll to the top;
 7108                            // We want the scroll manager to get an update in such cases and detect the change of direction
 7109                            // on the next frame.
 7110                            cx.notify();
 7111                        }
 7112                    });
 7113                }
 7114            }
 7115        });
 7116    }
 7117
 7118    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
 7119        if layout.mode.is_minimap() {
 7120            return;
 7121        }
 7122
 7123        self.paint_scroll_wheel_listener(layout, window, cx);
 7124
 7125        window.on_mouse_event({
 7126            let position_map = layout.position_map.clone();
 7127            let editor = self.editor.clone();
 7128            let diff_hunk_range =
 7129                layout
 7130                    .display_hunks
 7131                    .iter()
 7132                    .find_map(|(hunk, hunk_hitbox)| match hunk {
 7133                        DisplayDiffHunk::Folded { .. } => None,
 7134                        DisplayDiffHunk::Unfolded {
 7135                            multi_buffer_range, ..
 7136                        } => {
 7137                            if hunk_hitbox
 7138                                .as_ref()
 7139                                .map(|hitbox| hitbox.is_hovered(window))
 7140                                .unwrap_or(false)
 7141                            {
 7142                                Some(multi_buffer_range.clone())
 7143                            } else {
 7144                                None
 7145                            }
 7146                        }
 7147                    });
 7148            let line_numbers = layout.line_numbers.clone();
 7149
 7150            move |event: &MouseDownEvent, phase, window, cx| {
 7151                if phase == DispatchPhase::Bubble {
 7152                    match event.button {
 7153                        MouseButton::Left => editor.update(cx, |editor, cx| {
 7154                            let pending_mouse_down = editor
 7155                                .pending_mouse_down
 7156                                .get_or_insert_with(Default::default)
 7157                                .clone();
 7158
 7159                            *pending_mouse_down.borrow_mut() = Some(event.clone());
 7160
 7161                            Self::mouse_left_down(
 7162                                editor,
 7163                                event,
 7164                                diff_hunk_range.clone(),
 7165                                &position_map,
 7166                                line_numbers.as_ref(),
 7167                                window,
 7168                                cx,
 7169                            );
 7170                        }),
 7171                        MouseButton::Right => editor.update(cx, |editor, cx| {
 7172                            Self::mouse_right_down(editor, event, &position_map, window, cx);
 7173                        }),
 7174                        MouseButton::Middle => editor.update(cx, |editor, cx| {
 7175                            Self::mouse_middle_down(editor, event, &position_map, window, cx);
 7176                        }),
 7177                        _ => {}
 7178                    };
 7179                }
 7180            }
 7181        });
 7182
 7183        window.on_mouse_event({
 7184            let editor = self.editor.clone();
 7185            let position_map = layout.position_map.clone();
 7186
 7187            move |event: &MouseUpEvent, phase, window, cx| {
 7188                if phase == DispatchPhase::Bubble {
 7189                    editor.update(cx, |editor, cx| {
 7190                        Self::mouse_up(editor, event, &position_map, window, cx)
 7191                    });
 7192                }
 7193            }
 7194        });
 7195
 7196        window.on_mouse_event({
 7197            let editor = self.editor.clone();
 7198            let position_map = layout.position_map.clone();
 7199            let mut captured_mouse_down = None;
 7200
 7201            move |event: &MouseUpEvent, phase, window, cx| match phase {
 7202                // Clear the pending mouse down during the capture phase,
 7203                // so that it happens even if another event handler stops
 7204                // propagation.
 7205                DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
 7206                    let pending_mouse_down = editor
 7207                        .pending_mouse_down
 7208                        .get_or_insert_with(Default::default)
 7209                        .clone();
 7210
 7211                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
 7212                    if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
 7213                        captured_mouse_down = pending_mouse_down.take();
 7214                        window.refresh();
 7215                    }
 7216                }),
 7217                // Fire click handlers during the bubble phase.
 7218                DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
 7219                    if let Some(mouse_down) = captured_mouse_down.take() {
 7220                        let event = ClickEvent::Mouse(MouseClickEvent {
 7221                            down: mouse_down,
 7222                            up: event.clone(),
 7223                        });
 7224                        Self::click(editor, &event, &position_map, window, cx);
 7225                    }
 7226                }),
 7227            }
 7228        });
 7229
 7230        window.on_mouse_event({
 7231            let position_map = layout.position_map.clone();
 7232            let editor = self.editor.clone();
 7233
 7234            move |event: &MouseMoveEvent, phase, window, cx| {
 7235                if phase == DispatchPhase::Bubble {
 7236                    editor.update(cx, |editor, cx| {
 7237                        if editor.hover_state.focused(window, cx) {
 7238                            return;
 7239                        }
 7240                        if event.pressed_button == Some(MouseButton::Left)
 7241                            || event.pressed_button == Some(MouseButton::Middle)
 7242                        {
 7243                            Self::mouse_dragged(editor, event, &position_map, window, cx)
 7244                        }
 7245
 7246                        Self::mouse_moved(editor, event, &position_map, window, cx)
 7247                    });
 7248                }
 7249            }
 7250        });
 7251    }
 7252
 7253    fn column_pixels(&self, column: usize, window: &Window) -> Pixels {
 7254        let style = &self.style;
 7255        let font_size = style.text.font_size.to_pixels(window.rem_size());
 7256        let layout = window.text_system().shape_line(
 7257            SharedString::from(" ".repeat(column)),
 7258            font_size,
 7259            &[TextRun {
 7260                len: column,
 7261                font: style.text.font(),
 7262                color: Hsla::default(),
 7263                background_color: None,
 7264                underline: None,
 7265                strikethrough: None,
 7266            }],
 7267            None,
 7268        );
 7269
 7270        layout.width
 7271    }
 7272
 7273    fn max_line_number_width(&self, snapshot: &EditorSnapshot, window: &mut Window) -> Pixels {
 7274        let digit_count = snapshot.widest_line_number().ilog10() + 1;
 7275        self.column_pixels(digit_count as usize, window)
 7276    }
 7277
 7278    fn shape_line_number(
 7279        &self,
 7280        text: SharedString,
 7281        color: Hsla,
 7282        window: &mut Window,
 7283    ) -> ShapedLine {
 7284        let run = TextRun {
 7285            len: text.len(),
 7286            font: self.style.text.font(),
 7287            color,
 7288            background_color: None,
 7289            underline: None,
 7290            strikethrough: None,
 7291        };
 7292        window.text_system().shape_line(
 7293            text,
 7294            self.style.text.font_size.to_pixels(window.rem_size()),
 7295            &[run],
 7296            None,
 7297        )
 7298    }
 7299
 7300    fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
 7301        let unstaged = status.has_secondary_hunk();
 7302        let unstaged_hollow = ProjectSettings::get_global(cx)
 7303            .git
 7304            .hunk_style
 7305            .is_some_and(|style| matches!(style, GitHunkStyleSetting::UnstagedHollow));
 7306
 7307        unstaged == unstaged_hollow
 7308    }
 7309
 7310    #[cfg(debug_assertions)]
 7311    fn layout_debug_ranges(
 7312        selections: &mut Vec<(PlayerColor, Vec<SelectionLayout>)>,
 7313        anchor_range: Range<Anchor>,
 7314        display_snapshot: &DisplaySnapshot,
 7315        cx: &App,
 7316    ) {
 7317        let theme = cx.theme();
 7318        text::debug::GlobalDebugRanges::with_locked(|debug_ranges| {
 7319            if debug_ranges.ranges.is_empty() {
 7320                return;
 7321            }
 7322            let buffer_snapshot = &display_snapshot.buffer_snapshot;
 7323            for (buffer, buffer_range, excerpt_id) in
 7324                buffer_snapshot.range_to_buffer_ranges(anchor_range)
 7325            {
 7326                let buffer_range =
 7327                    buffer.anchor_after(buffer_range.start)..buffer.anchor_before(buffer_range.end);
 7328                selections.extend(debug_ranges.ranges.iter().flat_map(|debug_range| {
 7329                    let player_color = theme
 7330                        .players()
 7331                        .color_for_participant(debug_range.occurrence_index as u32 + 1);
 7332                    debug_range.ranges.iter().filter_map(move |range| {
 7333                        if range.start.buffer_id != Some(buffer.remote_id()) {
 7334                            return None;
 7335                        }
 7336                        let clipped_start = range.start.max(&buffer_range.start, buffer);
 7337                        let clipped_end = range.end.min(&buffer_range.end, buffer);
 7338                        let range = buffer_snapshot.anchor_in_excerpt(excerpt_id, clipped_start)?
 7339                            ..buffer_snapshot.anchor_in_excerpt(excerpt_id, clipped_end)?;
 7340                        let start = range.start.to_display_point(display_snapshot);
 7341                        let end = range.end.to_display_point(display_snapshot);
 7342                        let selection_layout = SelectionLayout {
 7343                            head: start,
 7344                            range: start..end,
 7345                            cursor_shape: CursorShape::Bar,
 7346                            is_newest: false,
 7347                            is_local: false,
 7348                            active_rows: start.row()..end.row(),
 7349                            user_name: Some(SharedString::new(debug_range.value.clone())),
 7350                        };
 7351                        Some((player_color, vec![selection_layout]))
 7352                    })
 7353                }));
 7354            }
 7355        });
 7356    }
 7357}
 7358
 7359fn header_jump_data(
 7360    snapshot: &EditorSnapshot,
 7361    block_row_start: DisplayRow,
 7362    height: u32,
 7363    for_excerpt: &ExcerptInfo,
 7364) -> JumpData {
 7365    let range = &for_excerpt.range;
 7366    let buffer = &for_excerpt.buffer;
 7367    let jump_anchor = range.primary.start;
 7368
 7369    let excerpt_start = range.context.start;
 7370    let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
 7371    let rows_from_excerpt_start = if jump_anchor == excerpt_start {
 7372        0
 7373    } else {
 7374        let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
 7375        jump_position.row.saturating_sub(excerpt_start_point.row)
 7376    };
 7377
 7378    let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
 7379        .saturating_sub(
 7380            snapshot
 7381                .scroll_anchor
 7382                .scroll_position(&snapshot.display_snapshot)
 7383                .y as u32,
 7384        );
 7385
 7386    JumpData::MultiBufferPoint {
 7387        excerpt_id: for_excerpt.id,
 7388        anchor: jump_anchor,
 7389        position: jump_position,
 7390        line_offset_from_top,
 7391    }
 7392}
 7393
 7394pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
 7395
 7396impl AcceptEditPredictionBinding {
 7397    pub fn keystroke(&self) -> Option<&KeybindingKeystroke> {
 7398        if let Some(binding) = self.0.as_ref() {
 7399            match &binding.keystrokes() {
 7400                [keystroke, ..] => Some(keystroke),
 7401                _ => None,
 7402            }
 7403        } else {
 7404            None
 7405        }
 7406    }
 7407}
 7408
 7409fn prepaint_gutter_button(
 7410    button: IconButton,
 7411    row: DisplayRow,
 7412    line_height: Pixels,
 7413    gutter_dimensions: &GutterDimensions,
 7414    scroll_pixel_position: gpui::Point<Pixels>,
 7415    gutter_hitbox: &Hitbox,
 7416    display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 7417    window: &mut Window,
 7418    cx: &mut App,
 7419) -> AnyElement {
 7420    let mut button = button.into_any_element();
 7421
 7422    let available_space = size(
 7423        AvailableSpace::MinContent,
 7424        AvailableSpace::Definite(line_height),
 7425    );
 7426    let indicator_size = button.layout_as_root(available_space, window, cx);
 7427
 7428    let blame_width = gutter_dimensions.git_blame_entries_width;
 7429    let gutter_width = display_hunks
 7430        .binary_search_by(|(hunk, _)| match hunk {
 7431            DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
 7432            DisplayDiffHunk::Unfolded {
 7433                display_row_range, ..
 7434            } => {
 7435                if display_row_range.end <= row {
 7436                    Ordering::Less
 7437                } else if display_row_range.start > row {
 7438                    Ordering::Greater
 7439                } else {
 7440                    Ordering::Equal
 7441                }
 7442            }
 7443        })
 7444        .ok()
 7445        .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
 7446    let left_offset = blame_width.max(gutter_width).unwrap_or_default();
 7447
 7448    let mut x = left_offset;
 7449    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
 7450        - indicator_size.width
 7451        - left_offset;
 7452    x += available_width / 2.;
 7453
 7454    let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
 7455    y += (line_height - indicator_size.height) / 2.;
 7456
 7457    button.prepaint_as_root(
 7458        gutter_hitbox.origin + point(x, y),
 7459        available_space,
 7460        window,
 7461        cx,
 7462    );
 7463    button
 7464}
 7465
 7466fn render_inline_blame_entry(
 7467    blame_entry: BlameEntry,
 7468    style: &EditorStyle,
 7469    cx: &mut App,
 7470) -> Option<AnyElement> {
 7471    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 7472    renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
 7473}
 7474
 7475fn render_blame_entry_popover(
 7476    blame_entry: BlameEntry,
 7477    scroll_handle: ScrollHandle,
 7478    commit_message: Option<ParsedCommitMessage>,
 7479    markdown: Entity<Markdown>,
 7480    workspace: WeakEntity<Workspace>,
 7481    blame: &Entity<GitBlame>,
 7482    buffer: BufferId,
 7483    window: &mut Window,
 7484    cx: &mut App,
 7485) -> Option<AnyElement> {
 7486    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 7487    let blame = blame.read(cx);
 7488    let repository = blame.repository(cx, buffer)?;
 7489    renderer.render_blame_entry_popover(
 7490        blame_entry,
 7491        scroll_handle,
 7492        commit_message,
 7493        markdown,
 7494        repository,
 7495        workspace,
 7496        window,
 7497        cx,
 7498    )
 7499}
 7500
 7501fn render_blame_entry(
 7502    ix: usize,
 7503    blame: &Entity<GitBlame>,
 7504    blame_entry: BlameEntry,
 7505    style: &EditorStyle,
 7506    last_used_color: &mut Option<(PlayerColor, Oid)>,
 7507    editor: Entity<Editor>,
 7508    workspace: Entity<Workspace>,
 7509    buffer: BufferId,
 7510    renderer: Arc<dyn BlameRenderer>,
 7511    cx: &mut App,
 7512) -> Option<AnyElement> {
 7513    let mut sha_color = cx
 7514        .theme()
 7515        .players()
 7516        .color_for_participant(blame_entry.sha.into());
 7517
 7518    // If the last color we used is the same as the one we get for this line, but
 7519    // the commit SHAs are different, then we try again to get a different color.
 7520    match *last_used_color {
 7521        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
 7522            let index: u32 = blame_entry.sha.into();
 7523            sha_color = cx.theme().players().color_for_participant(index + 1);
 7524        }
 7525        _ => {}
 7526    };
 7527    last_used_color.replace((sha_color, blame_entry.sha));
 7528
 7529    let blame = blame.read(cx);
 7530    let details = blame.details_for_entry(buffer, &blame_entry);
 7531    let repository = blame.repository(cx, buffer)?;
 7532    renderer.render_blame_entry(
 7533        &style.text,
 7534        blame_entry,
 7535        details,
 7536        repository,
 7537        workspace.downgrade(),
 7538        editor,
 7539        ix,
 7540        sha_color.cursor,
 7541        cx,
 7542    )
 7543}
 7544
 7545#[derive(Debug)]
 7546pub(crate) struct LineWithInvisibles {
 7547    fragments: SmallVec<[LineFragment; 1]>,
 7548    invisibles: Vec<Invisible>,
 7549    len: usize,
 7550    pub(crate) width: Pixels,
 7551    font_size: Pixels,
 7552}
 7553
 7554enum LineFragment {
 7555    Text(ShapedLine),
 7556    Element {
 7557        id: ChunkRendererId,
 7558        element: Option<AnyElement>,
 7559        size: Size<Pixels>,
 7560        len: usize,
 7561    },
 7562}
 7563
 7564impl fmt::Debug for LineFragment {
 7565    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 7566        match self {
 7567            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
 7568            LineFragment::Element { size, len, .. } => f
 7569                .debug_struct("Element")
 7570                .field("size", size)
 7571                .field("len", len)
 7572                .finish(),
 7573        }
 7574    }
 7575}
 7576
 7577impl LineWithInvisibles {
 7578    fn from_chunks<'a>(
 7579        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
 7580        editor_style: &EditorStyle,
 7581        max_line_len: usize,
 7582        max_line_count: usize,
 7583        editor_mode: &EditorMode,
 7584        text_width: Pixels,
 7585        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 7586        bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
 7587        window: &mut Window,
 7588        cx: &mut App,
 7589    ) -> Vec<Self> {
 7590        let text_style = &editor_style.text;
 7591        let mut layouts = Vec::with_capacity(max_line_count);
 7592        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
 7593        let mut line = String::new();
 7594        let mut invisibles = Vec::new();
 7595        let mut width = Pixels::ZERO;
 7596        let mut len = 0;
 7597        let mut styles = Vec::new();
 7598        let mut non_whitespace_added = false;
 7599        let mut row = 0;
 7600        let mut line_exceeded_max_len = false;
 7601        let font_size = text_style.font_size.to_pixels(window.rem_size());
 7602        let min_contrast = EditorSettings::get_global(cx).minimum_contrast_for_highlights;
 7603
 7604        let ellipsis = SharedString::from("β‹―");
 7605
 7606        for highlighted_chunk in chunks.chain([HighlightedChunk {
 7607            text: "\n",
 7608            style: None,
 7609            is_tab: false,
 7610            is_inlay: false,
 7611            replacement: None,
 7612        }]) {
 7613            if let Some(replacement) = highlighted_chunk.replacement {
 7614                if !line.is_empty() {
 7615                    let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
 7616                    let text_runs: &[TextRun] = if segments.is_empty() {
 7617                        &styles
 7618                    } else {
 7619                        &Self::split_runs_by_bg_segments(&styles, segments, min_contrast)
 7620                    };
 7621                    let shaped_line = window.text_system().shape_line(
 7622                        line.clone().into(),
 7623                        font_size,
 7624                        text_runs,
 7625                        None,
 7626                    );
 7627                    width += shaped_line.width;
 7628                    len += shaped_line.len;
 7629                    fragments.push(LineFragment::Text(shaped_line));
 7630                    line.clear();
 7631                    styles.clear();
 7632                }
 7633
 7634                match replacement {
 7635                    ChunkReplacement::Renderer(renderer) => {
 7636                        let available_width = if renderer.constrain_width {
 7637                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
 7638                                ellipsis.clone()
 7639                            } else {
 7640                                SharedString::from(Arc::from(highlighted_chunk.text))
 7641                            };
 7642                            let shaped_line = window.text_system().shape_line(
 7643                                chunk,
 7644                                font_size,
 7645                                &[text_style.to_run(highlighted_chunk.text.len())],
 7646                                None,
 7647                            );
 7648                            AvailableSpace::Definite(shaped_line.width)
 7649                        } else {
 7650                            AvailableSpace::MinContent
 7651                        };
 7652
 7653                        let mut element = (renderer.render)(&mut ChunkRendererContext {
 7654                            context: cx,
 7655                            window,
 7656                            max_width: text_width,
 7657                        });
 7658                        let line_height = text_style.line_height_in_pixels(window.rem_size());
 7659                        let size = element.layout_as_root(
 7660                            size(available_width, AvailableSpace::Definite(line_height)),
 7661                            window,
 7662                            cx,
 7663                        );
 7664
 7665                        width += size.width;
 7666                        len += highlighted_chunk.text.len();
 7667                        fragments.push(LineFragment::Element {
 7668                            id: renderer.id,
 7669                            element: Some(element),
 7670                            size,
 7671                            len: highlighted_chunk.text.len(),
 7672                        });
 7673                    }
 7674                    ChunkReplacement::Str(x) => {
 7675                        let text_style = if let Some(style) = highlighted_chunk.style {
 7676                            Cow::Owned(text_style.clone().highlight(style))
 7677                        } else {
 7678                            Cow::Borrowed(text_style)
 7679                        };
 7680
 7681                        let run = TextRun {
 7682                            len: x.len(),
 7683                            font: text_style.font(),
 7684                            color: text_style.color,
 7685                            background_color: text_style.background_color,
 7686                            underline: text_style.underline,
 7687                            strikethrough: text_style.strikethrough,
 7688                        };
 7689                        let line_layout = window
 7690                            .text_system()
 7691                            .shape_line(x, font_size, &[run], None)
 7692                            .with_len(highlighted_chunk.text.len());
 7693
 7694                        width += line_layout.width;
 7695                        len += highlighted_chunk.text.len();
 7696                        fragments.push(LineFragment::Text(line_layout))
 7697                    }
 7698                }
 7699            } else {
 7700                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
 7701                    if ix > 0 {
 7702                        let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
 7703                        let text_runs = if segments.is_empty() {
 7704                            &styles
 7705                        } else {
 7706                            &Self::split_runs_by_bg_segments(&styles, segments, min_contrast)
 7707                        };
 7708                        let shaped_line = window.text_system().shape_line(
 7709                            line.clone().into(),
 7710                            font_size,
 7711                            text_runs,
 7712                            None,
 7713                        );
 7714                        width += shaped_line.width;
 7715                        len += shaped_line.len;
 7716                        fragments.push(LineFragment::Text(shaped_line));
 7717                        layouts.push(Self {
 7718                            width: mem::take(&mut width),
 7719                            len: mem::take(&mut len),
 7720                            fragments: mem::take(&mut fragments),
 7721                            invisibles: std::mem::take(&mut invisibles),
 7722                            font_size,
 7723                        });
 7724
 7725                        line.clear();
 7726                        styles.clear();
 7727                        row += 1;
 7728                        line_exceeded_max_len = false;
 7729                        non_whitespace_added = false;
 7730                        if row == max_line_count {
 7731                            return layouts;
 7732                        }
 7733                    }
 7734
 7735                    if !line_chunk.is_empty() && !line_exceeded_max_len {
 7736                        let text_style = if let Some(style) = highlighted_chunk.style {
 7737                            Cow::Owned(text_style.clone().highlight(style))
 7738                        } else {
 7739                            Cow::Borrowed(text_style)
 7740                        };
 7741
 7742                        if line.len() + line_chunk.len() > max_line_len {
 7743                            let mut chunk_len = max_line_len - line.len();
 7744                            while !line_chunk.is_char_boundary(chunk_len) {
 7745                                chunk_len -= 1;
 7746                            }
 7747                            line_chunk = &line_chunk[..chunk_len];
 7748                            line_exceeded_max_len = true;
 7749                        }
 7750
 7751                        styles.push(TextRun {
 7752                            len: line_chunk.len(),
 7753                            font: text_style.font(),
 7754                            color: text_style.color,
 7755                            background_color: text_style.background_color,
 7756                            underline: text_style.underline,
 7757                            strikethrough: text_style.strikethrough,
 7758                        });
 7759
 7760                        if editor_mode.is_full() && !highlighted_chunk.is_inlay {
 7761                            // Line wrap pads its contents with fake whitespaces,
 7762                            // avoid printing them
 7763                            let is_soft_wrapped = is_row_soft_wrapped(row);
 7764                            if highlighted_chunk.is_tab {
 7765                                if non_whitespace_added || !is_soft_wrapped {
 7766                                    invisibles.push(Invisible::Tab {
 7767                                        line_start_offset: line.len(),
 7768                                        line_end_offset: line.len() + line_chunk.len(),
 7769                                    });
 7770                                }
 7771                            } else {
 7772                                invisibles.extend(line_chunk.char_indices().filter_map(
 7773                                    |(index, c)| {
 7774                                        let is_whitespace = c.is_whitespace();
 7775                                        non_whitespace_added |= !is_whitespace;
 7776                                        if is_whitespace
 7777                                            && (non_whitespace_added || !is_soft_wrapped)
 7778                                        {
 7779                                            Some(Invisible::Whitespace {
 7780                                                line_offset: line.len() + index,
 7781                                            })
 7782                                        } else {
 7783                                            None
 7784                                        }
 7785                                    },
 7786                                ))
 7787                            }
 7788                        }
 7789
 7790                        line.push_str(line_chunk);
 7791                    }
 7792                }
 7793            }
 7794        }
 7795
 7796        layouts
 7797    }
 7798
 7799    /// Takes text runs and non-overlapping left-to-right background ranges with color.
 7800    /// Returns new text runs with adjusted contrast as per background ranges.
 7801    fn split_runs_by_bg_segments(
 7802        text_runs: &[TextRun],
 7803        bg_segments: &[(Range<DisplayPoint>, Hsla)],
 7804        min_contrast: f32,
 7805    ) -> Vec<TextRun> {
 7806        let mut output_runs: Vec<TextRun> = Vec::with_capacity(text_runs.len());
 7807        let mut line_col = 0usize;
 7808        let mut segment_ix = 0usize;
 7809
 7810        for text_run in text_runs.iter() {
 7811            let run_start_col = line_col;
 7812            let run_end_col = run_start_col + text_run.len;
 7813            while segment_ix < bg_segments.len()
 7814                && (bg_segments[segment_ix].0.end.column() as usize) <= run_start_col
 7815            {
 7816                segment_ix += 1;
 7817            }
 7818            let mut cursor_col = run_start_col;
 7819            let mut local_segment_ix = segment_ix;
 7820            while local_segment_ix < bg_segments.len() {
 7821                let (range, segment_color) = &bg_segments[local_segment_ix];
 7822                let segment_start_col = range.start.column() as usize;
 7823                let segment_end_col = range.end.column() as usize;
 7824                if segment_start_col >= run_end_col {
 7825                    break;
 7826                }
 7827                if segment_start_col > cursor_col {
 7828                    let span_len = segment_start_col - cursor_col;
 7829                    output_runs.push(TextRun {
 7830                        len: span_len,
 7831                        font: text_run.font.clone(),
 7832                        color: text_run.color,
 7833                        background_color: text_run.background_color,
 7834                        underline: text_run.underline,
 7835                        strikethrough: text_run.strikethrough,
 7836                    });
 7837                    cursor_col = segment_start_col;
 7838                }
 7839                let segment_slice_end_col = segment_end_col.min(run_end_col);
 7840                if segment_slice_end_col > cursor_col {
 7841                    let new_text_color =
 7842                        ensure_minimum_contrast(text_run.color, *segment_color, min_contrast);
 7843                    output_runs.push(TextRun {
 7844                        len: segment_slice_end_col - cursor_col,
 7845                        font: text_run.font.clone(),
 7846                        color: new_text_color,
 7847                        background_color: text_run.background_color,
 7848                        underline: text_run.underline,
 7849                        strikethrough: text_run.strikethrough,
 7850                    });
 7851                    cursor_col = segment_slice_end_col;
 7852                }
 7853                if segment_end_col >= run_end_col {
 7854                    break;
 7855                }
 7856                local_segment_ix += 1;
 7857            }
 7858            if cursor_col < run_end_col {
 7859                output_runs.push(TextRun {
 7860                    len: run_end_col - cursor_col,
 7861                    font: text_run.font.clone(),
 7862                    color: text_run.color,
 7863                    background_color: text_run.background_color,
 7864                    underline: text_run.underline,
 7865                    strikethrough: text_run.strikethrough,
 7866                });
 7867            }
 7868            line_col = run_end_col;
 7869            segment_ix = local_segment_ix;
 7870        }
 7871        output_runs
 7872    }
 7873
 7874    fn prepaint(
 7875        &mut self,
 7876        line_height: Pixels,
 7877        scroll_pixel_position: gpui::Point<Pixels>,
 7878        row: DisplayRow,
 7879        content_origin: gpui::Point<Pixels>,
 7880        line_elements: &mut SmallVec<[AnyElement; 1]>,
 7881        window: &mut Window,
 7882        cx: &mut App,
 7883    ) {
 7884        let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
 7885        let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
 7886        for fragment in &mut self.fragments {
 7887            match fragment {
 7888                LineFragment::Text(line) => {
 7889                    fragment_origin.x += line.width;
 7890                }
 7891                LineFragment::Element { element, size, .. } => {
 7892                    let mut element = element
 7893                        .take()
 7894                        .expect("you can't prepaint LineWithInvisibles twice");
 7895
 7896                    // Center the element vertically within the line.
 7897                    let mut element_origin = fragment_origin;
 7898                    element_origin.y += (line_height - size.height) / 2.;
 7899                    element.prepaint_at(element_origin, window, cx);
 7900                    line_elements.push(element);
 7901
 7902                    fragment_origin.x += size.width;
 7903                }
 7904            }
 7905        }
 7906    }
 7907
 7908    fn draw(
 7909        &self,
 7910        layout: &EditorLayout,
 7911        row: DisplayRow,
 7912        content_origin: gpui::Point<Pixels>,
 7913        whitespace_setting: ShowWhitespaceSetting,
 7914        selection_ranges: &[Range<DisplayPoint>],
 7915        window: &mut Window,
 7916        cx: &mut App,
 7917    ) {
 7918        let line_height = layout.position_map.line_height;
 7919        let line_y = line_height
 7920            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
 7921
 7922        let mut fragment_origin =
 7923            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
 7924
 7925        for fragment in &self.fragments {
 7926            match fragment {
 7927                LineFragment::Text(line) => {
 7928                    line.paint(fragment_origin, line_height, window, cx)
 7929                        .log_err();
 7930                    fragment_origin.x += line.width;
 7931                }
 7932                LineFragment::Element { size, .. } => {
 7933                    fragment_origin.x += size.width;
 7934                }
 7935            }
 7936        }
 7937
 7938        self.draw_invisibles(
 7939            selection_ranges,
 7940            layout,
 7941            content_origin,
 7942            line_y,
 7943            row,
 7944            line_height,
 7945            whitespace_setting,
 7946            window,
 7947            cx,
 7948        );
 7949    }
 7950
 7951    fn draw_background(
 7952        &self,
 7953        layout: &EditorLayout,
 7954        row: DisplayRow,
 7955        content_origin: gpui::Point<Pixels>,
 7956        window: &mut Window,
 7957        cx: &mut App,
 7958    ) {
 7959        let line_height = layout.position_map.line_height;
 7960        let line_y = line_height
 7961            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
 7962
 7963        let mut fragment_origin =
 7964            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
 7965
 7966        for fragment in &self.fragments {
 7967            match fragment {
 7968                LineFragment::Text(line) => {
 7969                    line.paint_background(fragment_origin, line_height, window, cx)
 7970                        .log_err();
 7971                    fragment_origin.x += line.width;
 7972                }
 7973                LineFragment::Element { size, .. } => {
 7974                    fragment_origin.x += size.width;
 7975                }
 7976            }
 7977        }
 7978    }
 7979
 7980    fn draw_invisibles(
 7981        &self,
 7982        selection_ranges: &[Range<DisplayPoint>],
 7983        layout: &EditorLayout,
 7984        content_origin: gpui::Point<Pixels>,
 7985        line_y: Pixels,
 7986        row: DisplayRow,
 7987        line_height: Pixels,
 7988        whitespace_setting: ShowWhitespaceSetting,
 7989        window: &mut Window,
 7990        cx: &mut App,
 7991    ) {
 7992        let extract_whitespace_info = |invisible: &Invisible| {
 7993            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
 7994                Invisible::Tab {
 7995                    line_start_offset,
 7996                    line_end_offset,
 7997                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
 7998                Invisible::Whitespace { line_offset } => {
 7999                    (*line_offset, line_offset + 1, &layout.space_invisible)
 8000                }
 8001            };
 8002
 8003            let x_offset = self.x_for_index(token_offset);
 8004            let invisible_offset =
 8005                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
 8006            let origin = content_origin
 8007                + gpui::point(
 8008                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
 8009                    line_y,
 8010                );
 8011
 8012            (
 8013                [token_offset, token_end_offset],
 8014                Box::new(move |window: &mut Window, cx: &mut App| {
 8015                    invisible_symbol
 8016                        .paint(origin, line_height, window, cx)
 8017                        .log_err();
 8018                }),
 8019            )
 8020        };
 8021
 8022        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
 8023        match whitespace_setting {
 8024            ShowWhitespaceSetting::None => (),
 8025            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
 8026            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
 8027                let invisible_point = DisplayPoint::new(row, start as u32);
 8028                if !selection_ranges
 8029                    .iter()
 8030                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
 8031                {
 8032                    return;
 8033                }
 8034
 8035                paint(window, cx);
 8036            }),
 8037
 8038            ShowWhitespaceSetting::Trailing => {
 8039                let mut previous_start = self.len;
 8040                for ([start, end], paint) in invisible_iter.rev() {
 8041                    if previous_start != end {
 8042                        break;
 8043                    }
 8044                    previous_start = start;
 8045                    paint(window, cx);
 8046                }
 8047            }
 8048
 8049            // For a whitespace to be on a boundary, any of the following conditions need to be met:
 8050            // - It is a tab
 8051            // - It is adjacent to an edge (start or end)
 8052            // - It is adjacent to a whitespace (left or right)
 8053            ShowWhitespaceSetting::Boundary => {
 8054                // 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
 8055                // the above cases.
 8056                // Note: We zip in the original `invisibles` to check for tab equality
 8057                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
 8058                for (([start, end], paint), invisible) in
 8059                    invisible_iter.zip_eq(self.invisibles.iter())
 8060                {
 8061                    let should_render = match (&last_seen, invisible) {
 8062                        (_, Invisible::Tab { .. }) => true,
 8063                        (Some((_, last_end, _)), _) => *last_end == start,
 8064                        _ => false,
 8065                    };
 8066
 8067                    if should_render || start == 0 || end == self.len {
 8068                        paint(window, cx);
 8069
 8070                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
 8071                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
 8072                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
 8073                            // Note that we need to make sure that the last one is actually adjacent
 8074                            if !should_render_last && last_end == start {
 8075                                paint_last(window, cx);
 8076                            }
 8077                        }
 8078                    }
 8079
 8080                    // Manually render anything within a selection
 8081                    let invisible_point = DisplayPoint::new(row, start as u32);
 8082                    if selection_ranges.iter().any(|region| {
 8083                        region.start <= invisible_point && invisible_point < region.end
 8084                    }) {
 8085                        paint(window, cx);
 8086                    }
 8087
 8088                    last_seen = Some((should_render, end, paint));
 8089                }
 8090            }
 8091        }
 8092    }
 8093
 8094    pub fn x_for_index(&self, index: usize) -> Pixels {
 8095        let mut fragment_start_x = Pixels::ZERO;
 8096        let mut fragment_start_index = 0;
 8097
 8098        for fragment in &self.fragments {
 8099            match fragment {
 8100                LineFragment::Text(shaped_line) => {
 8101                    let fragment_end_index = fragment_start_index + shaped_line.len;
 8102                    if index < fragment_end_index {
 8103                        return fragment_start_x
 8104                            + shaped_line.x_for_index(index - fragment_start_index);
 8105                    }
 8106                    fragment_start_x += shaped_line.width;
 8107                    fragment_start_index = fragment_end_index;
 8108                }
 8109                LineFragment::Element { len, size, .. } => {
 8110                    let fragment_end_index = fragment_start_index + len;
 8111                    if index < fragment_end_index {
 8112                        return fragment_start_x;
 8113                    }
 8114                    fragment_start_x += size.width;
 8115                    fragment_start_index = fragment_end_index;
 8116                }
 8117            }
 8118        }
 8119
 8120        fragment_start_x
 8121    }
 8122
 8123    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
 8124        let mut fragment_start_x = Pixels::ZERO;
 8125        let mut fragment_start_index = 0;
 8126
 8127        for fragment in &self.fragments {
 8128            match fragment {
 8129                LineFragment::Text(shaped_line) => {
 8130                    let fragment_end_x = fragment_start_x + shaped_line.width;
 8131                    if x < fragment_end_x {
 8132                        return Some(
 8133                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
 8134                        );
 8135                    }
 8136                    fragment_start_x = fragment_end_x;
 8137                    fragment_start_index += shaped_line.len;
 8138                }
 8139                LineFragment::Element { len, size, .. } => {
 8140                    let fragment_end_x = fragment_start_x + size.width;
 8141                    if x < fragment_end_x {
 8142                        return Some(fragment_start_index);
 8143                    }
 8144                    fragment_start_index += len;
 8145                    fragment_start_x = fragment_end_x;
 8146                }
 8147            }
 8148        }
 8149
 8150        None
 8151    }
 8152
 8153    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
 8154        let mut fragment_start_index = 0;
 8155
 8156        for fragment in &self.fragments {
 8157            match fragment {
 8158                LineFragment::Text(shaped_line) => {
 8159                    let fragment_end_index = fragment_start_index + shaped_line.len;
 8160                    if index < fragment_end_index {
 8161                        return shaped_line.font_id_for_index(index - fragment_start_index);
 8162                    }
 8163                    fragment_start_index = fragment_end_index;
 8164                }
 8165                LineFragment::Element { len, .. } => {
 8166                    let fragment_end_index = fragment_start_index + len;
 8167                    if index < fragment_end_index {
 8168                        return None;
 8169                    }
 8170                    fragment_start_index = fragment_end_index;
 8171                }
 8172            }
 8173        }
 8174
 8175        None
 8176    }
 8177}
 8178
 8179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 8180enum Invisible {
 8181    /// A tab character
 8182    ///
 8183    /// A tab character is internally represented by spaces (configured by the user's tab width)
 8184    /// aligned to the nearest column, so it's necessary to store the start and end offset for
 8185    /// adjacency checks.
 8186    Tab {
 8187        line_start_offset: usize,
 8188        line_end_offset: usize,
 8189    },
 8190    Whitespace {
 8191        line_offset: usize,
 8192    },
 8193}
 8194
 8195impl EditorElement {
 8196    /// Returns the rem size to use when rendering the [`EditorElement`].
 8197    ///
 8198    /// This allows UI elements to scale based on the `buffer_font_size`.
 8199    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
 8200        match self.editor.read(cx).mode {
 8201            EditorMode::Full {
 8202                scale_ui_elements_with_buffer_font_size: true,
 8203                ..
 8204            }
 8205            | EditorMode::Minimap { .. } => {
 8206                let buffer_font_size = self.style.text.font_size;
 8207                match buffer_font_size {
 8208                    AbsoluteLength::Pixels(pixels) => {
 8209                        let rem_size_scale = {
 8210                            // Our default UI font size is 14px on a 16px base scale.
 8211                            // This means the default UI font size is 0.875rems.
 8212                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
 8213
 8214                            // We then determine the delta between a single rem and the default font
 8215                            // size scale.
 8216                            let default_font_size_delta = 1. - default_font_size_scale;
 8217
 8218                            // Finally, we add this delta to 1rem to get the scale factor that
 8219                            // should be used to scale up the UI.
 8220                            1. + default_font_size_delta
 8221                        };
 8222
 8223                        Some(pixels * rem_size_scale)
 8224                    }
 8225                    AbsoluteLength::Rems(rems) => {
 8226                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
 8227                    }
 8228                }
 8229            }
 8230            // We currently use single-line and auto-height editors in UI contexts,
 8231            // so we don't want to scale everything with the buffer font size, as it
 8232            // ends up looking off.
 8233            _ => None,
 8234        }
 8235    }
 8236
 8237    fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
 8238        if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
 8239            parent.upgrade()
 8240        } else {
 8241            Some(self.editor.clone())
 8242        }
 8243    }
 8244}
 8245
 8246impl Element for EditorElement {
 8247    type RequestLayoutState = ();
 8248    type PrepaintState = EditorLayout;
 8249
 8250    fn id(&self) -> Option<ElementId> {
 8251        None
 8252    }
 8253
 8254    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
 8255        None
 8256    }
 8257
 8258    fn request_layout(
 8259        &mut self,
 8260        _: Option<&GlobalElementId>,
 8261        _inspector_id: Option<&gpui::InspectorElementId>,
 8262        window: &mut Window,
 8263        cx: &mut App,
 8264    ) -> (gpui::LayoutId, ()) {
 8265        let rem_size = self.rem_size(cx);
 8266        window.with_rem_size(rem_size, |window| {
 8267            self.editor.update(cx, |editor, cx| {
 8268                editor.set_style(self.style.clone(), window, cx);
 8269
 8270                let layout_id = match editor.mode {
 8271                    EditorMode::SingleLine => {
 8272                        let rem_size = window.rem_size();
 8273                        let height = self.style.text.line_height_in_pixels(rem_size);
 8274                        let mut style = Style::default();
 8275                        style.size.height = height.into();
 8276                        style.size.width = relative(1.).into();
 8277                        window.request_layout(style, None, cx)
 8278                    }
 8279                    EditorMode::AutoHeight {
 8280                        min_lines,
 8281                        max_lines,
 8282                    } => {
 8283                        let editor_handle = cx.entity();
 8284                        let max_line_number_width =
 8285                            self.max_line_number_width(&editor.snapshot(window, cx), window);
 8286                        window.request_measured_layout(
 8287                            Style::default(),
 8288                            move |known_dimensions, available_space, window, cx| {
 8289                                editor_handle
 8290                                    .update(cx, |editor, cx| {
 8291                                        compute_auto_height_layout(
 8292                                            editor,
 8293                                            min_lines,
 8294                                            max_lines,
 8295                                            max_line_number_width,
 8296                                            known_dimensions,
 8297                                            available_space.width,
 8298                                            window,
 8299                                            cx,
 8300                                        )
 8301                                    })
 8302                                    .unwrap_or_default()
 8303                            },
 8304                        )
 8305                    }
 8306                    EditorMode::Minimap { .. } => {
 8307                        let mut style = Style::default();
 8308                        style.size.width = relative(1.).into();
 8309                        style.size.height = relative(1.).into();
 8310                        window.request_layout(style, None, cx)
 8311                    }
 8312                    EditorMode::Full {
 8313                        sized_by_content, ..
 8314                    } => {
 8315                        let mut style = Style::default();
 8316                        style.size.width = relative(1.).into();
 8317                        if sized_by_content {
 8318                            let snapshot = editor.snapshot(window, cx);
 8319                            let line_height =
 8320                                self.style.text.line_height_in_pixels(window.rem_size());
 8321                            let scroll_height =
 8322                                (snapshot.max_point().row().next_row().0 as f32) * line_height;
 8323                            style.size.height = scroll_height.into();
 8324                        } else {
 8325                            style.size.height = relative(1.).into();
 8326                        }
 8327                        window.request_layout(style, None, cx)
 8328                    }
 8329                };
 8330
 8331                (layout_id, ())
 8332            })
 8333        })
 8334    }
 8335
 8336    fn prepaint(
 8337        &mut self,
 8338        _: Option<&GlobalElementId>,
 8339        _inspector_id: Option<&gpui::InspectorElementId>,
 8340        bounds: Bounds<Pixels>,
 8341        _: &mut Self::RequestLayoutState,
 8342        window: &mut Window,
 8343        cx: &mut App,
 8344    ) -> Self::PrepaintState {
 8345        let text_style = TextStyleRefinement {
 8346            font_size: Some(self.style.text.font_size),
 8347            line_height: Some(self.style.text.line_height),
 8348            ..Default::default()
 8349        };
 8350
 8351        let is_minimap = self.editor.read(cx).mode.is_minimap();
 8352
 8353        if !is_minimap {
 8354            let focus_handle = self.editor.focus_handle(cx);
 8355            window.set_view_id(self.editor.entity_id());
 8356            window.set_focus_handle(&focus_handle, cx);
 8357        }
 8358
 8359        let rem_size = self.rem_size(cx);
 8360        window.with_rem_size(rem_size, |window| {
 8361            window.with_text_style(Some(text_style), |window| {
 8362                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 8363                    let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
 8364                        (editor.snapshot(window, cx), editor.read_only(cx))
 8365                    });
 8366                    let style = &self.style;
 8367
 8368                    let rem_size = window.rem_size();
 8369                    let font_id = window.text_system().resolve_font(&style.text.font());
 8370                    let font_size = style.text.font_size.to_pixels(rem_size);
 8371                    let line_height = style.text.line_height_in_pixels(rem_size);
 8372                    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
 8373                    let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
 8374                    let glyph_grid_cell = size(em_advance, line_height);
 8375
 8376                    let gutter_dimensions = snapshot
 8377                        .gutter_dimensions(
 8378                            font_id,
 8379                            font_size,
 8380                            self.max_line_number_width(&snapshot, window),
 8381                            cx,
 8382                        )
 8383                        .or_else(|| {
 8384                            self.editor.read(cx).offset_content.then(|| {
 8385                                GutterDimensions::default_with_margin(font_id, font_size, cx)
 8386                            })
 8387                        })
 8388                        .unwrap_or_default();
 8389                    let text_width = bounds.size.width - gutter_dimensions.width;
 8390
 8391                    let settings = EditorSettings::get_global(cx);
 8392                    let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
 8393                    let vertical_scrollbar_width = (scrollbars_shown
 8394                        && settings.scrollbar.axes.vertical
 8395                        && self.editor.read(cx).show_scrollbars.vertical)
 8396                        .then_some(style.scrollbar_width)
 8397                        .unwrap_or_default();
 8398                    let minimap_width = self
 8399                        .get_minimap_width(
 8400                            &settings.minimap,
 8401                            scrollbars_shown,
 8402                            text_width,
 8403                            em_width,
 8404                            font_size,
 8405                            rem_size,
 8406                            cx,
 8407                        )
 8408                        .unwrap_or_default();
 8409
 8410                    let right_margin = minimap_width + vertical_scrollbar_width;
 8411
 8412                    let editor_width =
 8413                        text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
 8414                    let editor_margins = EditorMargins {
 8415                        gutter: gutter_dimensions,
 8416                        right: right_margin,
 8417                    };
 8418
 8419                    snapshot = self.editor.update(cx, |editor, cx| {
 8420                        editor.last_bounds = Some(bounds);
 8421                        editor.gutter_dimensions = gutter_dimensions;
 8422                        editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
 8423                        editor.set_visible_column_count(editor_width / em_advance);
 8424
 8425                        if matches!(
 8426                            editor.mode,
 8427                            EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
 8428                        ) {
 8429                            snapshot
 8430                        } else {
 8431                            let wrap_width_for = |column: u32| (column as f32 * em_advance).ceil();
 8432                            let wrap_width = match editor.soft_wrap_mode(cx) {
 8433                                SoftWrap::GitDiff => None,
 8434                                SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
 8435                                SoftWrap::EditorWidth => Some(editor_width),
 8436                                SoftWrap::Column(column) => Some(wrap_width_for(column)),
 8437                                SoftWrap::Bounded(column) => {
 8438                                    Some(editor_width.min(wrap_width_for(column)))
 8439                                }
 8440                            };
 8441
 8442                            if editor.set_wrap_width(wrap_width, cx) {
 8443                                editor.snapshot(window, cx)
 8444                            } else {
 8445                                snapshot
 8446                            }
 8447                        }
 8448                    });
 8449
 8450                    let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
 8451                    let gutter_hitbox = window.insert_hitbox(
 8452                        gutter_bounds(bounds, gutter_dimensions),
 8453                        HitboxBehavior::Normal,
 8454                    );
 8455                    let text_hitbox = window.insert_hitbox(
 8456                        Bounds {
 8457                            origin: gutter_hitbox.top_right(),
 8458                            size: size(text_width, bounds.size.height),
 8459                        },
 8460                        HitboxBehavior::Normal,
 8461                    );
 8462
 8463                    // Offset the content_bounds from the text_bounds by the gutter margin (which
 8464                    // is roughly half a character wide) to make hit testing work more like how we want.
 8465                    let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
 8466                    let content_origin = text_hitbox.origin + content_offset;
 8467
 8468                    let height_in_lines = bounds.size.height / line_height;
 8469                    let max_row = snapshot.max_point().row().as_f32();
 8470
 8471                    // The max scroll position for the top of the window
 8472                    let max_scroll_top = if matches!(
 8473                        snapshot.mode,
 8474                        EditorMode::SingleLine
 8475                            | EditorMode::AutoHeight { .. }
 8476                            | EditorMode::Full {
 8477                                sized_by_content: true,
 8478                                ..
 8479                            }
 8480                    ) {
 8481                        (max_row - height_in_lines + 1.).max(0.)
 8482                    } else {
 8483                        let settings = EditorSettings::get_global(cx);
 8484                        match settings.scroll_beyond_last_line {
 8485                            ScrollBeyondLastLine::OnePage => max_row,
 8486                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
 8487                            ScrollBeyondLastLine::VerticalScrollMargin => {
 8488                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
 8489                                    .max(0.)
 8490                            }
 8491                        }
 8492                    };
 8493
 8494                    let (
 8495                        autoscroll_request,
 8496                        autoscroll_containing_element,
 8497                        needs_horizontal_autoscroll,
 8498                    ) = self.editor.update(cx, |editor, cx| {
 8499                        let autoscroll_request = editor.scroll_manager.take_autoscroll_request();
 8500
 8501                        let autoscroll_containing_element =
 8502                            autoscroll_request.is_some() || editor.has_pending_selection();
 8503
 8504                        let (needs_horizontal_autoscroll, was_scrolled) = editor
 8505                            .autoscroll_vertically(
 8506                                bounds,
 8507                                line_height,
 8508                                max_scroll_top,
 8509                                autoscroll_request,
 8510                                window,
 8511                                cx,
 8512                            );
 8513                        if was_scrolled.0 {
 8514                            snapshot = editor.snapshot(window, cx);
 8515                        }
 8516                        (
 8517                            autoscroll_request,
 8518                            autoscroll_containing_element,
 8519                            needs_horizontal_autoscroll,
 8520                        )
 8521                    });
 8522
 8523                    let mut scroll_position = snapshot.scroll_position();
 8524                    // The scroll position is a fractional point, the whole number of which represents
 8525                    // the top of the window in terms of display rows.
 8526                    let start_row = DisplayRow(scroll_position.y as u32);
 8527                    let max_row = snapshot.max_point().row();
 8528                    let end_row = cmp::min(
 8529                        (scroll_position.y + height_in_lines).ceil() as u32,
 8530                        max_row.next_row().0,
 8531                    );
 8532                    let end_row = DisplayRow(end_row);
 8533
 8534                    let row_infos = snapshot
 8535                        .row_infos(start_row)
 8536                        .take((start_row..end_row).len())
 8537                        .collect::<Vec<RowInfo>>();
 8538                    let is_row_soft_wrapped = |row: usize| {
 8539                        row_infos
 8540                            .get(row)
 8541                            .is_none_or(|info| info.buffer_row.is_none())
 8542                    };
 8543
 8544                    let start_anchor = if start_row == Default::default() {
 8545                        Anchor::min()
 8546                    } else {
 8547                        snapshot.buffer_snapshot.anchor_before(
 8548                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
 8549                        )
 8550                    };
 8551                    let end_anchor = if end_row > max_row {
 8552                        Anchor::max()
 8553                    } else {
 8554                        snapshot.buffer_snapshot.anchor_before(
 8555                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
 8556                        )
 8557                    };
 8558
 8559                    let mut highlighted_rows = self
 8560                        .editor
 8561                        .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
 8562
 8563                    let is_light = cx.theme().appearance().is_light();
 8564
 8565                    for (ix, row_info) in row_infos.iter().enumerate() {
 8566                        let Some(diff_status) = row_info.diff_status else {
 8567                            continue;
 8568                        };
 8569
 8570                        let background_color = match diff_status.kind {
 8571                            DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
 8572                            DiffHunkStatusKind::Deleted => {
 8573                                cx.theme().colors().version_control_deleted
 8574                            }
 8575                            DiffHunkStatusKind::Modified => {
 8576                                debug_panic!("modified diff status for row info");
 8577                                continue;
 8578                            }
 8579                        };
 8580
 8581                        let hunk_opacity = if is_light { 0.16 } else { 0.12 };
 8582
 8583                        let hollow_highlight = LineHighlight {
 8584                            background: (background_color.opacity(if is_light {
 8585                                0.08
 8586                            } else {
 8587                                0.06
 8588                            }))
 8589                            .into(),
 8590                            border: Some(if is_light {
 8591                                background_color.opacity(0.48)
 8592                            } else {
 8593                                background_color.opacity(0.36)
 8594                            }),
 8595                            include_gutter: true,
 8596                            type_id: None,
 8597                        };
 8598
 8599                        let filled_highlight = LineHighlight {
 8600                            background: solid_background(background_color.opacity(hunk_opacity)),
 8601                            border: None,
 8602                            include_gutter: true,
 8603                            type_id: None,
 8604                        };
 8605
 8606                        let background = if Self::diff_hunk_hollow(diff_status, cx) {
 8607                            hollow_highlight
 8608                        } else {
 8609                            filled_highlight
 8610                        };
 8611
 8612                        highlighted_rows
 8613                            .entry(start_row + DisplayRow(ix as u32))
 8614                            .or_insert(background);
 8615                    }
 8616
 8617                    let highlighted_ranges = self
 8618                        .editor_with_selections(cx)
 8619                        .map(|editor| {
 8620                            editor.read(cx).background_highlights_in_range(
 8621                                start_anchor..end_anchor,
 8622                                &snapshot.display_snapshot,
 8623                                cx.theme(),
 8624                            )
 8625                        })
 8626                        .unwrap_or_default();
 8627                    let highlighted_gutter_ranges =
 8628                        self.editor.read(cx).gutter_highlights_in_range(
 8629                            start_anchor..end_anchor,
 8630                            &snapshot.display_snapshot,
 8631                            cx,
 8632                        );
 8633
 8634                    let document_colors = self
 8635                        .editor
 8636                        .read(cx)
 8637                        .colors
 8638                        .as_ref()
 8639                        .map(|colors| colors.editor_display_highlights(&snapshot));
 8640                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
 8641                        start_anchor..end_anchor,
 8642                        &snapshot.display_snapshot,
 8643                        cx,
 8644                    );
 8645
 8646                    let (local_selections, selected_buffer_ids): (
 8647                        Vec<Selection<Point>>,
 8648                        Vec<BufferId>,
 8649                    ) = self
 8650                        .editor_with_selections(cx)
 8651                        .map(|editor| {
 8652                            editor.update(cx, |editor, cx| {
 8653                                let all_selections = editor.selections.all::<Point>(cx);
 8654                                let selected_buffer_ids = if editor.is_singleton(cx) {
 8655                                    Vec::new()
 8656                                } else {
 8657                                    let mut selected_buffer_ids =
 8658                                        Vec::with_capacity(all_selections.len());
 8659
 8660                                    for selection in all_selections {
 8661                                        for buffer_id in snapshot
 8662                                            .buffer_snapshot
 8663                                            .buffer_ids_for_range(selection.range())
 8664                                        {
 8665                                            if selected_buffer_ids.last() != Some(&buffer_id) {
 8666                                                selected_buffer_ids.push(buffer_id);
 8667                                            }
 8668                                        }
 8669                                    }
 8670
 8671                                    selected_buffer_ids
 8672                                };
 8673
 8674                                let mut selections = editor
 8675                                    .selections
 8676                                    .disjoint_in_range(start_anchor..end_anchor, cx);
 8677                                selections.extend(editor.selections.pending(cx));
 8678
 8679                                (selections, selected_buffer_ids)
 8680                            })
 8681                        })
 8682                        .unwrap_or_default();
 8683
 8684                    let (selections, mut active_rows, newest_selection_head) = self
 8685                        .layout_selections(
 8686                            start_anchor,
 8687                            end_anchor,
 8688                            &local_selections,
 8689                            &snapshot,
 8690                            start_row,
 8691                            end_row,
 8692                            window,
 8693                            cx,
 8694                        );
 8695                    let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
 8696                        editor.active_breakpoints(start_row..end_row, window, cx)
 8697                    });
 8698                    for (display_row, (_, bp, state)) in &breakpoint_rows {
 8699                        if bp.is_enabled() && state.is_none_or(|s| s.verified) {
 8700                            active_rows.entry(*display_row).or_default().breakpoint = true;
 8701                        }
 8702                    }
 8703
 8704                    let line_numbers = self.layout_line_numbers(
 8705                        Some(&gutter_hitbox),
 8706                        gutter_dimensions,
 8707                        line_height,
 8708                        scroll_position,
 8709                        start_row..end_row,
 8710                        &row_infos,
 8711                        &active_rows,
 8712                        newest_selection_head,
 8713                        &snapshot,
 8714                        window,
 8715                        cx,
 8716                    );
 8717
 8718                    // We add the gutter breakpoint indicator to breakpoint_rows after painting
 8719                    // line numbers so we don't paint a line number debug accent color if a user
 8720                    // has their mouse over that line when a breakpoint isn't there
 8721                    self.editor.update(cx, |editor, _| {
 8722                        if let Some(phantom_breakpoint) = &mut editor
 8723                            .gutter_breakpoint_indicator
 8724                            .0
 8725                            .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
 8726                        {
 8727                            // Is there a non-phantom breakpoint on this line?
 8728                            phantom_breakpoint.collides_with_existing_breakpoint = true;
 8729                            breakpoint_rows
 8730                                .entry(phantom_breakpoint.display_row)
 8731                                .or_insert_with(|| {
 8732                                    let position = snapshot.display_point_to_anchor(
 8733                                        DisplayPoint::new(phantom_breakpoint.display_row, 0),
 8734                                        Bias::Right,
 8735                                    );
 8736                                    let breakpoint = Breakpoint::new_standard();
 8737                                    phantom_breakpoint.collides_with_existing_breakpoint = false;
 8738                                    (position, breakpoint, None)
 8739                                });
 8740                        }
 8741                    });
 8742
 8743                    let mut expand_toggles =
 8744                        window.with_element_namespace("expand_toggles", |window| {
 8745                            self.layout_expand_toggles(
 8746                                &gutter_hitbox,
 8747                                gutter_dimensions,
 8748                                em_width,
 8749                                line_height,
 8750                                scroll_position,
 8751                                &row_infos,
 8752                                window,
 8753                                cx,
 8754                            )
 8755                        });
 8756
 8757                    let mut crease_toggles =
 8758                        window.with_element_namespace("crease_toggles", |window| {
 8759                            self.layout_crease_toggles(
 8760                                start_row..end_row,
 8761                                &row_infos,
 8762                                &active_rows,
 8763                                &snapshot,
 8764                                window,
 8765                                cx,
 8766                            )
 8767                        });
 8768                    let crease_trailers =
 8769                        window.with_element_namespace("crease_trailers", |window| {
 8770                            self.layout_crease_trailers(
 8771                                row_infos.iter().copied(),
 8772                                &snapshot,
 8773                                window,
 8774                                cx,
 8775                            )
 8776                        });
 8777
 8778                    let display_hunks = self.layout_gutter_diff_hunks(
 8779                        line_height,
 8780                        &gutter_hitbox,
 8781                        start_row..end_row,
 8782                        &snapshot,
 8783                        window,
 8784                        cx,
 8785                    );
 8786
 8787                    let bg_segments_per_row = Self::bg_segments_per_row(
 8788                        start_row..end_row,
 8789                        &selections,
 8790                        &highlighted_ranges,
 8791                        self.style.background,
 8792                    );
 8793
 8794                    let mut line_layouts = Self::layout_lines(
 8795                        start_row..end_row,
 8796                        &snapshot,
 8797                        &self.style,
 8798                        editor_width,
 8799                        is_row_soft_wrapped,
 8800                        &bg_segments_per_row,
 8801                        window,
 8802                        cx,
 8803                    );
 8804                    let new_renderer_widths = (!is_minimap).then(|| {
 8805                        line_layouts
 8806                            .iter()
 8807                            .flat_map(|layout| &layout.fragments)
 8808                            .filter_map(|fragment| {
 8809                                if let LineFragment::Element { id, size, .. } = fragment {
 8810                                    Some((*id, size.width))
 8811                                } else {
 8812                                    None
 8813                                }
 8814                            })
 8815                    });
 8816                    if new_renderer_widths.is_some_and(|new_renderer_widths| {
 8817                        self.editor.update(cx, |editor, cx| {
 8818                            editor.update_renderer_widths(new_renderer_widths, cx)
 8819                        })
 8820                    }) {
 8821                        // If the fold widths have changed, we need to prepaint
 8822                        // the element again to account for any changes in
 8823                        // wrapping.
 8824                        return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
 8825                    }
 8826
 8827                    let longest_line_blame_width = self
 8828                        .editor
 8829                        .update(cx, |editor, cx| {
 8830                            if !editor.show_git_blame_inline {
 8831                                return None;
 8832                            }
 8833                            let blame = editor.blame.as_ref()?;
 8834                            let (_, blame_entry) = blame
 8835                                .update(cx, |blame, cx| {
 8836                                    let row_infos =
 8837                                        snapshot.row_infos(snapshot.longest_row()).next()?;
 8838                                    blame.blame_for_rows(&[row_infos], cx).next()
 8839                                })
 8840                                .flatten()?;
 8841                            let mut element = render_inline_blame_entry(blame_entry, style, cx)?;
 8842                            let inline_blame_padding = ProjectSettings::get_global(cx)
 8843                                .git
 8844                                .inline_blame
 8845                                .unwrap_or_default()
 8846                                .padding
 8847                                as f32
 8848                                * em_advance;
 8849                            Some(
 8850                                element
 8851                                    .layout_as_root(AvailableSpace::min_size(), window, cx)
 8852                                    .width
 8853                                    + inline_blame_padding,
 8854                            )
 8855                        })
 8856                        .unwrap_or(Pixels::ZERO);
 8857
 8858                    let longest_line_width = layout_line(
 8859                        snapshot.longest_row(),
 8860                        &snapshot,
 8861                        style,
 8862                        editor_width,
 8863                        is_row_soft_wrapped,
 8864                        window,
 8865                        cx,
 8866                    )
 8867                    .width;
 8868
 8869                    let scrollbar_layout_information = ScrollbarLayoutInformation::new(
 8870                        text_hitbox.bounds,
 8871                        glyph_grid_cell,
 8872                        size(longest_line_width, max_row.as_f32() * line_height),
 8873                        longest_line_blame_width,
 8874                        EditorSettings::get_global(cx),
 8875                    );
 8876
 8877                    let mut scroll_width = scrollbar_layout_information.scroll_range.width;
 8878
 8879                    let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
 8880                        snapshot.sticky_header_excerpt(scroll_position.y)
 8881                    } else {
 8882                        None
 8883                    };
 8884                    let sticky_header_excerpt_id =
 8885                        sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
 8886
 8887                    let blocks = (!is_minimap)
 8888                        .then(|| {
 8889                            window.with_element_namespace("blocks", |window| {
 8890                                self.render_blocks(
 8891                                    start_row..end_row,
 8892                                    &snapshot,
 8893                                    &hitbox,
 8894                                    &text_hitbox,
 8895                                    editor_width,
 8896                                    &mut scroll_width,
 8897                                    &editor_margins,
 8898                                    em_width,
 8899                                    gutter_dimensions.full_width(),
 8900                                    line_height,
 8901                                    &mut line_layouts,
 8902                                    &local_selections,
 8903                                    &selected_buffer_ids,
 8904                                    is_row_soft_wrapped,
 8905                                    sticky_header_excerpt_id,
 8906                                    window,
 8907                                    cx,
 8908                                )
 8909                            })
 8910                        })
 8911                        .unwrap_or_else(|| Ok((Vec::default(), HashMap::default())));
 8912                    let (mut blocks, row_block_types) = match blocks {
 8913                        Ok(blocks) => blocks,
 8914                        Err(resized_blocks) => {
 8915                            self.editor.update(cx, |editor, cx| {
 8916                                editor.resize_blocks(
 8917                                    resized_blocks,
 8918                                    autoscroll_request.map(|(autoscroll, _)| autoscroll),
 8919                                    cx,
 8920                                )
 8921                            });
 8922                            return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
 8923                        }
 8924                    };
 8925
 8926                    let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
 8927                        window.with_element_namespace("blocks", |window| {
 8928                            self.layout_sticky_buffer_header(
 8929                                sticky_header_excerpt,
 8930                                scroll_position.y,
 8931                                line_height,
 8932                                right_margin,
 8933                                &snapshot,
 8934                                &hitbox,
 8935                                &selected_buffer_ids,
 8936                                &blocks,
 8937                                window,
 8938                                cx,
 8939                            )
 8940                        })
 8941                    });
 8942
 8943                    let start_buffer_row =
 8944                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
 8945                    let end_buffer_row =
 8946                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
 8947
 8948                    let scroll_max = point(
 8949                        ((scroll_width - editor_width) / em_advance).max(0.0),
 8950                        max_scroll_top,
 8951                    );
 8952
 8953                    self.editor.update(cx, |editor, cx| {
 8954                        if editor.scroll_manager.clamp_scroll_left(scroll_max.x) {
 8955                            scroll_position.x = scroll_position.x.min(scroll_max.x);
 8956                        }
 8957
 8958                        if needs_horizontal_autoscroll.0
 8959                            && let Some(new_scroll_position) = editor.autoscroll_horizontally(
 8960                                start_row,
 8961                                editor_width,
 8962                                scroll_width,
 8963                                em_advance,
 8964                                &line_layouts,
 8965                                autoscroll_request,
 8966                                window,
 8967                                cx,
 8968                            )
 8969                        {
 8970                            scroll_position = new_scroll_position;
 8971                        }
 8972                    });
 8973
 8974                    let scroll_pixel_position = point(
 8975                        scroll_position.x * em_advance,
 8976                        scroll_position.y * line_height,
 8977                    );
 8978                    let indent_guides = self.layout_indent_guides(
 8979                        content_origin,
 8980                        text_hitbox.origin,
 8981                        start_buffer_row..end_buffer_row,
 8982                        scroll_pixel_position,
 8983                        line_height,
 8984                        &snapshot,
 8985                        window,
 8986                        cx,
 8987                    );
 8988
 8989                    let crease_trailers =
 8990                        window.with_element_namespace("crease_trailers", |window| {
 8991                            self.prepaint_crease_trailers(
 8992                                crease_trailers,
 8993                                &line_layouts,
 8994                                line_height,
 8995                                content_origin,
 8996                                scroll_pixel_position,
 8997                                em_width,
 8998                                window,
 8999                                cx,
 9000                            )
 9001                        });
 9002
 9003                    let (edit_prediction_popover, edit_prediction_popover_origin) = self
 9004                        .editor
 9005                        .update(cx, |editor, cx| {
 9006                            editor.render_edit_prediction_popover(
 9007                                &text_hitbox.bounds,
 9008                                content_origin,
 9009                                right_margin,
 9010                                &snapshot,
 9011                                start_row..end_row,
 9012                                scroll_position.y,
 9013                                scroll_position.y + height_in_lines,
 9014                                &line_layouts,
 9015                                line_height,
 9016                                scroll_pixel_position,
 9017                                newest_selection_head,
 9018                                editor_width,
 9019                                style,
 9020                                window,
 9021                                cx,
 9022                            )
 9023                        })
 9024                        .unzip();
 9025
 9026                    let mut inline_diagnostics = self.layout_inline_diagnostics(
 9027                        &line_layouts,
 9028                        &crease_trailers,
 9029                        &row_block_types,
 9030                        content_origin,
 9031                        scroll_pixel_position,
 9032                        edit_prediction_popover_origin,
 9033                        start_row,
 9034                        end_row,
 9035                        line_height,
 9036                        em_width,
 9037                        style,
 9038                        window,
 9039                        cx,
 9040                    );
 9041
 9042                    let mut inline_blame_layout = None;
 9043                    let mut inline_code_actions = None;
 9044                    if let Some(newest_selection_head) = newest_selection_head {
 9045                        let display_row = newest_selection_head.row();
 9046                        if (start_row..end_row).contains(&display_row)
 9047                            && !row_block_types.contains_key(&display_row)
 9048                        {
 9049                            inline_code_actions = self.layout_inline_code_actions(
 9050                                newest_selection_head,
 9051                                content_origin,
 9052                                scroll_pixel_position,
 9053                                line_height,
 9054                                &snapshot,
 9055                                window,
 9056                                cx,
 9057                            );
 9058
 9059                            let line_ix = display_row.minus(start_row) as usize;
 9060                            if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
 9061                                row_infos.get(line_ix),
 9062                                line_layouts.get(line_ix),
 9063                                crease_trailers.get(line_ix),
 9064                            ) {
 9065                                let crease_trailer_layout = crease_trailer.as_ref();
 9066                                if let Some(layout) = self.layout_inline_blame(
 9067                                    display_row,
 9068                                    row_info,
 9069                                    line_layout,
 9070                                    crease_trailer_layout,
 9071                                    em_width,
 9072                                    content_origin,
 9073                                    scroll_pixel_position,
 9074                                    line_height,
 9075                                    &text_hitbox,
 9076                                    window,
 9077                                    cx,
 9078                                ) {
 9079                                    inline_blame_layout = Some(layout);
 9080                                    // Blame overrides inline diagnostics
 9081                                    inline_diagnostics.remove(&display_row);
 9082                                }
 9083                            } else {
 9084                                log::error!(
 9085                                    "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
 9086                                    line_layouts.len(): {}, \
 9087                                    crease_trailers.len(): {}",
 9088                                    line_ix,
 9089                                    row_infos.len(),
 9090                                    line_layouts.len(),
 9091                                    crease_trailers.len(),
 9092                                );
 9093                            }
 9094                        }
 9095                    }
 9096
 9097                    let blamed_display_rows = self.layout_blame_entries(
 9098                        &row_infos,
 9099                        em_width,
 9100                        scroll_position,
 9101                        line_height,
 9102                        &gutter_hitbox,
 9103                        gutter_dimensions.git_blame_entries_width,
 9104                        window,
 9105                        cx,
 9106                    );
 9107
 9108                    let line_elements = self.prepaint_lines(
 9109                        start_row,
 9110                        &mut line_layouts,
 9111                        line_height,
 9112                        scroll_pixel_position,
 9113                        content_origin,
 9114                        window,
 9115                        cx,
 9116                    );
 9117
 9118                    window.with_element_namespace("blocks", |window| {
 9119                        self.layout_blocks(
 9120                            &mut blocks,
 9121                            &hitbox,
 9122                            line_height,
 9123                            scroll_pixel_position,
 9124                            window,
 9125                            cx,
 9126                        );
 9127                    });
 9128
 9129                    let cursors = self.collect_cursors(&snapshot, cx);
 9130                    let visible_row_range = start_row..end_row;
 9131                    let non_visible_cursors = cursors
 9132                        .iter()
 9133                        .any(|c| !visible_row_range.contains(&c.0.row()));
 9134
 9135                    let visible_cursors = self.layout_visible_cursors(
 9136                        &snapshot,
 9137                        &selections,
 9138                        &row_block_types,
 9139                        start_row..end_row,
 9140                        &line_layouts,
 9141                        &text_hitbox,
 9142                        content_origin,
 9143                        scroll_position,
 9144                        scroll_pixel_position,
 9145                        line_height,
 9146                        em_width,
 9147                        em_advance,
 9148                        autoscroll_containing_element,
 9149                        window,
 9150                        cx,
 9151                    );
 9152
 9153                    let scrollbars_layout = self.layout_scrollbars(
 9154                        &snapshot,
 9155                        &scrollbar_layout_information,
 9156                        content_offset,
 9157                        scroll_position,
 9158                        non_visible_cursors,
 9159                        right_margin,
 9160                        editor_width,
 9161                        window,
 9162                        cx,
 9163                    );
 9164
 9165                    let gutter_settings = EditorSettings::get_global(cx).gutter;
 9166
 9167                    let context_menu_layout =
 9168                        if let Some(newest_selection_head) = newest_selection_head {
 9169                            let newest_selection_point =
 9170                                newest_selection_head.to_point(&snapshot.display_snapshot);
 9171                            if (start_row..end_row).contains(&newest_selection_head.row()) {
 9172                                self.layout_cursor_popovers(
 9173                                    line_height,
 9174                                    &text_hitbox,
 9175                                    content_origin,
 9176                                    right_margin,
 9177                                    start_row,
 9178                                    scroll_pixel_position,
 9179                                    &line_layouts,
 9180                                    newest_selection_head,
 9181                                    newest_selection_point,
 9182                                    style,
 9183                                    window,
 9184                                    cx,
 9185                                )
 9186                            } else {
 9187                                None
 9188                            }
 9189                        } else {
 9190                            None
 9191                        };
 9192
 9193                    self.layout_gutter_menu(
 9194                        line_height,
 9195                        &text_hitbox,
 9196                        content_origin,
 9197                        right_margin,
 9198                        scroll_pixel_position,
 9199                        gutter_dimensions.width - gutter_dimensions.left_padding,
 9200                        window,
 9201                        cx,
 9202                    );
 9203
 9204                    let test_indicators = if gutter_settings.runnables {
 9205                        self.layout_run_indicators(
 9206                            line_height,
 9207                            start_row..end_row,
 9208                            &row_infos,
 9209                            scroll_pixel_position,
 9210                            &gutter_dimensions,
 9211                            &gutter_hitbox,
 9212                            &display_hunks,
 9213                            &snapshot,
 9214                            &mut breakpoint_rows,
 9215                            window,
 9216                            cx,
 9217                        )
 9218                    } else {
 9219                        Vec::new()
 9220                    };
 9221
 9222                    let show_breakpoints = snapshot
 9223                        .show_breakpoints
 9224                        .unwrap_or(gutter_settings.breakpoints);
 9225                    let breakpoints = if show_breakpoints {
 9226                        self.layout_breakpoints(
 9227                            line_height,
 9228                            start_row..end_row,
 9229                            scroll_pixel_position,
 9230                            &gutter_dimensions,
 9231                            &gutter_hitbox,
 9232                            &display_hunks,
 9233                            &snapshot,
 9234                            breakpoint_rows,
 9235                            &row_infos,
 9236                            window,
 9237                            cx,
 9238                        )
 9239                    } else {
 9240                        Vec::new()
 9241                    };
 9242
 9243                    self.layout_signature_help(
 9244                        &hitbox,
 9245                        content_origin,
 9246                        scroll_pixel_position,
 9247                        newest_selection_head,
 9248                        start_row,
 9249                        &line_layouts,
 9250                        line_height,
 9251                        em_width,
 9252                        context_menu_layout,
 9253                        window,
 9254                        cx,
 9255                    );
 9256
 9257                    if !cx.has_active_drag() {
 9258                        self.layout_hover_popovers(
 9259                            &snapshot,
 9260                            &hitbox,
 9261                            start_row..end_row,
 9262                            content_origin,
 9263                            scroll_pixel_position,
 9264                            &line_layouts,
 9265                            line_height,
 9266                            em_width,
 9267                            context_menu_layout,
 9268                            window,
 9269                            cx,
 9270                        );
 9271                    }
 9272
 9273                    let mouse_context_menu = self.layout_mouse_context_menu(
 9274                        &snapshot,
 9275                        start_row..end_row,
 9276                        content_origin,
 9277                        window,
 9278                        cx,
 9279                    );
 9280
 9281                    window.with_element_namespace("crease_toggles", |window| {
 9282                        self.prepaint_crease_toggles(
 9283                            &mut crease_toggles,
 9284                            line_height,
 9285                            &gutter_dimensions,
 9286                            gutter_settings,
 9287                            scroll_pixel_position,
 9288                            &gutter_hitbox,
 9289                            window,
 9290                            cx,
 9291                        )
 9292                    });
 9293
 9294                    window.with_element_namespace("expand_toggles", |window| {
 9295                        self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
 9296                    });
 9297
 9298                    let wrap_guides = self.layout_wrap_guides(
 9299                        em_advance,
 9300                        scroll_position,
 9301                        content_origin,
 9302                        scrollbars_layout.as_ref(),
 9303                        vertical_scrollbar_width,
 9304                        &hitbox,
 9305                        window,
 9306                        cx,
 9307                    );
 9308
 9309                    let minimap = window.with_element_namespace("minimap", |window| {
 9310                        self.layout_minimap(
 9311                            &snapshot,
 9312                            minimap_width,
 9313                            scroll_position,
 9314                            &scrollbar_layout_information,
 9315                            scrollbars_layout.as_ref(),
 9316                            window,
 9317                            cx,
 9318                        )
 9319                    });
 9320
 9321                    let invisible_symbol_font_size = font_size / 2.;
 9322                    let whitespace_map = &self
 9323                        .editor
 9324                        .read(cx)
 9325                        .buffer
 9326                        .read(cx)
 9327                        .language_settings(cx)
 9328                        .whitespace_map;
 9329
 9330                    let tab_char = whitespace_map.tab();
 9331                    let tab_len = tab_char.len();
 9332                    let tab_invisible = window.text_system().shape_line(
 9333                        tab_char,
 9334                        invisible_symbol_font_size,
 9335                        &[TextRun {
 9336                            len: tab_len,
 9337                            font: self.style.text.font(),
 9338                            color: cx.theme().colors().editor_invisible,
 9339                            background_color: None,
 9340                            underline: None,
 9341                            strikethrough: None,
 9342                        }],
 9343                        None,
 9344                    );
 9345
 9346                    let space_char = whitespace_map.space();
 9347                    let space_len = space_char.len();
 9348                    let space_invisible = window.text_system().shape_line(
 9349                        space_char,
 9350                        invisible_symbol_font_size,
 9351                        &[TextRun {
 9352                            len: space_len,
 9353                            font: self.style.text.font(),
 9354                            color: cx.theme().colors().editor_invisible,
 9355                            background_color: None,
 9356                            underline: None,
 9357                            strikethrough: None,
 9358                        }],
 9359                        None,
 9360                    );
 9361
 9362                    let mode = snapshot.mode.clone();
 9363
 9364                    let (diff_hunk_controls, diff_hunk_control_bounds) = if is_read_only {
 9365                        (vec![], vec![])
 9366                    } else {
 9367                        self.layout_diff_hunk_controls(
 9368                            start_row..end_row,
 9369                            &row_infos,
 9370                            &text_hitbox,
 9371                            newest_selection_head,
 9372                            line_height,
 9373                            right_margin,
 9374                            scroll_pixel_position,
 9375                            &display_hunks,
 9376                            &highlighted_rows,
 9377                            self.editor.clone(),
 9378                            window,
 9379                            cx,
 9380                        )
 9381                    };
 9382
 9383                    let position_map = Rc::new(PositionMap {
 9384                        size: bounds.size,
 9385                        visible_row_range,
 9386                        scroll_pixel_position,
 9387                        scroll_max,
 9388                        line_layouts,
 9389                        line_height,
 9390                        em_width,
 9391                        em_advance,
 9392                        snapshot,
 9393                        gutter_hitbox: gutter_hitbox.clone(),
 9394                        text_hitbox: text_hitbox.clone(),
 9395                        inline_blame_bounds: inline_blame_layout
 9396                            .as_ref()
 9397                            .map(|layout| (layout.bounds, layout.buffer_id, layout.entry.clone())),
 9398                        display_hunks: display_hunks.clone(),
 9399                        diff_hunk_control_bounds,
 9400                    });
 9401
 9402                    self.editor.update(cx, |editor, _| {
 9403                        editor.last_position_map = Some(position_map.clone())
 9404                    });
 9405
 9406                    EditorLayout {
 9407                        mode,
 9408                        position_map,
 9409                        visible_display_row_range: start_row..end_row,
 9410                        wrap_guides,
 9411                        indent_guides,
 9412                        hitbox,
 9413                        gutter_hitbox,
 9414                        display_hunks,
 9415                        content_origin,
 9416                        scrollbars_layout,
 9417                        minimap,
 9418                        active_rows,
 9419                        highlighted_rows,
 9420                        highlighted_ranges,
 9421                        highlighted_gutter_ranges,
 9422                        redacted_ranges,
 9423                        document_colors,
 9424                        line_elements,
 9425                        line_numbers,
 9426                        blamed_display_rows,
 9427                        inline_diagnostics,
 9428                        inline_blame_layout,
 9429                        inline_code_actions,
 9430                        blocks,
 9431                        cursors,
 9432                        visible_cursors,
 9433                        selections,
 9434                        edit_prediction_popover,
 9435                        diff_hunk_controls,
 9436                        mouse_context_menu,
 9437                        test_indicators,
 9438                        breakpoints,
 9439                        crease_toggles,
 9440                        crease_trailers,
 9441                        tab_invisible,
 9442                        space_invisible,
 9443                        sticky_buffer_header,
 9444                        expand_toggles,
 9445                    }
 9446                })
 9447            })
 9448        })
 9449    }
 9450
 9451    fn paint(
 9452        &mut self,
 9453        _: Option<&GlobalElementId>,
 9454        _inspector_id: Option<&gpui::InspectorElementId>,
 9455        bounds: Bounds<gpui::Pixels>,
 9456        _: &mut Self::RequestLayoutState,
 9457        layout: &mut Self::PrepaintState,
 9458        window: &mut Window,
 9459        cx: &mut App,
 9460    ) {
 9461        if !layout.mode.is_minimap() {
 9462            let focus_handle = self.editor.focus_handle(cx);
 9463            let key_context = self
 9464                .editor
 9465                .update(cx, |editor, cx| editor.key_context(window, cx));
 9466
 9467            window.set_key_context(key_context);
 9468            window.handle_input(
 9469                &focus_handle,
 9470                ElementInputHandler::new(bounds, self.editor.clone()),
 9471                cx,
 9472            );
 9473            self.register_actions(window, cx);
 9474            self.register_key_listeners(window, cx, layout);
 9475        }
 9476
 9477        let text_style = TextStyleRefinement {
 9478            font_size: Some(self.style.text.font_size),
 9479            line_height: Some(self.style.text.line_height),
 9480            ..Default::default()
 9481        };
 9482        let rem_size = self.rem_size(cx);
 9483        window.with_rem_size(rem_size, |window| {
 9484            window.with_text_style(Some(text_style), |window| {
 9485                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 9486                    self.paint_mouse_listeners(layout, window, cx);
 9487                    self.paint_background(layout, window, cx);
 9488                    self.paint_indent_guides(layout, window, cx);
 9489
 9490                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
 9491                        self.paint_blamed_display_rows(layout, window, cx);
 9492                        self.paint_line_numbers(layout, window, cx);
 9493                    }
 9494
 9495                    self.paint_text(layout, window, cx);
 9496
 9497                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
 9498                        self.paint_gutter_highlights(layout, window, cx);
 9499                        self.paint_gutter_indicators(layout, window, cx);
 9500                    }
 9501
 9502                    if !layout.blocks.is_empty() {
 9503                        window.with_element_namespace("blocks", |window| {
 9504                            self.paint_blocks(layout, window, cx);
 9505                        });
 9506                    }
 9507
 9508                    window.with_element_namespace("blocks", |window| {
 9509                        if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
 9510                            sticky_header.paint(window, cx)
 9511                        }
 9512                    });
 9513
 9514                    self.paint_minimap(layout, window, cx);
 9515                    self.paint_scrollbars(layout, window, cx);
 9516                    self.paint_edit_prediction_popover(layout, window, cx);
 9517                    self.paint_mouse_context_menu(layout, window, cx);
 9518                });
 9519            })
 9520        })
 9521    }
 9522}
 9523
 9524pub(super) fn gutter_bounds(
 9525    editor_bounds: Bounds<Pixels>,
 9526    gutter_dimensions: GutterDimensions,
 9527) -> Bounds<Pixels> {
 9528    Bounds {
 9529        origin: editor_bounds.origin,
 9530        size: size(gutter_dimensions.width, editor_bounds.size.height),
 9531    }
 9532}
 9533
 9534#[derive(Clone, Copy)]
 9535struct ContextMenuLayout {
 9536    y_flipped: bool,
 9537    bounds: Bounds<Pixels>,
 9538}
 9539
 9540/// Holds information required for layouting the editor scrollbars.
 9541struct ScrollbarLayoutInformation {
 9542    /// The bounds of the editor area (excluding the content offset).
 9543    editor_bounds: Bounds<Pixels>,
 9544    /// The available range to scroll within the document.
 9545    scroll_range: Size<Pixels>,
 9546    /// The space available for one glyph in the editor.
 9547    glyph_grid_cell: Size<Pixels>,
 9548}
 9549
 9550impl ScrollbarLayoutInformation {
 9551    pub fn new(
 9552        editor_bounds: Bounds<Pixels>,
 9553        glyph_grid_cell: Size<Pixels>,
 9554        document_size: Size<Pixels>,
 9555        longest_line_blame_width: Pixels,
 9556        settings: &EditorSettings,
 9557    ) -> Self {
 9558        let vertical_overscroll = match settings.scroll_beyond_last_line {
 9559            ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
 9560            ScrollBeyondLastLine::Off => glyph_grid_cell.height,
 9561            ScrollBeyondLastLine::VerticalScrollMargin => {
 9562                (1.0 + settings.vertical_scroll_margin) * glyph_grid_cell.height
 9563            }
 9564        };
 9565
 9566        let overscroll = size(longest_line_blame_width, vertical_overscroll);
 9567
 9568        ScrollbarLayoutInformation {
 9569            editor_bounds,
 9570            scroll_range: document_size + overscroll,
 9571            glyph_grid_cell,
 9572        }
 9573    }
 9574}
 9575
 9576impl IntoElement for EditorElement {
 9577    type Element = Self;
 9578
 9579    fn into_element(self) -> Self::Element {
 9580        self
 9581    }
 9582}
 9583
 9584pub struct EditorLayout {
 9585    position_map: Rc<PositionMap>,
 9586    hitbox: Hitbox,
 9587    gutter_hitbox: Hitbox,
 9588    content_origin: gpui::Point<Pixels>,
 9589    scrollbars_layout: Option<EditorScrollbars>,
 9590    minimap: Option<MinimapLayout>,
 9591    mode: EditorMode,
 9592    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
 9593    indent_guides: Option<Vec<IndentGuideLayout>>,
 9594    visible_display_row_range: Range<DisplayRow>,
 9595    active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
 9596    highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
 9597    line_elements: SmallVec<[AnyElement; 1]>,
 9598    line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
 9599    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
 9600    blamed_display_rows: Option<Vec<AnyElement>>,
 9601    inline_diagnostics: HashMap<DisplayRow, AnyElement>,
 9602    inline_blame_layout: Option<InlineBlameLayout>,
 9603    inline_code_actions: Option<AnyElement>,
 9604    blocks: Vec<BlockLayout>,
 9605    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
 9606    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
 9607    redacted_ranges: Vec<Range<DisplayPoint>>,
 9608    cursors: Vec<(DisplayPoint, Hsla)>,
 9609    visible_cursors: Vec<CursorLayout>,
 9610    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
 9611    test_indicators: Vec<AnyElement>,
 9612    breakpoints: Vec<AnyElement>,
 9613    crease_toggles: Vec<Option<AnyElement>>,
 9614    expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
 9615    diff_hunk_controls: Vec<AnyElement>,
 9616    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
 9617    edit_prediction_popover: Option<AnyElement>,
 9618    mouse_context_menu: Option<AnyElement>,
 9619    tab_invisible: ShapedLine,
 9620    space_invisible: ShapedLine,
 9621    sticky_buffer_header: Option<AnyElement>,
 9622    document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
 9623}
 9624
 9625impl EditorLayout {
 9626    fn line_end_overshoot(&self) -> Pixels {
 9627        0.15 * self.position_map.line_height
 9628    }
 9629}
 9630
 9631struct LineNumberLayout {
 9632    shaped_line: ShapedLine,
 9633    hitbox: Option<Hitbox>,
 9634}
 9635
 9636struct ColoredRange<T> {
 9637    start: T,
 9638    end: T,
 9639    color: Hsla,
 9640}
 9641
 9642impl Along for ScrollbarAxes {
 9643    type Unit = bool;
 9644
 9645    fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
 9646        match axis {
 9647            ScrollbarAxis::Horizontal => self.horizontal,
 9648            ScrollbarAxis::Vertical => self.vertical,
 9649        }
 9650    }
 9651
 9652    fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
 9653        match axis {
 9654            ScrollbarAxis::Horizontal => ScrollbarAxes {
 9655                horizontal: f(self.horizontal),
 9656                vertical: self.vertical,
 9657            },
 9658            ScrollbarAxis::Vertical => ScrollbarAxes {
 9659                horizontal: self.horizontal,
 9660                vertical: f(self.vertical),
 9661            },
 9662        }
 9663    }
 9664}
 9665
 9666#[derive(Clone)]
 9667struct EditorScrollbars {
 9668    pub vertical: Option<ScrollbarLayout>,
 9669    pub horizontal: Option<ScrollbarLayout>,
 9670    pub visible: bool,
 9671}
 9672
 9673impl EditorScrollbars {
 9674    pub fn from_scrollbar_axes(
 9675        show_scrollbar: ScrollbarAxes,
 9676        layout_information: &ScrollbarLayoutInformation,
 9677        content_offset: gpui::Point<Pixels>,
 9678        scroll_position: gpui::Point<f32>,
 9679        scrollbar_width: Pixels,
 9680        right_margin: Pixels,
 9681        editor_width: Pixels,
 9682        show_scrollbars: bool,
 9683        scrollbar_state: Option<&ActiveScrollbarState>,
 9684        window: &mut Window,
 9685    ) -> Self {
 9686        let ScrollbarLayoutInformation {
 9687            editor_bounds,
 9688            scroll_range,
 9689            glyph_grid_cell,
 9690        } = layout_information;
 9691
 9692        let viewport_size = size(editor_width, editor_bounds.size.height);
 9693
 9694        let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
 9695            ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
 9696                Corner::BottomLeft,
 9697                editor_bounds.bottom_left(),
 9698                size(
 9699                    // The horizontal viewport size differs from the space available for the
 9700                    // horizontal scrollbar, so we have to manually stitch it together here.
 9701                    editor_bounds.size.width - right_margin,
 9702                    scrollbar_width,
 9703                ),
 9704            ),
 9705            ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
 9706                Corner::TopRight,
 9707                editor_bounds.top_right(),
 9708                size(scrollbar_width, viewport_size.height),
 9709            ),
 9710        };
 9711
 9712        let mut create_scrollbar_layout = |axis| {
 9713            let viewport_size = viewport_size.along(axis);
 9714            let scroll_range = scroll_range.along(axis);
 9715
 9716            // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
 9717            (show_scrollbar.along(axis)
 9718                && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
 9719                .then(|| {
 9720                    ScrollbarLayout::new(
 9721                        window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
 9722                        viewport_size,
 9723                        scroll_range,
 9724                        glyph_grid_cell.along(axis),
 9725                        content_offset.along(axis),
 9726                        scroll_position.along(axis),
 9727                        show_scrollbars,
 9728                        axis,
 9729                    )
 9730                    .with_thumb_state(
 9731                        scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
 9732                    )
 9733                })
 9734        };
 9735
 9736        Self {
 9737            vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
 9738            horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
 9739            visible: show_scrollbars,
 9740        }
 9741    }
 9742
 9743    pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
 9744        [
 9745            (&self.vertical, ScrollbarAxis::Vertical),
 9746            (&self.horizontal, ScrollbarAxis::Horizontal),
 9747        ]
 9748        .into_iter()
 9749        .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
 9750    }
 9751
 9752    /// Returns the currently hovered scrollbar axis, if any.
 9753    pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
 9754        self.iter_scrollbars()
 9755            .find(|s| s.0.hitbox.is_hovered(window))
 9756    }
 9757}
 9758
 9759#[derive(Clone)]
 9760struct ScrollbarLayout {
 9761    hitbox: Hitbox,
 9762    visible_range: Range<f32>,
 9763    text_unit_size: Pixels,
 9764    thumb_bounds: Option<Bounds<Pixels>>,
 9765    thumb_state: ScrollbarThumbState,
 9766}
 9767
 9768impl ScrollbarLayout {
 9769    const BORDER_WIDTH: Pixels = px(1.0);
 9770    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
 9771    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
 9772    const MIN_THUMB_SIZE: Pixels = px(25.0);
 9773
 9774    fn new(
 9775        scrollbar_track_hitbox: Hitbox,
 9776        viewport_size: Pixels,
 9777        scroll_range: Pixels,
 9778        glyph_space: Pixels,
 9779        content_offset: Pixels,
 9780        scroll_position: f32,
 9781        show_thumb: bool,
 9782        axis: ScrollbarAxis,
 9783    ) -> Self {
 9784        let track_bounds = scrollbar_track_hitbox.bounds;
 9785        // The length of the track available to the scrollbar thumb. We deliberately
 9786        // exclude the content size here so that the thumb aligns with the content.
 9787        let track_length = track_bounds.size.along(axis) - content_offset;
 9788
 9789        Self::new_with_hitbox_and_track_length(
 9790            scrollbar_track_hitbox,
 9791            track_length,
 9792            viewport_size,
 9793            scroll_range,
 9794            glyph_space,
 9795            content_offset,
 9796            scroll_position,
 9797            show_thumb,
 9798            axis,
 9799        )
 9800    }
 9801
 9802    fn for_minimap(
 9803        minimap_track_hitbox: Hitbox,
 9804        visible_lines: f32,
 9805        total_editor_lines: f32,
 9806        minimap_line_height: Pixels,
 9807        scroll_position: f32,
 9808        minimap_scroll_top: f32,
 9809        show_thumb: bool,
 9810    ) -> Self {
 9811        // The scrollbar thumb size is calculated as
 9812        // (visible_content/total_content) Γ— scrollbar_track_length.
 9813        //
 9814        // For the minimap's thumb layout, we leverage this by setting the
 9815        // scrollbar track length to the entire document size (using minimap line
 9816        // height). This creates a thumb that exactly represents the editor
 9817        // viewport scaled to minimap proportions.
 9818        //
 9819        // We adjust the thumb position relative to `minimap_scroll_top` to
 9820        // accommodate for the deliberately oversized track.
 9821        //
 9822        // This approach ensures that the minimap thumb accurately reflects the
 9823        // editor's current scroll position whilst nicely synchronizing the minimap
 9824        // thumb and scrollbar thumb.
 9825        let scroll_range = total_editor_lines * minimap_line_height;
 9826        let viewport_size = visible_lines * minimap_line_height;
 9827
 9828        let track_top_offset = -minimap_scroll_top * minimap_line_height;
 9829
 9830        Self::new_with_hitbox_and_track_length(
 9831            minimap_track_hitbox,
 9832            scroll_range,
 9833            viewport_size,
 9834            scroll_range,
 9835            minimap_line_height,
 9836            track_top_offset,
 9837            scroll_position,
 9838            show_thumb,
 9839            ScrollbarAxis::Vertical,
 9840        )
 9841    }
 9842
 9843    fn new_with_hitbox_and_track_length(
 9844        scrollbar_track_hitbox: Hitbox,
 9845        track_length: Pixels,
 9846        viewport_size: Pixels,
 9847        scroll_range: Pixels,
 9848        glyph_space: Pixels,
 9849        content_offset: Pixels,
 9850        scroll_position: f32,
 9851        show_thumb: bool,
 9852        axis: ScrollbarAxis,
 9853    ) -> Self {
 9854        let text_units_per_page = viewport_size / glyph_space;
 9855        let visible_range = scroll_position..scroll_position + text_units_per_page;
 9856        let total_text_units = scroll_range / glyph_space;
 9857
 9858        let thumb_percentage = text_units_per_page / total_text_units;
 9859        let thumb_size = (track_length * thumb_percentage)
 9860            .max(ScrollbarLayout::MIN_THUMB_SIZE)
 9861            .min(track_length);
 9862
 9863        let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
 9864
 9865        let content_larger_than_viewport = text_unit_divisor > 0.;
 9866
 9867        let text_unit_size = if content_larger_than_viewport {
 9868            (track_length - thumb_size) / text_unit_divisor
 9869        } else {
 9870            glyph_space
 9871        };
 9872
 9873        let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
 9874            Self::thumb_bounds(
 9875                &scrollbar_track_hitbox,
 9876                content_offset,
 9877                visible_range.start,
 9878                text_unit_size,
 9879                thumb_size,
 9880                axis,
 9881            )
 9882        });
 9883
 9884        ScrollbarLayout {
 9885            hitbox: scrollbar_track_hitbox,
 9886            visible_range,
 9887            text_unit_size,
 9888            thumb_bounds,
 9889            thumb_state: Default::default(),
 9890        }
 9891    }
 9892
 9893    fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
 9894        if let Some(thumb_state) = thumb_state {
 9895            Self {
 9896                thumb_state,
 9897                ..self
 9898            }
 9899        } else {
 9900            self
 9901        }
 9902    }
 9903
 9904    fn thumb_bounds(
 9905        scrollbar_track: &Hitbox,
 9906        content_offset: Pixels,
 9907        visible_range_start: f32,
 9908        text_unit_size: Pixels,
 9909        thumb_size: Pixels,
 9910        axis: ScrollbarAxis,
 9911    ) -> Bounds<Pixels> {
 9912        let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
 9913            origin + content_offset + visible_range_start * text_unit_size
 9914        });
 9915        Bounds::new(
 9916            thumb_origin,
 9917            scrollbar_track.size.apply_along(axis, |_| thumb_size),
 9918        )
 9919    }
 9920
 9921    fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
 9922        self.thumb_bounds
 9923            .is_some_and(|bounds| bounds.contains(position))
 9924    }
 9925
 9926    fn marker_quads_for_ranges(
 9927        &self,
 9928        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
 9929        column: Option<usize>,
 9930    ) -> Vec<PaintQuad> {
 9931        struct MinMax {
 9932            min: Pixels,
 9933            max: Pixels,
 9934        }
 9935        let (x_range, height_limit) = if let Some(column) = column {
 9936            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
 9937            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
 9938            let end = start + column_width;
 9939            (
 9940                Range { start, end },
 9941                MinMax {
 9942                    min: Self::MIN_MARKER_HEIGHT,
 9943                    max: px(f32::MAX),
 9944                },
 9945            )
 9946        } else {
 9947            (
 9948                Range {
 9949                    start: Self::BORDER_WIDTH,
 9950                    end: self.hitbox.size.width,
 9951                },
 9952                MinMax {
 9953                    min: Self::LINE_MARKER_HEIGHT,
 9954                    max: Self::LINE_MARKER_HEIGHT,
 9955                },
 9956            )
 9957        };
 9958
 9959        let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
 9960        let mut pixel_ranges = row_ranges
 9961            .into_iter()
 9962            .map(|range| {
 9963                let start_y = row_to_y(range.start);
 9964                let end_y = row_to_y(range.end)
 9965                    + self
 9966                        .text_unit_size
 9967                        .max(height_limit.min)
 9968                        .min(height_limit.max);
 9969                ColoredRange {
 9970                    start: start_y,
 9971                    end: end_y,
 9972                    color: range.color,
 9973                }
 9974            })
 9975            .peekable();
 9976
 9977        let mut quads = Vec::new();
 9978        while let Some(mut pixel_range) = pixel_ranges.next() {
 9979            while let Some(next_pixel_range) = pixel_ranges.peek() {
 9980                if pixel_range.end >= next_pixel_range.start - px(1.0)
 9981                    && pixel_range.color == next_pixel_range.color
 9982                {
 9983                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
 9984                    pixel_ranges.next();
 9985                } else {
 9986                    break;
 9987                }
 9988            }
 9989
 9990            let bounds = Bounds::from_corners(
 9991                point(x_range.start, pixel_range.start),
 9992                point(x_range.end, pixel_range.end),
 9993            );
 9994            quads.push(quad(
 9995                bounds,
 9996                Corners::default(),
 9997                pixel_range.color,
 9998                Edges::default(),
 9999                Hsla::transparent_black(),
10000                BorderStyle::default(),
10001            ));
10002        }
10003
10004        quads
10005    }
10006}
10007
10008struct MinimapLayout {
10009    pub minimap: AnyElement,
10010    pub thumb_layout: ScrollbarLayout,
10011    pub minimap_scroll_top: f32,
10012    pub minimap_line_height: Pixels,
10013    pub thumb_border_style: MinimapThumbBorder,
10014    pub max_scroll_top: f32,
10015}
10016
10017impl MinimapLayout {
10018    /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
10019    const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
10020    /// The minimap width as a percentage of the editor width.
10021    const MINIMAP_WIDTH_PCT: f32 = 0.15;
10022    /// Calculates the scroll top offset the minimap editor has to have based on the
10023    /// current scroll progress.
10024    fn calculate_minimap_top_offset(
10025        document_lines: f32,
10026        visible_editor_lines: f32,
10027        visible_minimap_lines: f32,
10028        scroll_position: f32,
10029    ) -> f32 {
10030        let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
10031        if non_visible_document_lines == 0. {
10032            0.
10033        } else {
10034            let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
10035            scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
10036        }
10037    }
10038}
10039
10040struct CreaseTrailerLayout {
10041    element: AnyElement,
10042    bounds: Bounds<Pixels>,
10043}
10044
10045pub(crate) struct PositionMap {
10046    pub size: Size<Pixels>,
10047    pub line_height: Pixels,
10048    pub scroll_pixel_position: gpui::Point<Pixels>,
10049    pub scroll_max: gpui::Point<f32>,
10050    pub em_width: Pixels,
10051    pub em_advance: Pixels,
10052    pub visible_row_range: Range<DisplayRow>,
10053    pub line_layouts: Vec<LineWithInvisibles>,
10054    pub snapshot: EditorSnapshot,
10055    pub text_hitbox: Hitbox,
10056    pub gutter_hitbox: Hitbox,
10057    pub inline_blame_bounds: Option<(Bounds<Pixels>, BufferId, BlameEntry)>,
10058    pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
10059    pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
10060}
10061
10062#[derive(Debug, Copy, Clone)]
10063pub struct PointForPosition {
10064    pub previous_valid: DisplayPoint,
10065    pub next_valid: DisplayPoint,
10066    pub exact_unclipped: DisplayPoint,
10067    pub column_overshoot_after_line_end: u32,
10068}
10069
10070impl PointForPosition {
10071    pub fn as_valid(&self) -> Option<DisplayPoint> {
10072        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
10073            Some(self.previous_valid)
10074        } else {
10075            None
10076        }
10077    }
10078
10079    pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
10080        let Some(valid_point) = self.as_valid() else {
10081            return false;
10082        };
10083        let range = selection.range();
10084
10085        let candidate_row = valid_point.row();
10086        let candidate_col = valid_point.column();
10087
10088        let start_row = range.start.row();
10089        let start_col = range.start.column();
10090        let end_row = range.end.row();
10091        let end_col = range.end.column();
10092
10093        if candidate_row < start_row || candidate_row > end_row {
10094            false
10095        } else if start_row == end_row {
10096            candidate_col >= start_col && candidate_col < end_col
10097        } else if candidate_row == start_row {
10098            candidate_col >= start_col
10099        } else if candidate_row == end_row {
10100            candidate_col < end_col
10101        } else {
10102            true
10103        }
10104    }
10105}
10106
10107impl PositionMap {
10108    pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
10109        let text_bounds = self.text_hitbox.bounds;
10110        let scroll_position = self.snapshot.scroll_position();
10111        let position = position - text_bounds.origin;
10112        let y = position.y.max(px(0.)).min(self.size.height);
10113        let x = position.x + (scroll_position.x * self.em_advance);
10114        let row = ((y / self.line_height) + scroll_position.y) as u32;
10115
10116        let (column, x_overshoot_after_line_end) = if let Some(line) = self
10117            .line_layouts
10118            .get(row as usize - scroll_position.y as usize)
10119        {
10120            if let Some(ix) = line.index_for_x(x) {
10121                (ix as u32, px(0.))
10122            } else {
10123                (line.len as u32, px(0.).max(x - line.width))
10124            }
10125        } else {
10126            (0, x)
10127        };
10128
10129        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
10130        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
10131        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
10132
10133        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
10134        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
10135        PointForPosition {
10136            previous_valid,
10137            next_valid,
10138            exact_unclipped,
10139            column_overshoot_after_line_end,
10140        }
10141    }
10142}
10143
10144struct BlockLayout {
10145    id: BlockId,
10146    x_offset: Pixels,
10147    row: Option<DisplayRow>,
10148    element: AnyElement,
10149    available_space: Size<AvailableSpace>,
10150    style: BlockStyle,
10151    overlaps_gutter: bool,
10152    is_buffer_header: bool,
10153}
10154
10155pub fn layout_line(
10156    row: DisplayRow,
10157    snapshot: &EditorSnapshot,
10158    style: &EditorStyle,
10159    text_width: Pixels,
10160    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
10161    window: &mut Window,
10162    cx: &mut App,
10163) -> LineWithInvisibles {
10164    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
10165    LineWithInvisibles::from_chunks(
10166        chunks,
10167        style,
10168        MAX_LINE_LEN,
10169        1,
10170        &snapshot.mode,
10171        text_width,
10172        is_row_soft_wrapped,
10173        &[],
10174        window,
10175        cx,
10176    )
10177    .pop()
10178    .unwrap()
10179}
10180
10181#[derive(Debug)]
10182pub struct IndentGuideLayout {
10183    origin: gpui::Point<Pixels>,
10184    length: Pixels,
10185    single_indent_width: Pixels,
10186    depth: u32,
10187    active: bool,
10188    settings: IndentGuideSettings,
10189}
10190
10191pub struct CursorLayout {
10192    origin: gpui::Point<Pixels>,
10193    block_width: Pixels,
10194    line_height: Pixels,
10195    color: Hsla,
10196    shape: CursorShape,
10197    block_text: Option<ShapedLine>,
10198    cursor_name: Option<AnyElement>,
10199}
10200
10201#[derive(Debug)]
10202pub struct CursorName {
10203    string: SharedString,
10204    color: Hsla,
10205    is_top_row: bool,
10206}
10207
10208impl CursorLayout {
10209    pub fn new(
10210        origin: gpui::Point<Pixels>,
10211        block_width: Pixels,
10212        line_height: Pixels,
10213        color: Hsla,
10214        shape: CursorShape,
10215        block_text: Option<ShapedLine>,
10216    ) -> CursorLayout {
10217        CursorLayout {
10218            origin,
10219            block_width,
10220            line_height,
10221            color,
10222            shape,
10223            block_text,
10224            cursor_name: None,
10225        }
10226    }
10227
10228    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
10229        Bounds {
10230            origin: self.origin + origin,
10231            size: size(self.block_width, self.line_height),
10232        }
10233    }
10234
10235    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
10236        match self.shape {
10237            CursorShape::Bar => Bounds {
10238                origin: self.origin + origin,
10239                size: size(px(2.0), self.line_height),
10240            },
10241            CursorShape::Block | CursorShape::Hollow => Bounds {
10242                origin: self.origin + origin,
10243                size: size(self.block_width, self.line_height),
10244            },
10245            CursorShape::Underline => Bounds {
10246                origin: self.origin
10247                    + origin
10248                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
10249                size: size(self.block_width, px(2.0)),
10250            },
10251        }
10252    }
10253
10254    pub fn layout(
10255        &mut self,
10256        origin: gpui::Point<Pixels>,
10257        cursor_name: Option<CursorName>,
10258        window: &mut Window,
10259        cx: &mut App,
10260    ) {
10261        if let Some(cursor_name) = cursor_name {
10262            let bounds = self.bounds(origin);
10263            let text_size = self.line_height / 1.5;
10264
10265            let name_origin = if cursor_name.is_top_row {
10266                point(bounds.right() - px(1.), bounds.top())
10267            } else {
10268                match self.shape {
10269                    CursorShape::Bar => point(
10270                        bounds.right() - px(2.),
10271                        bounds.top() - text_size / 2. - px(1.),
10272                    ),
10273                    _ => point(
10274                        bounds.right() - px(1.),
10275                        bounds.top() - text_size / 2. - px(1.),
10276                    ),
10277                }
10278            };
10279            let mut name_element = div()
10280                .bg(self.color)
10281                .text_size(text_size)
10282                .px_0p5()
10283                .line_height(text_size + px(2.))
10284                .text_color(cursor_name.color)
10285                .child(cursor_name.string)
10286                .into_any_element();
10287
10288            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
10289
10290            self.cursor_name = Some(name_element);
10291        }
10292    }
10293
10294    pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
10295        let bounds = self.bounds(origin);
10296
10297        //Draw background or border quad
10298        let cursor = if matches!(self.shape, CursorShape::Hollow) {
10299            outline(bounds, self.color, BorderStyle::Solid)
10300        } else {
10301            fill(bounds, self.color)
10302        };
10303
10304        if let Some(name) = &mut self.cursor_name {
10305            name.paint(window, cx);
10306        }
10307
10308        window.paint_quad(cursor);
10309
10310        if let Some(block_text) = &self.block_text {
10311            block_text
10312                .paint(self.origin + origin, self.line_height, window, cx)
10313                .log_err();
10314        }
10315    }
10316
10317    pub fn shape(&self) -> CursorShape {
10318        self.shape
10319    }
10320}
10321
10322#[derive(Debug)]
10323pub struct HighlightedRange {
10324    pub start_y: Pixels,
10325    pub line_height: Pixels,
10326    pub lines: Vec<HighlightedRangeLine>,
10327    pub color: Hsla,
10328    pub corner_radius: Pixels,
10329}
10330
10331#[derive(Debug)]
10332pub struct HighlightedRangeLine {
10333    pub start_x: Pixels,
10334    pub end_x: Pixels,
10335}
10336
10337impl HighlightedRange {
10338    pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
10339        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
10340            self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
10341            self.paint_lines(
10342                self.start_y + self.line_height,
10343                &self.lines[1..],
10344                fill,
10345                bounds,
10346                window,
10347            );
10348        } else {
10349            self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
10350        }
10351    }
10352
10353    fn paint_lines(
10354        &self,
10355        start_y: Pixels,
10356        lines: &[HighlightedRangeLine],
10357        fill: bool,
10358        _bounds: Bounds<Pixels>,
10359        window: &mut Window,
10360    ) {
10361        if lines.is_empty() {
10362            return;
10363        }
10364
10365        let first_line = lines.first().unwrap();
10366        let last_line = lines.last().unwrap();
10367
10368        let first_top_left = point(first_line.start_x, start_y);
10369        let first_top_right = point(first_line.end_x, start_y);
10370
10371        let curve_height = point(Pixels::ZERO, self.corner_radius);
10372        let curve_width = |start_x: Pixels, end_x: Pixels| {
10373            let max = (end_x - start_x) / 2.;
10374            let width = if max < self.corner_radius {
10375                max
10376            } else {
10377                self.corner_radius
10378            };
10379
10380            point(width, Pixels::ZERO)
10381        };
10382
10383        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
10384        let mut builder = if fill {
10385            gpui::PathBuilder::fill()
10386        } else {
10387            gpui::PathBuilder::stroke(px(1.))
10388        };
10389        builder.move_to(first_top_right - top_curve_width);
10390        builder.curve_to(first_top_right + curve_height, first_top_right);
10391
10392        let mut iter = lines.iter().enumerate().peekable();
10393        while let Some((ix, line)) = iter.next() {
10394            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
10395
10396            if let Some((_, next_line)) = iter.peek() {
10397                let next_top_right = point(next_line.end_x, bottom_right.y);
10398
10399                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
10400                    Ordering::Equal => {
10401                        builder.line_to(bottom_right);
10402                    }
10403                    Ordering::Less => {
10404                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
10405                        builder.line_to(bottom_right - curve_height);
10406                        if self.corner_radius > Pixels::ZERO {
10407                            builder.curve_to(bottom_right - curve_width, bottom_right);
10408                        }
10409                        builder.line_to(next_top_right + curve_width);
10410                        if self.corner_radius > Pixels::ZERO {
10411                            builder.curve_to(next_top_right + curve_height, next_top_right);
10412                        }
10413                    }
10414                    Ordering::Greater => {
10415                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
10416                        builder.line_to(bottom_right - curve_height);
10417                        if self.corner_radius > Pixels::ZERO {
10418                            builder.curve_to(bottom_right + curve_width, bottom_right);
10419                        }
10420                        builder.line_to(next_top_right - curve_width);
10421                        if self.corner_radius > Pixels::ZERO {
10422                            builder.curve_to(next_top_right + curve_height, next_top_right);
10423                        }
10424                    }
10425                }
10426            } else {
10427                let curve_width = curve_width(line.start_x, line.end_x);
10428                builder.line_to(bottom_right - curve_height);
10429                if self.corner_radius > Pixels::ZERO {
10430                    builder.curve_to(bottom_right - curve_width, bottom_right);
10431                }
10432
10433                let bottom_left = point(line.start_x, bottom_right.y);
10434                builder.line_to(bottom_left + curve_width);
10435                if self.corner_radius > Pixels::ZERO {
10436                    builder.curve_to(bottom_left - curve_height, bottom_left);
10437                }
10438            }
10439        }
10440
10441        if first_line.start_x > last_line.start_x {
10442            let curve_width = curve_width(last_line.start_x, first_line.start_x);
10443            let second_top_left = point(last_line.start_x, start_y + self.line_height);
10444            builder.line_to(second_top_left + curve_height);
10445            if self.corner_radius > Pixels::ZERO {
10446                builder.curve_to(second_top_left + curve_width, second_top_left);
10447            }
10448            let first_bottom_left = point(first_line.start_x, second_top_left.y);
10449            builder.line_to(first_bottom_left - curve_width);
10450            if self.corner_radius > Pixels::ZERO {
10451                builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
10452            }
10453        }
10454
10455        builder.line_to(first_top_left + curve_height);
10456        if self.corner_radius > Pixels::ZERO {
10457            builder.curve_to(first_top_left + top_curve_width, first_top_left);
10458        }
10459        builder.line_to(first_top_right - top_curve_width);
10460
10461        if let Ok(path) = builder.build() {
10462            window.paint_path(path, self.color);
10463        }
10464    }
10465}
10466
10467enum CursorPopoverType {
10468    CodeContextMenu,
10469    EditPrediction,
10470}
10471
10472pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
10473    (delta.pow(1.2) / 100.0).min(px(3.0)).into()
10474}
10475
10476fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
10477    (delta.pow(1.2) / 300.0).into()
10478}
10479
10480pub fn register_action<T: Action>(
10481    editor: &Entity<Editor>,
10482    window: &mut Window,
10483    listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
10484) {
10485    let editor = editor.clone();
10486    window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
10487        let action = action.downcast_ref().unwrap();
10488        if phase == DispatchPhase::Bubble {
10489            editor.update(cx, |editor, cx| {
10490                listener(editor, action, window, cx);
10491            })
10492        }
10493    })
10494}
10495
10496fn compute_auto_height_layout(
10497    editor: &mut Editor,
10498    min_lines: usize,
10499    max_lines: Option<usize>,
10500    max_line_number_width: Pixels,
10501    known_dimensions: Size<Option<Pixels>>,
10502    available_width: AvailableSpace,
10503    window: &mut Window,
10504    cx: &mut Context<Editor>,
10505) -> Option<Size<Pixels>> {
10506    let width = known_dimensions.width.or({
10507        if let AvailableSpace::Definite(available_width) = available_width {
10508            Some(available_width)
10509        } else {
10510            None
10511        }
10512    })?;
10513    if let Some(height) = known_dimensions.height {
10514        return Some(size(width, height));
10515    }
10516
10517    let style = editor.style.as_ref().unwrap();
10518    let font_id = window.text_system().resolve_font(&style.text.font());
10519    let font_size = style.text.font_size.to_pixels(window.rem_size());
10520    let line_height = style.text.line_height_in_pixels(window.rem_size());
10521    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
10522
10523    let mut snapshot = editor.snapshot(window, cx);
10524    let gutter_dimensions = snapshot
10525        .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
10526        .or_else(|| {
10527            editor
10528                .offset_content
10529                .then(|| GutterDimensions::default_with_margin(font_id, font_size, cx))
10530        })
10531        .unwrap_or_default();
10532
10533    editor.gutter_dimensions = gutter_dimensions;
10534    let text_width = width - gutter_dimensions.width;
10535    let overscroll = size(em_width, px(0.));
10536
10537    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
10538    if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None)
10539        && editor.set_wrap_width(Some(editor_width), cx)
10540    {
10541        snapshot = editor.snapshot(window, cx);
10542    }
10543
10544    let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
10545
10546    let min_height = line_height * min_lines as f32;
10547    let content_height = scroll_height.max(min_height);
10548
10549    let final_height = if let Some(max_lines) = max_lines {
10550        let max_height = line_height * max_lines as f32;
10551        content_height.min(max_height)
10552    } else {
10553        content_height
10554    };
10555
10556    Some(size(width, final_height))
10557}
10558
10559#[cfg(test)]
10560mod tests {
10561    use super::*;
10562    use crate::{
10563        Editor, MultiBuffer, SelectionEffects,
10564        display_map::{BlockPlacement, BlockProperties},
10565        editor_tests::{init_test, update_test_language_settings},
10566    };
10567    use gpui::{TestAppContext, VisualTestContext};
10568    use language::language_settings;
10569    use log::info;
10570    use std::num::NonZeroU32;
10571    use util::test::sample_text;
10572
10573    #[gpui::test]
10574    async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
10575        init_test(cx, |_| {});
10576
10577        let window = cx.add_window(|window, cx| {
10578            let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
10579            let mut editor = Editor::new(
10580                EditorMode::AutoHeight {
10581                    min_lines: 1,
10582                    max_lines: None,
10583                },
10584                buffer,
10585                None,
10586                window,
10587                cx,
10588            );
10589            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10590            editor
10591        });
10592        let cx = &mut VisualTestContext::from_window(*window, cx);
10593        let editor = window.root(cx).unwrap();
10594        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10595
10596        for x in 1..=100 {
10597            let (_, state) = cx.draw(
10598                Default::default(),
10599                size(px(200. + 0.13 * x as f32), px(500.)),
10600                |_, _| EditorElement::new(&editor, style.clone()),
10601            );
10602
10603            assert!(
10604                state.position_map.scroll_max.x == 0.,
10605                "Soft wrapped editor should have no horizontal scrolling!"
10606            );
10607        }
10608    }
10609
10610    #[gpui::test]
10611    async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
10612        init_test(cx, |_| {});
10613
10614        let window = cx.add_window(|window, cx| {
10615            let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
10616            let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
10617            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10618            editor
10619        });
10620        let cx = &mut VisualTestContext::from_window(*window, cx);
10621        let editor = window.root(cx).unwrap();
10622        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10623
10624        for x in 1..=100 {
10625            let (_, state) = cx.draw(
10626                Default::default(),
10627                size(px(200. + 0.13 * x as f32), px(500.)),
10628                |_, _| EditorElement::new(&editor, style.clone()),
10629            );
10630
10631            assert!(
10632                state.position_map.scroll_max.x == 0.,
10633                "Soft wrapped editor should have no horizontal scrolling!"
10634            );
10635        }
10636    }
10637
10638    #[gpui::test]
10639    fn test_shape_line_numbers(cx: &mut TestAppContext) {
10640        init_test(cx, |_| {});
10641        let window = cx.add_window(|window, cx| {
10642            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
10643            Editor::new(EditorMode::full(), buffer, None, window, cx)
10644        });
10645
10646        let editor = window.root(cx).unwrap();
10647        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
10648        let line_height = window
10649            .update(cx, |_, window, _| {
10650                style.text.line_height_in_pixels(window.rem_size())
10651            })
10652            .unwrap();
10653        let element = EditorElement::new(&editor, style);
10654        let snapshot = window
10655            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
10656            .unwrap();
10657
10658        let layouts = cx
10659            .update_window(*window, |_, window, cx| {
10660                element.layout_line_numbers(
10661                    None,
10662                    GutterDimensions {
10663                        left_padding: Pixels::ZERO,
10664                        right_padding: Pixels::ZERO,
10665                        width: px(30.0),
10666                        margin: Pixels::ZERO,
10667                        git_blame_entries_width: None,
10668                    },
10669                    line_height,
10670                    gpui::Point::default(),
10671                    DisplayRow(0)..DisplayRow(6),
10672                    &(0..6)
10673                        .map(|row| RowInfo {
10674                            buffer_row: Some(row),
10675                            ..Default::default()
10676                        })
10677                        .collect::<Vec<_>>(),
10678                    &BTreeMap::default(),
10679                    Some(DisplayPoint::new(DisplayRow(0), 0)),
10680                    &snapshot,
10681                    window,
10682                    cx,
10683                )
10684            })
10685            .unwrap();
10686        assert_eq!(layouts.len(), 6);
10687
10688        let relative_rows = window
10689            .update(cx, |editor, window, cx| {
10690                let snapshot = editor.snapshot(window, cx);
10691                element.calculate_relative_line_numbers(
10692                    &snapshot,
10693                    &(DisplayRow(0)..DisplayRow(6)),
10694                    Some(DisplayRow(3)),
10695                )
10696            })
10697            .unwrap();
10698        assert_eq!(relative_rows[&DisplayRow(0)], 3);
10699        assert_eq!(relative_rows[&DisplayRow(1)], 2);
10700        assert_eq!(relative_rows[&DisplayRow(2)], 1);
10701        // current line has no relative number
10702        assert_eq!(relative_rows[&DisplayRow(4)], 1);
10703        assert_eq!(relative_rows[&DisplayRow(5)], 2);
10704
10705        // works if cursor is before screen
10706        let relative_rows = window
10707            .update(cx, |editor, window, cx| {
10708                let snapshot = editor.snapshot(window, cx);
10709                element.calculate_relative_line_numbers(
10710                    &snapshot,
10711                    &(DisplayRow(3)..DisplayRow(6)),
10712                    Some(DisplayRow(1)),
10713                )
10714            })
10715            .unwrap();
10716        assert_eq!(relative_rows.len(), 3);
10717        assert_eq!(relative_rows[&DisplayRow(3)], 2);
10718        assert_eq!(relative_rows[&DisplayRow(4)], 3);
10719        assert_eq!(relative_rows[&DisplayRow(5)], 4);
10720
10721        // works if cursor is after screen
10722        let relative_rows = window
10723            .update(cx, |editor, window, cx| {
10724                let snapshot = editor.snapshot(window, cx);
10725                element.calculate_relative_line_numbers(
10726                    &snapshot,
10727                    &(DisplayRow(0)..DisplayRow(3)),
10728                    Some(DisplayRow(6)),
10729                )
10730            })
10731            .unwrap();
10732        assert_eq!(relative_rows.len(), 3);
10733        assert_eq!(relative_rows[&DisplayRow(0)], 5);
10734        assert_eq!(relative_rows[&DisplayRow(1)], 4);
10735        assert_eq!(relative_rows[&DisplayRow(2)], 3);
10736    }
10737
10738    #[gpui::test]
10739    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
10740        init_test(cx, |_| {});
10741
10742        let window = cx.add_window(|window, cx| {
10743            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
10744            Editor::new(EditorMode::full(), buffer, None, window, cx)
10745        });
10746        let cx = &mut VisualTestContext::from_window(*window, cx);
10747        let editor = window.root(cx).unwrap();
10748        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10749
10750        window
10751            .update(cx, |editor, window, cx| {
10752                editor.cursor_shape = CursorShape::Block;
10753                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
10754                    s.select_ranges([
10755                        Point::new(0, 0)..Point::new(1, 0),
10756                        Point::new(3, 2)..Point::new(3, 3),
10757                        Point::new(5, 6)..Point::new(6, 0),
10758                    ]);
10759                });
10760            })
10761            .unwrap();
10762
10763        let (_, state) = cx.draw(
10764            point(px(500.), px(500.)),
10765            size(px(500.), px(500.)),
10766            |_, _| EditorElement::new(&editor, style),
10767        );
10768
10769        assert_eq!(state.selections.len(), 1);
10770        let local_selections = &state.selections[0].1;
10771        assert_eq!(local_selections.len(), 3);
10772        // moves cursor back one line
10773        assert_eq!(
10774            local_selections[0].head,
10775            DisplayPoint::new(DisplayRow(0), 6)
10776        );
10777        assert_eq!(
10778            local_selections[0].range,
10779            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
10780        );
10781
10782        // moves cursor back one column
10783        assert_eq!(
10784            local_selections[1].range,
10785            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
10786        );
10787        assert_eq!(
10788            local_selections[1].head,
10789            DisplayPoint::new(DisplayRow(3), 2)
10790        );
10791
10792        // leaves cursor on the max point
10793        assert_eq!(
10794            local_selections[2].range,
10795            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
10796        );
10797        assert_eq!(
10798            local_selections[2].head,
10799            DisplayPoint::new(DisplayRow(6), 0)
10800        );
10801
10802        // active lines does not include 1 (even though the range of the selection does)
10803        assert_eq!(
10804            state.active_rows.keys().cloned().collect::<Vec<_>>(),
10805            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
10806        );
10807    }
10808
10809    #[gpui::test]
10810    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
10811        init_test(cx, |_| {});
10812
10813        let window = cx.add_window(|window, cx| {
10814            let buffer = MultiBuffer::build_simple("", cx);
10815            Editor::new(EditorMode::full(), buffer, None, window, cx)
10816        });
10817        let cx = &mut VisualTestContext::from_window(*window, cx);
10818        let editor = window.root(cx).unwrap();
10819        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10820        window
10821            .update(cx, |editor, window, cx| {
10822                editor.set_placeholder_text("hello", window, cx);
10823                editor.insert_blocks(
10824                    [BlockProperties {
10825                        style: BlockStyle::Fixed,
10826                        placement: BlockPlacement::Above(Anchor::min()),
10827                        height: Some(3),
10828                        render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
10829                        priority: 0,
10830                    }],
10831                    None,
10832                    cx,
10833                );
10834
10835                // Blur the editor so that it displays placeholder text.
10836                window.blur();
10837            })
10838            .unwrap();
10839
10840        let (_, state) = cx.draw(
10841            point(px(500.), px(500.)),
10842            size(px(500.), px(500.)),
10843            |_, _| EditorElement::new(&editor, style),
10844        );
10845        assert_eq!(state.position_map.line_layouts.len(), 4);
10846        assert_eq!(state.line_numbers.len(), 1);
10847        assert_eq!(
10848            state
10849                .line_numbers
10850                .get(&MultiBufferRow(0))
10851                .map(|line_number| line_number.shaped_line.text.as_ref()),
10852            Some("1")
10853        );
10854    }
10855
10856    #[gpui::test]
10857    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
10858        const TAB_SIZE: u32 = 4;
10859
10860        let input_text = "\t \t|\t| a b";
10861        let expected_invisibles = vec![
10862            Invisible::Tab {
10863                line_start_offset: 0,
10864                line_end_offset: TAB_SIZE as usize,
10865            },
10866            Invisible::Whitespace {
10867                line_offset: TAB_SIZE as usize,
10868            },
10869            Invisible::Tab {
10870                line_start_offset: TAB_SIZE as usize + 1,
10871                line_end_offset: TAB_SIZE as usize * 2,
10872            },
10873            Invisible::Tab {
10874                line_start_offset: TAB_SIZE as usize * 2 + 1,
10875                line_end_offset: TAB_SIZE as usize * 3,
10876            },
10877            Invisible::Whitespace {
10878                line_offset: TAB_SIZE as usize * 3 + 1,
10879            },
10880            Invisible::Whitespace {
10881                line_offset: TAB_SIZE as usize * 3 + 3,
10882            },
10883        ];
10884        assert_eq!(
10885            expected_invisibles.len(),
10886            input_text
10887                .chars()
10888                .filter(|initial_char| initial_char.is_whitespace())
10889                .count(),
10890            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10891        );
10892
10893        for show_line_numbers in [true, false] {
10894            init_test(cx, |s| {
10895                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10896                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
10897            });
10898
10899            let actual_invisibles = collect_invisibles_from_new_editor(
10900                cx,
10901                EditorMode::full(),
10902                input_text,
10903                px(500.0),
10904                show_line_numbers,
10905            );
10906
10907            assert_eq!(expected_invisibles, actual_invisibles);
10908        }
10909    }
10910
10911    #[gpui::test]
10912    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
10913        init_test(cx, |s| {
10914            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10915            s.defaults.tab_size = NonZeroU32::new(4);
10916        });
10917
10918        for editor_mode_without_invisibles in [
10919            EditorMode::SingleLine,
10920            EditorMode::AutoHeight {
10921                min_lines: 1,
10922                max_lines: Some(100),
10923            },
10924        ] {
10925            for show_line_numbers in [true, false] {
10926                let invisibles = collect_invisibles_from_new_editor(
10927                    cx,
10928                    editor_mode_without_invisibles.clone(),
10929                    "\t\t\t| | a b",
10930                    px(500.0),
10931                    show_line_numbers,
10932                );
10933                assert!(
10934                    invisibles.is_empty(),
10935                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
10936                );
10937            }
10938        }
10939    }
10940
10941    #[gpui::test]
10942    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
10943        let tab_size = 4;
10944        let input_text = "a\tbcd     ".repeat(9);
10945        let repeated_invisibles = [
10946            Invisible::Tab {
10947                line_start_offset: 1,
10948                line_end_offset: tab_size as usize,
10949            },
10950            Invisible::Whitespace {
10951                line_offset: tab_size as usize + 3,
10952            },
10953            Invisible::Whitespace {
10954                line_offset: tab_size as usize + 4,
10955            },
10956            Invisible::Whitespace {
10957                line_offset: tab_size as usize + 5,
10958            },
10959            Invisible::Whitespace {
10960                line_offset: tab_size as usize + 6,
10961            },
10962            Invisible::Whitespace {
10963                line_offset: tab_size as usize + 7,
10964            },
10965        ];
10966        let expected_invisibles = std::iter::once(repeated_invisibles)
10967            .cycle()
10968            .take(9)
10969            .flatten()
10970            .collect::<Vec<_>>();
10971        assert_eq!(
10972            expected_invisibles.len(),
10973            input_text
10974                .chars()
10975                .filter(|initial_char| initial_char.is_whitespace())
10976                .count(),
10977            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10978        );
10979        info!("Expected invisibles: {expected_invisibles:?}");
10980
10981        init_test(cx, |_| {});
10982
10983        // Put the same string with repeating whitespace pattern into editors of various size,
10984        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
10985        let resize_step = 10.0;
10986        let mut editor_width = 200.0;
10987        while editor_width <= 1000.0 {
10988            for show_line_numbers in [true, false] {
10989                update_test_language_settings(cx, |s| {
10990                    s.defaults.tab_size = NonZeroU32::new(tab_size);
10991                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10992                    s.defaults.preferred_line_length = Some(editor_width as u32);
10993                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
10994                });
10995
10996                let actual_invisibles = collect_invisibles_from_new_editor(
10997                    cx,
10998                    EditorMode::full(),
10999                    &input_text,
11000                    px(editor_width),
11001                    show_line_numbers,
11002                );
11003
11004                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
11005                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
11006                let mut i = 0;
11007                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
11008                    i = actual_index;
11009                    match expected_invisibles.get(i) {
11010                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
11011                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
11012                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
11013                            _ => {
11014                                panic!(
11015                                    "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
11016                                )
11017                            }
11018                        },
11019                        None => {
11020                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
11021                        }
11022                    }
11023                }
11024                let missing_expected_invisibles = &expected_invisibles[i + 1..];
11025                assert!(
11026                    missing_expected_invisibles.is_empty(),
11027                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
11028                );
11029
11030                editor_width += resize_step;
11031            }
11032        }
11033    }
11034
11035    fn collect_invisibles_from_new_editor(
11036        cx: &mut TestAppContext,
11037        editor_mode: EditorMode,
11038        input_text: &str,
11039        editor_width: Pixels,
11040        show_line_numbers: bool,
11041    ) -> Vec<Invisible> {
11042        info!(
11043            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
11044            editor_width.0
11045        );
11046        let window = cx.add_window(|window, cx| {
11047            let buffer = MultiBuffer::build_simple(input_text, cx);
11048            Editor::new(editor_mode, buffer, None, window, cx)
11049        });
11050        let cx = &mut VisualTestContext::from_window(*window, cx);
11051        let editor = window.root(cx).unwrap();
11052
11053        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
11054        window
11055            .update(cx, |editor, _, cx| {
11056                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
11057                editor.set_wrap_width(Some(editor_width), cx);
11058                editor.set_show_line_numbers(show_line_numbers, cx);
11059            })
11060            .unwrap();
11061        let (_, state) = cx.draw(
11062            point(px(500.), px(500.)),
11063            size(px(500.), px(500.)),
11064            |_, _| EditorElement::new(&editor, style),
11065        );
11066        state
11067            .position_map
11068            .line_layouts
11069            .iter()
11070            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
11071            .cloned()
11072            .collect()
11073    }
11074
11075    #[gpui::test]
11076    fn test_merge_overlapping_ranges() {
11077        let base_bg = Hsla::white();
11078        let color1 = Hsla {
11079            h: 0.0,
11080            s: 0.5,
11081            l: 0.5,
11082            a: 0.5,
11083        };
11084        let color2 = Hsla {
11085            h: 120.0,
11086            s: 0.5,
11087            l: 0.5,
11088            a: 0.5,
11089        };
11090
11091        let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
11092        let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
11093            v.iter()
11094                .map(|(r, _)| (r.start.column(), r.end.column()))
11095                .collect()
11096        };
11097
11098        // Test overlapping ranges blend colors
11099        let overlapping = vec![
11100            (display_point(5)..display_point(15), color1),
11101            (display_point(10)..display_point(20), color2),
11102        ];
11103        let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
11104        assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
11105
11106        // Test middle segment should have blended color
11107        let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
11108        assert_eq!(result[1].1, blended);
11109
11110        // Test adjacent same-color ranges merge
11111        let adjacent_same = vec![
11112            (display_point(5)..display_point(10), color1),
11113            (display_point(10)..display_point(15), color1),
11114        ];
11115        let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
11116        assert_eq!(cols(&result), vec![(5, 15)]);
11117
11118        // Test contained range splits
11119        let contained = vec![
11120            (display_point(5)..display_point(20), color1),
11121            (display_point(10)..display_point(15), color2),
11122        ];
11123        let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
11124        assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
11125
11126        // Test multiple overlaps split at every boundary
11127        let color3 = Hsla {
11128            h: 240.0,
11129            s: 0.5,
11130            l: 0.5,
11131            a: 0.5,
11132        };
11133        let complex = vec![
11134            (display_point(5)..display_point(12), color1),
11135            (display_point(8)..display_point(16), color2),
11136            (display_point(10)..display_point(14), color3),
11137        ];
11138        let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
11139        assert_eq!(
11140            cols(&result),
11141            vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
11142        );
11143    }
11144
11145    #[gpui::test]
11146    fn test_bg_segments_per_row() {
11147        let base_bg = Hsla::white();
11148
11149        // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
11150        {
11151            let selection_color = Hsla {
11152                h: 200.0,
11153                s: 0.5,
11154                l: 0.5,
11155                a: 0.5,
11156            };
11157            let player_color = PlayerColor {
11158                cursor: selection_color,
11159                background: selection_color,
11160                selection: selection_color,
11161            };
11162
11163            let spanning_selection = SelectionLayout {
11164                head: DisplayPoint::new(DisplayRow(3), 7),
11165                cursor_shape: CursorShape::Bar,
11166                is_newest: true,
11167                is_local: true,
11168                range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
11169                active_rows: DisplayRow(1)..DisplayRow(4),
11170                user_name: None,
11171            };
11172
11173            let selections = vec![(player_color, vec![spanning_selection])];
11174            let result = EditorElement::bg_segments_per_row(
11175                DisplayRow(0)..DisplayRow(5),
11176                &selections,
11177                &[],
11178                base_bg,
11179            );
11180
11181            assert_eq!(result.len(), 5);
11182            assert!(result[0].is_empty());
11183            assert_eq!(result[1].len(), 1);
11184            assert_eq!(result[2].len(), 1);
11185            assert_eq!(result[3].len(), 1);
11186            assert!(result[4].is_empty());
11187
11188            assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
11189            assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
11190            assert_eq!(result[1][0].0.end.column(), u32::MAX);
11191            assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
11192            assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
11193            assert_eq!(result[2][0].0.end.column(), u32::MAX);
11194            assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
11195            assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
11196        }
11197
11198        // Case B: selection ends exactly at the start of row 3, excluding row 3
11199        {
11200            let selection_color = Hsla {
11201                h: 120.0,
11202                s: 0.5,
11203                l: 0.5,
11204                a: 0.5,
11205            };
11206            let player_color = PlayerColor {
11207                cursor: selection_color,
11208                background: selection_color,
11209                selection: selection_color,
11210            };
11211
11212            let selection = SelectionLayout {
11213                head: DisplayPoint::new(DisplayRow(2), 0),
11214                cursor_shape: CursorShape::Bar,
11215                is_newest: true,
11216                is_local: true,
11217                range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
11218                active_rows: DisplayRow(1)..DisplayRow(3),
11219                user_name: None,
11220            };
11221
11222            let selections = vec![(player_color, vec![selection])];
11223            let result = EditorElement::bg_segments_per_row(
11224                DisplayRow(0)..DisplayRow(4),
11225                &selections,
11226                &[],
11227                base_bg,
11228            );
11229
11230            assert_eq!(result.len(), 4);
11231            assert!(result[0].is_empty());
11232            assert_eq!(result[1].len(), 1);
11233            assert_eq!(result[2].len(), 1);
11234            assert!(result[3].is_empty());
11235
11236            assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
11237            assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
11238            assert_eq!(result[1][0].0.end.column(), u32::MAX);
11239            assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
11240            assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
11241            assert_eq!(result[2][0].0.end.column(), u32::MAX);
11242        }
11243    }
11244
11245    #[cfg(test)]
11246    fn generate_test_run(len: usize, color: Hsla) -> TextRun {
11247        TextRun {
11248            len,
11249            font: gpui::font(".SystemUIFont"),
11250            color,
11251            background_color: None,
11252            underline: None,
11253            strikethrough: None,
11254        }
11255    }
11256
11257    #[gpui::test]
11258    fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
11259        init_test(cx, |_| {});
11260
11261        let text_color = Hsla {
11262            h: 210.0,
11263            s: 0.1,
11264            l: 0.4,
11265            a: 1.0,
11266        };
11267        let bg1 = Hsla {
11268            h: 30.0,
11269            s: 0.6,
11270            l: 0.8,
11271            a: 1.0,
11272        };
11273        let bg2 = Hsla {
11274            h: 200.0,
11275            s: 0.6,
11276            l: 0.2,
11277            a: 1.0,
11278        };
11279        let min_contrast = 45.0;
11280
11281        // Case A: single run; disjoint segments inside the run
11282        let runs = vec![generate_test_run(20, text_color)];
11283        let segs = vec![
11284            (
11285                DisplayPoint::new(DisplayRow(0), 5)..DisplayPoint::new(DisplayRow(0), 10),
11286                bg1,
11287            ),
11288            (
11289                DisplayPoint::new(DisplayRow(0), 12)..DisplayPoint::new(DisplayRow(0), 16),
11290                bg2,
11291            ),
11292        ];
11293        let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast);
11294        // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
11295        assert_eq!(
11296            out.iter().map(|r| r.len).collect::<Vec<_>>(),
11297            vec![5, 5, 2, 4, 4]
11298        );
11299        assert_eq!(out[0].color, text_color);
11300        assert_eq!(
11301            out[1].color,
11302            ensure_minimum_contrast(text_color, bg1, min_contrast)
11303        );
11304        assert_eq!(out[2].color, text_color);
11305        assert_eq!(
11306            out[3].color,
11307            ensure_minimum_contrast(text_color, bg2, min_contrast)
11308        );
11309        assert_eq!(out[4].color, text_color);
11310
11311        // Case B: multiple runs; segment extends to end of line (u32::MAX)
11312        let runs = vec![
11313            generate_test_run(8, text_color),
11314            generate_test_run(7, text_color),
11315        ];
11316        let segs = vec![(
11317            DisplayPoint::new(DisplayRow(0), 6)..DisplayPoint::new(DisplayRow(0), u32::MAX),
11318            bg1,
11319        )];
11320        let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast);
11321        // Expected slices across runs: [0,6) [6,8) | [0,7)
11322        assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
11323        let adjusted = ensure_minimum_contrast(text_color, bg1, min_contrast);
11324        assert_eq!(out[0].color, text_color);
11325        assert_eq!(out[1].color, adjusted);
11326        assert_eq!(out[2].color, adjusted);
11327
11328        // Case C: multi-byte characters
11329        // for text: "Hello 🌍 δΈ–η•Œ!"
11330        let runs = vec![
11331            generate_test_run(5, text_color), // "Hello"
11332            generate_test_run(6, text_color), // " 🌍 "
11333            generate_test_run(6, text_color), // "δΈ–η•Œ"
11334            generate_test_run(1, text_color), // "!"
11335        ];
11336        // selecting "🌍 δΈ–"
11337        let segs = vec![(
11338            DisplayPoint::new(DisplayRow(0), 6)..DisplayPoint::new(DisplayRow(0), 14),
11339            bg1,
11340        )];
11341        let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast);
11342        // "Hello" | " " | "🌍 " | "δΈ–" | "η•Œ" | "!"
11343        assert_eq!(
11344            out.iter().map(|r| r.len).collect::<Vec<_>>(),
11345            vec![5, 1, 5, 3, 3, 1]
11346        );
11347        assert_eq!(out[0].color, text_color); // "Hello"
11348        assert_eq!(
11349            out[2].color,
11350            ensure_minimum_contrast(text_color, bg1, min_contrast)
11351        ); // "🌍 "
11352        assert_eq!(
11353            out[3].color,
11354            ensure_minimum_contrast(text_color, bg1, min_contrast)
11355        ); // "δΈ–"
11356        assert_eq!(out[4].color, text_color); // "η•Œ"
11357        assert_eq!(out[5].color, text_color); // "!"
11358    }
11359}