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