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