element.rs

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