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