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