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