element.rs

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