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