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