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