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