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