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