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 = file.is_none_or(|file| file.can_open());
 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                    if x < text_hitbox.bounds.left() {
 5795                        continue;
 5796                    }
 5797
 5798                    let bounds = Bounds::new(gpui::Point::new(x, y), size);
 5799                    control_bounds.push((display_row_range.start, bounds));
 5800
 5801                    window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
 5802                        element.prepaint(window, cx)
 5803                    });
 5804                    controls.push(element);
 5805                }
 5806            }
 5807        }
 5808
 5809        (controls, control_bounds)
 5810    }
 5811
 5812    fn layout_signature_help(
 5813        &self,
 5814        hitbox: &Hitbox,
 5815        content_origin: gpui::Point<Pixels>,
 5816        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 5817        newest_selection_head: Option<DisplayPoint>,
 5818        start_row: DisplayRow,
 5819        line_layouts: &[LineWithInvisibles],
 5820        line_height: Pixels,
 5821        em_width: Pixels,
 5822        context_menu_layout: Option<ContextMenuLayout>,
 5823        window: &mut Window,
 5824        cx: &mut App,
 5825    ) {
 5826        if !self.editor.focus_handle(cx).is_focused(window) {
 5827            return;
 5828        }
 5829        let Some(newest_selection_head) = newest_selection_head else {
 5830            return;
 5831        };
 5832
 5833        let max_size = size(
 5834            (120. * em_width) // Default size
 5835                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
 5836                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
 5837            (16. * line_height) // Default size
 5838                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
 5839                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
 5840        );
 5841
 5842        let maybe_element = self.editor.update(cx, |editor, cx| {
 5843            if let Some(popover) = editor.signature_help_state.popover_mut() {
 5844                let element = popover.render(max_size, window, cx);
 5845                Some(element)
 5846            } else {
 5847                None
 5848            }
 5849        });
 5850        let Some(mut element) = maybe_element else {
 5851            return;
 5852        };
 5853
 5854        let selection_row = newest_selection_head.row();
 5855        let Some(cursor_row_layout) = (selection_row >= start_row)
 5856            .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
 5857            .flatten()
 5858        else {
 5859            return;
 5860        };
 5861
 5862        let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
 5863            - Pixels::from(scroll_pixel_position.x);
 5864        let target_y = Pixels::from(
 5865            selection_row.as_f64() * ScrollPixelOffset::from(line_height) - scroll_pixel_position.y,
 5866        );
 5867        let target_point = content_origin + point(target_x, target_y);
 5868
 5869        let actual_size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
 5870
 5871        let (popover_bounds_above, popover_bounds_below) = {
 5872            let horizontal_offset = (hitbox.top_right().x
 5873                - POPOVER_RIGHT_OFFSET
 5874                - (target_point.x + actual_size.width))
 5875                .min(Pixels::ZERO);
 5876            let initial_x = target_point.x + horizontal_offset;
 5877            (
 5878                Bounds::new(
 5879                    point(initial_x, target_point.y - actual_size.height),
 5880                    actual_size,
 5881                ),
 5882                Bounds::new(
 5883                    point(initial_x, target_point.y + line_height + HOVER_POPOVER_GAP),
 5884                    actual_size,
 5885                ),
 5886            )
 5887        };
 5888
 5889        let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
 5890            context_menu_layout
 5891                .as_ref()
 5892                .is_some_and(|menu| bounds.intersects(&menu.bounds))
 5893        };
 5894
 5895        let final_origin = if popover_bounds_above.is_contained_within(hitbox)
 5896            && !intersects_menu(popover_bounds_above)
 5897        {
 5898            // try placing above cursor
 5899            popover_bounds_above.origin
 5900        } else if popover_bounds_below.is_contained_within(hitbox)
 5901            && !intersects_menu(popover_bounds_below)
 5902        {
 5903            // try placing below cursor
 5904            popover_bounds_below.origin
 5905        } else {
 5906            // try surrounding context menu if exists
 5907            let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
 5908                let y_for_horizontal_positioning = if menu.y_flipped {
 5909                    menu.bounds.bottom() - actual_size.height
 5910                } else {
 5911                    menu.bounds.top()
 5912                };
 5913                let possible_origins = vec![
 5914                    // left of context menu
 5915                    point(
 5916                        menu.bounds.left() - actual_size.width - HOVER_POPOVER_GAP,
 5917                        y_for_horizontal_positioning,
 5918                    ),
 5919                    // right of context menu
 5920                    point(
 5921                        menu.bounds.right() + HOVER_POPOVER_GAP,
 5922                        y_for_horizontal_positioning,
 5923                    ),
 5924                    // top of context menu
 5925                    point(
 5926                        menu.bounds.left(),
 5927                        menu.bounds.top() - actual_size.height - HOVER_POPOVER_GAP,
 5928                    ),
 5929                    // bottom of context menu
 5930                    point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
 5931                ];
 5932                possible_origins
 5933                    .into_iter()
 5934                    .find(|&origin| Bounds::new(origin, actual_size).is_contained_within(hitbox))
 5935            });
 5936            origin_surrounding_menu.unwrap_or_else(|| {
 5937                // fallback to existing above/below cursor logic
 5938                // this might overlap menu or overflow in rare case
 5939                if popover_bounds_above.is_contained_within(hitbox) {
 5940                    popover_bounds_above.origin
 5941                } else {
 5942                    popover_bounds_below.origin
 5943                }
 5944            })
 5945        };
 5946
 5947        window.defer_draw(element, final_origin, 2);
 5948    }
 5949
 5950    fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
 5951        window.paint_layer(layout.hitbox.bounds, |window| {
 5952            let scroll_top = layout.position_map.snapshot.scroll_position().y;
 5953            let gutter_bg = cx.theme().colors().editor_gutter_background;
 5954            window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
 5955            window.paint_quad(fill(
 5956                layout.position_map.text_hitbox.bounds,
 5957                self.style.background,
 5958            ));
 5959
 5960            if matches!(
 5961                layout.mode,
 5962                EditorMode::Full { .. } | EditorMode::Minimap { .. }
 5963            ) {
 5964                let show_active_line_background = match layout.mode {
 5965                    EditorMode::Full {
 5966                        show_active_line_background,
 5967                        ..
 5968                    } => show_active_line_background,
 5969                    EditorMode::Minimap { .. } => true,
 5970                    _ => false,
 5971                };
 5972                let mut active_rows = layout.active_rows.iter().peekable();
 5973                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
 5974                    let mut end_row = start_row.0;
 5975                    while active_rows
 5976                        .peek()
 5977                        .is_some_and(|(active_row, has_selection)| {
 5978                            active_row.0 == end_row + 1
 5979                                && has_selection.selection == contains_non_empty_selection.selection
 5980                        })
 5981                    {
 5982                        active_rows.next().unwrap();
 5983                        end_row += 1;
 5984                    }
 5985
 5986                    if show_active_line_background && !contains_non_empty_selection.selection {
 5987                        let highlight_h_range =
 5988                            match layout.position_map.snapshot.current_line_highlight {
 5989                                CurrentLineHighlight::Gutter => Some(Range {
 5990                                    start: layout.hitbox.left(),
 5991                                    end: layout.gutter_hitbox.right(),
 5992                                }),
 5993                                CurrentLineHighlight::Line => Some(Range {
 5994                                    start: layout.position_map.text_hitbox.bounds.left(),
 5995                                    end: layout.position_map.text_hitbox.bounds.right(),
 5996                                }),
 5997                                CurrentLineHighlight::All => Some(Range {
 5998                                    start: layout.hitbox.left(),
 5999                                    end: layout.hitbox.right(),
 6000                                }),
 6001                                CurrentLineHighlight::None => None,
 6002                            };
 6003                        if let Some(range) = highlight_h_range {
 6004                            let active_line_bg = cx.theme().colors().editor_active_line_background;
 6005                            let bounds = Bounds {
 6006                                origin: point(
 6007                                    range.start,
 6008                                    layout.hitbox.origin.y
 6009                                        + Pixels::from(
 6010                                            (start_row.as_f64() - scroll_top)
 6011                                                * ScrollPixelOffset::from(
 6012                                                    layout.position_map.line_height,
 6013                                                ),
 6014                                        ),
 6015                                ),
 6016                                size: size(
 6017                                    range.end - range.start,
 6018                                    layout.position_map.line_height
 6019                                        * (end_row - start_row.0 + 1) as f32,
 6020                                ),
 6021                            };
 6022                            window.paint_quad(fill(bounds, active_line_bg));
 6023                        }
 6024                    }
 6025                }
 6026
 6027                let mut paint_highlight = |highlight_row_start: DisplayRow,
 6028                                           highlight_row_end: DisplayRow,
 6029                                           highlight: crate::LineHighlight,
 6030                                           edges| {
 6031                    let mut origin_x = layout.hitbox.left();
 6032                    let mut width = layout.hitbox.size.width;
 6033                    if !highlight.include_gutter {
 6034                        origin_x += layout.gutter_hitbox.size.width;
 6035                        width -= layout.gutter_hitbox.size.width;
 6036                    }
 6037
 6038                    let origin = point(
 6039                        origin_x,
 6040                        layout.hitbox.origin.y
 6041                            + Pixels::from(
 6042                                (highlight_row_start.as_f64() - scroll_top)
 6043                                    * ScrollPixelOffset::from(layout.position_map.line_height),
 6044                            ),
 6045                    );
 6046                    let size = size(
 6047                        width,
 6048                        layout.position_map.line_height
 6049                            * highlight_row_end.next_row().minus(highlight_row_start) as f32,
 6050                    );
 6051                    let mut quad = fill(Bounds { origin, size }, highlight.background);
 6052                    if let Some(border_color) = highlight.border {
 6053                        quad.border_color = border_color;
 6054                        quad.border_widths = edges
 6055                    }
 6056                    window.paint_quad(quad);
 6057                };
 6058
 6059                let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
 6060                    None;
 6061                for (&new_row, &new_background) in &layout.highlighted_rows {
 6062                    match &mut current_paint {
 6063                        &mut Some((current_background, ref mut current_range, mut edges)) => {
 6064                            let new_range_started = current_background != new_background
 6065                                || current_range.end.next_row() != new_row;
 6066                            if new_range_started {
 6067                                if current_range.end.next_row() == new_row {
 6068                                    edges.bottom = px(0.);
 6069                                };
 6070                                paint_highlight(
 6071                                    current_range.start,
 6072                                    current_range.end,
 6073                                    current_background,
 6074                                    edges,
 6075                                );
 6076                                let edges = Edges {
 6077                                    top: if current_range.end.next_row() != new_row {
 6078                                        px(1.)
 6079                                    } else {
 6080                                        px(0.)
 6081                                    },
 6082                                    bottom: px(1.),
 6083                                    ..Default::default()
 6084                                };
 6085                                current_paint = Some((new_background, new_row..new_row, edges));
 6086                                continue;
 6087                            } else {
 6088                                current_range.end = current_range.end.next_row();
 6089                            }
 6090                        }
 6091                        None => {
 6092                            let edges = Edges {
 6093                                top: px(1.),
 6094                                bottom: px(1.),
 6095                                ..Default::default()
 6096                            };
 6097                            current_paint = Some((new_background, new_row..new_row, edges))
 6098                        }
 6099                    };
 6100                }
 6101                if let Some((color, range, edges)) = current_paint {
 6102                    paint_highlight(range.start, range.end, color, edges);
 6103                }
 6104
 6105                for (guide_x, active) in layout.wrap_guides.iter() {
 6106                    let color = if *active {
 6107                        cx.theme().colors().editor_active_wrap_guide
 6108                    } else {
 6109                        cx.theme().colors().editor_wrap_guide
 6110                    };
 6111                    window.paint_quad(fill(
 6112                        Bounds {
 6113                            origin: point(*guide_x, layout.position_map.text_hitbox.origin.y),
 6114                            size: size(px(1.), layout.position_map.text_hitbox.size.height),
 6115                        },
 6116                        color,
 6117                    ));
 6118                }
 6119            }
 6120        })
 6121    }
 6122
 6123    fn paint_indent_guides(
 6124        &mut self,
 6125        layout: &mut EditorLayout,
 6126        window: &mut Window,
 6127        cx: &mut App,
 6128    ) {
 6129        let Some(indent_guides) = &layout.indent_guides else {
 6130            return;
 6131        };
 6132
 6133        let faded_color = |color: Hsla, alpha: f32| {
 6134            let mut faded = color;
 6135            faded.a = alpha;
 6136            faded
 6137        };
 6138
 6139        for indent_guide in indent_guides {
 6140            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
 6141            let settings = &indent_guide.settings;
 6142
 6143            // TODO fixed for now, expose them through themes later
 6144            const INDENT_AWARE_ALPHA: f32 = 0.2;
 6145            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
 6146            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
 6147            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
 6148
 6149            let line_color = match (settings.coloring, indent_guide.active) {
 6150                (IndentGuideColoring::Disabled, _) => None,
 6151                (IndentGuideColoring::Fixed, false) => {
 6152                    Some(cx.theme().colors().editor_indent_guide)
 6153                }
 6154                (IndentGuideColoring::Fixed, true) => {
 6155                    Some(cx.theme().colors().editor_indent_guide_active)
 6156                }
 6157                (IndentGuideColoring::IndentAware, false) => {
 6158                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
 6159                }
 6160                (IndentGuideColoring::IndentAware, true) => {
 6161                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
 6162                }
 6163            };
 6164
 6165            let background_color = match (settings.background_coloring, indent_guide.active) {
 6166                (IndentGuideBackgroundColoring::Disabled, _) => None,
 6167                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
 6168                    indent_accent_colors,
 6169                    INDENT_AWARE_BACKGROUND_ALPHA,
 6170                )),
 6171                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
 6172                    indent_accent_colors,
 6173                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
 6174                )),
 6175            };
 6176
 6177            let requested_line_width = if indent_guide.active {
 6178                settings.active_line_width
 6179            } else {
 6180                settings.line_width
 6181            }
 6182            .clamp(1, 10);
 6183            let mut line_indicator_width = 0.;
 6184            if let Some(color) = line_color {
 6185                window.paint_quad(fill(
 6186                    Bounds {
 6187                        origin: indent_guide.origin,
 6188                        size: size(px(requested_line_width as f32), indent_guide.length),
 6189                    },
 6190                    color,
 6191                ));
 6192                line_indicator_width = requested_line_width as f32;
 6193            }
 6194
 6195            if let Some(color) = background_color {
 6196                let width = indent_guide.single_indent_width - px(line_indicator_width);
 6197                window.paint_quad(fill(
 6198                    Bounds {
 6199                        origin: point(
 6200                            indent_guide.origin.x + px(line_indicator_width),
 6201                            indent_guide.origin.y,
 6202                        ),
 6203                        size: size(width, indent_guide.length),
 6204                    },
 6205                    color,
 6206                ));
 6207            }
 6208        }
 6209    }
 6210
 6211    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6212        let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
 6213
 6214        let line_height = layout.position_map.line_height;
 6215        window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
 6216
 6217        for line_layout in layout.line_numbers.values() {
 6218            for LineNumberSegment {
 6219                shaped_line,
 6220                hitbox,
 6221            } in &line_layout.segments
 6222            {
 6223                let Some(hitbox) = hitbox else {
 6224                    continue;
 6225                };
 6226
 6227                let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
 6228                    let color = cx.theme().colors().editor_hover_line_number;
 6229
 6230                    let line = self.shape_line_number(shaped_line.text.clone(), color, window);
 6231                    line.paint(
 6232                        hitbox.origin,
 6233                        line_height,
 6234                        TextAlign::Left,
 6235                        None,
 6236                        window,
 6237                        cx,
 6238                    )
 6239                    .log_err()
 6240                } else {
 6241                    shaped_line
 6242                        .paint(
 6243                            hitbox.origin,
 6244                            line_height,
 6245                            TextAlign::Left,
 6246                            None,
 6247                            window,
 6248                            cx,
 6249                        )
 6250                        .log_err()
 6251                }) else {
 6252                    continue;
 6253                };
 6254
 6255                // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
 6256                // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
 6257                if is_singleton {
 6258                    window.set_cursor_style(CursorStyle::IBeam, hitbox);
 6259                } else {
 6260                    window.set_cursor_style(CursorStyle::PointingHand, hitbox);
 6261                }
 6262            }
 6263        }
 6264    }
 6265
 6266    fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6267        if layout.display_hunks.is_empty() {
 6268            return;
 6269        }
 6270
 6271        let line_height = layout.position_map.line_height;
 6272        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6273            for (hunk, hitbox) in &layout.display_hunks {
 6274                let hunk_to_paint = match hunk {
 6275                    DisplayDiffHunk::Folded { .. } => {
 6276                        let hunk_bounds = Self::diff_hunk_bounds(
 6277                            &layout.position_map.snapshot,
 6278                            line_height,
 6279                            layout.gutter_hitbox.bounds,
 6280                            hunk,
 6281                        );
 6282                        Some((
 6283                            hunk_bounds,
 6284                            cx.theme().colors().version_control_modified,
 6285                            Corners::all(px(0.)),
 6286                            DiffHunkStatus::modified_none(),
 6287                        ))
 6288                    }
 6289                    DisplayDiffHunk::Unfolded {
 6290                        status,
 6291                        display_row_range,
 6292                        ..
 6293                    } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
 6294                        DiffHunkStatusKind::Added => (
 6295                            hunk_hitbox.bounds,
 6296                            cx.theme().colors().version_control_added,
 6297                            Corners::all(px(0.)),
 6298                            *status,
 6299                        ),
 6300                        DiffHunkStatusKind::Modified => (
 6301                            hunk_hitbox.bounds,
 6302                            cx.theme().colors().version_control_modified,
 6303                            Corners::all(px(0.)),
 6304                            *status,
 6305                        ),
 6306                        DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
 6307                            hunk_hitbox.bounds,
 6308                            cx.theme().colors().version_control_deleted,
 6309                            Corners::all(px(0.)),
 6310                            *status,
 6311                        ),
 6312                        DiffHunkStatusKind::Deleted => (
 6313                            Bounds::new(
 6314                                point(
 6315                                    hunk_hitbox.origin.x - hunk_hitbox.size.width,
 6316                                    hunk_hitbox.origin.y,
 6317                                ),
 6318                                size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
 6319                            ),
 6320                            cx.theme().colors().version_control_deleted,
 6321                            Corners::all(1. * line_height),
 6322                            *status,
 6323                        ),
 6324                    }),
 6325                };
 6326
 6327                if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
 6328                    // Flatten the background color with the editor color to prevent
 6329                    // elements below transparent hunks from showing through
 6330                    let flattened_background_color = cx
 6331                        .theme()
 6332                        .colors()
 6333                        .editor_background
 6334                        .blend(background_color);
 6335
 6336                    if !Self::diff_hunk_hollow(status, cx) {
 6337                        window.paint_quad(quad(
 6338                            hunk_bounds,
 6339                            corner_radii,
 6340                            flattened_background_color,
 6341                            Edges::default(),
 6342                            transparent_black(),
 6343                            BorderStyle::default(),
 6344                        ));
 6345                    } else {
 6346                        let flattened_unstaged_background_color = cx
 6347                            .theme()
 6348                            .colors()
 6349                            .editor_background
 6350                            .blend(background_color.opacity(0.3));
 6351
 6352                        window.paint_quad(quad(
 6353                            hunk_bounds,
 6354                            corner_radii,
 6355                            flattened_unstaged_background_color,
 6356                            Edges::all(px(1.0)),
 6357                            flattened_background_color,
 6358                            BorderStyle::Solid,
 6359                        ));
 6360                    }
 6361                }
 6362            }
 6363        });
 6364    }
 6365
 6366    fn gutter_strip_width(line_height: Pixels) -> Pixels {
 6367        (0.275 * line_height).floor()
 6368    }
 6369
 6370    fn diff_hunk_bounds(
 6371        snapshot: &EditorSnapshot,
 6372        line_height: Pixels,
 6373        gutter_bounds: Bounds<Pixels>,
 6374        hunk: &DisplayDiffHunk,
 6375    ) -> Bounds<Pixels> {
 6376        let scroll_position = snapshot.scroll_position();
 6377        let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
 6378        let gutter_strip_width = Self::gutter_strip_width(line_height);
 6379
 6380        match hunk {
 6381            DisplayDiffHunk::Folded { display_row, .. } => {
 6382                let start_y = (display_row.as_f64() * ScrollPixelOffset::from(line_height)
 6383                    - scroll_top)
 6384                    .into();
 6385                let end_y = start_y + line_height;
 6386                let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 6387                let highlight_size = size(gutter_strip_width, end_y - start_y);
 6388                Bounds::new(highlight_origin, highlight_size)
 6389            }
 6390            DisplayDiffHunk::Unfolded {
 6391                display_row_range,
 6392                status,
 6393                ..
 6394            } => {
 6395                if status.is_deleted() && display_row_range.is_empty() {
 6396                    let row = display_row_range.start;
 6397
 6398                    let offset = ScrollPixelOffset::from(line_height / 2.);
 6399                    let start_y =
 6400                        (row.as_f64() * ScrollPixelOffset::from(line_height) - offset - scroll_top)
 6401                            .into();
 6402                    let end_y = start_y + line_height;
 6403
 6404                    let width = (0.35 * line_height).floor();
 6405                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 6406                    let highlight_size = size(width, end_y - start_y);
 6407                    Bounds::new(highlight_origin, highlight_size)
 6408                } else {
 6409                    let start_row = display_row_range.start;
 6410                    let end_row = display_row_range.end;
 6411                    // If we're in a multibuffer, row range span might include an
 6412                    // excerpt header, so if we were to draw the marker straight away,
 6413                    // the hunk might include the rows of that header.
 6414                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
 6415                    // Instead, we simply check whether the range we're dealing with includes
 6416                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
 6417                    let end_row_in_current_excerpt = snapshot
 6418                        .blocks_in_range(start_row..end_row)
 6419                        .find_map(|(start_row, block)| {
 6420                            if matches!(
 6421                                block,
 6422                                Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
 6423                            ) {
 6424                                Some(start_row)
 6425                            } else {
 6426                                None
 6427                            }
 6428                        })
 6429                        .unwrap_or(end_row);
 6430
 6431                    let start_y = (start_row.as_f64() * ScrollPixelOffset::from(line_height)
 6432                        - scroll_top)
 6433                        .into();
 6434                    let end_y = Pixels::from(
 6435                        end_row_in_current_excerpt.as_f64() * ScrollPixelOffset::from(line_height)
 6436                            - scroll_top,
 6437                    );
 6438
 6439                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
 6440                    let highlight_size = size(gutter_strip_width, end_y - start_y);
 6441                    Bounds::new(highlight_origin, highlight_size)
 6442                }
 6443            }
 6444        }
 6445    }
 6446
 6447    fn paint_gutter_indicators(
 6448        &self,
 6449        layout: &mut EditorLayout,
 6450        window: &mut Window,
 6451        cx: &mut App,
 6452    ) {
 6453        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6454            window.with_element_namespace("crease_toggles", |window| {
 6455                for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
 6456                    crease_toggle.paint(window, cx);
 6457                }
 6458            });
 6459
 6460            window.with_element_namespace("expand_toggles", |window| {
 6461                for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
 6462                    expand_toggle.paint(window, cx);
 6463                }
 6464            });
 6465
 6466            for breakpoint in layout.breakpoints.iter_mut() {
 6467                breakpoint.paint(window, cx);
 6468            }
 6469
 6470            for test_indicator in layout.test_indicators.iter_mut() {
 6471                test_indicator.paint(window, cx);
 6472            }
 6473        });
 6474    }
 6475
 6476    fn paint_gutter_highlights(
 6477        &self,
 6478        layout: &mut EditorLayout,
 6479        window: &mut Window,
 6480        cx: &mut App,
 6481    ) {
 6482        for (_, hunk_hitbox) in &layout.display_hunks {
 6483            if let Some(hunk_hitbox) = hunk_hitbox
 6484                && !self
 6485                    .editor
 6486                    .read(cx)
 6487                    .buffer()
 6488                    .read(cx)
 6489                    .all_diff_hunks_expanded()
 6490            {
 6491                window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
 6492            }
 6493        }
 6494
 6495        let show_git_gutter = layout
 6496            .position_map
 6497            .snapshot
 6498            .show_git_diff_gutter
 6499            .unwrap_or_else(|| {
 6500                matches!(
 6501                    ProjectSettings::get_global(cx).git.git_gutter,
 6502                    GitGutterSetting::TrackedFiles
 6503                )
 6504            });
 6505        if show_git_gutter {
 6506            Self::paint_gutter_diff_hunks(layout, window, cx)
 6507        }
 6508
 6509        let highlight_width = 0.275 * layout.position_map.line_height;
 6510        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
 6511        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6512            for (range, color) in &layout.highlighted_gutter_ranges {
 6513                let start_row = if range.start.row() < layout.visible_display_row_range.start {
 6514                    layout.visible_display_row_range.start - DisplayRow(1)
 6515                } else {
 6516                    range.start.row()
 6517                };
 6518                let end_row = if range.end.row() > layout.visible_display_row_range.end {
 6519                    layout.visible_display_row_range.end + DisplayRow(1)
 6520                } else {
 6521                    range.end.row()
 6522                };
 6523
 6524                let start_y = layout.gutter_hitbox.top()
 6525                    + Pixels::from(
 6526                        start_row.0 as f64
 6527                            * ScrollPixelOffset::from(layout.position_map.line_height)
 6528                            - layout.position_map.scroll_pixel_position.y,
 6529                    );
 6530                let end_y = layout.gutter_hitbox.top()
 6531                    + Pixels::from(
 6532                        (end_row.0 + 1) as f64
 6533                            * ScrollPixelOffset::from(layout.position_map.line_height)
 6534                            - layout.position_map.scroll_pixel_position.y,
 6535                    );
 6536                let bounds = Bounds::from_corners(
 6537                    point(layout.gutter_hitbox.left(), start_y),
 6538                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
 6539                );
 6540                window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
 6541            }
 6542        });
 6543    }
 6544
 6545    fn paint_blamed_display_rows(
 6546        &self,
 6547        layout: &mut EditorLayout,
 6548        window: &mut Window,
 6549        cx: &mut App,
 6550    ) {
 6551        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
 6552            return;
 6553        };
 6554
 6555        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
 6556            for mut blame_element in blamed_display_rows.into_iter() {
 6557                blame_element.paint(window, cx);
 6558            }
 6559        })
 6560    }
 6561
 6562    fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6563        window.with_content_mask(
 6564            Some(ContentMask {
 6565                bounds: layout.position_map.text_hitbox.bounds,
 6566            }),
 6567            |window| {
 6568                let editor = self.editor.read(cx);
 6569                if editor.mouse_cursor_hidden {
 6570                    window.set_window_cursor_style(CursorStyle::None);
 6571                } else if let SelectionDragState::ReadyToDrag {
 6572                    mouse_down_time, ..
 6573                } = &editor.selection_drag_state
 6574                {
 6575                    let drag_and_drop_delay = Duration::from_millis(
 6576                        EditorSettings::get_global(cx)
 6577                            .drag_and_drop_selection
 6578                            .delay
 6579                            .0,
 6580                    );
 6581                    if mouse_down_time.elapsed() >= drag_and_drop_delay {
 6582                        window.set_cursor_style(
 6583                            CursorStyle::DragCopy,
 6584                            &layout.position_map.text_hitbox,
 6585                        );
 6586                    }
 6587                } else if matches!(
 6588                    editor.selection_drag_state,
 6589                    SelectionDragState::Dragging { .. }
 6590                ) {
 6591                    window
 6592                        .set_cursor_style(CursorStyle::DragCopy, &layout.position_map.text_hitbox);
 6593                } else if editor
 6594                    .hovered_link_state
 6595                    .as_ref()
 6596                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
 6597                {
 6598                    window.set_cursor_style(
 6599                        CursorStyle::PointingHand,
 6600                        &layout.position_map.text_hitbox,
 6601                    );
 6602                } else {
 6603                    window.set_cursor_style(CursorStyle::IBeam, &layout.position_map.text_hitbox);
 6604                };
 6605
 6606                self.paint_lines_background(layout, window, cx);
 6607                let invisible_display_ranges = self.paint_highlights(layout, window, cx);
 6608                self.paint_document_colors(layout, window);
 6609                self.paint_lines(&invisible_display_ranges, layout, window, cx);
 6610                self.paint_redactions(layout, window);
 6611                self.paint_cursors(layout, window, cx);
 6612                self.paint_inline_diagnostics(layout, window, cx);
 6613                self.paint_inline_blame(layout, window, cx);
 6614                self.paint_inline_code_actions(layout, window, cx);
 6615                self.paint_diff_hunk_controls(layout, window, cx);
 6616                window.with_element_namespace("crease_trailers", |window| {
 6617                    for trailer in layout.crease_trailers.iter_mut().flatten() {
 6618                        trailer.element.paint(window, cx);
 6619                    }
 6620                });
 6621            },
 6622        )
 6623    }
 6624
 6625    fn paint_highlights(
 6626        &mut self,
 6627        layout: &mut EditorLayout,
 6628        window: &mut Window,
 6629        cx: &mut App,
 6630    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
 6631        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6632            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
 6633            let line_end_overshoot = 0.15 * layout.position_map.line_height;
 6634            for (range, color) in &layout.highlighted_ranges {
 6635                self.paint_highlighted_range(
 6636                    range.clone(),
 6637                    true,
 6638                    *color,
 6639                    Pixels::ZERO,
 6640                    line_end_overshoot,
 6641                    layout,
 6642                    window,
 6643                );
 6644            }
 6645
 6646            let corner_radius = if EditorSettings::get_global(cx).rounded_selection {
 6647                0.15 * layout.position_map.line_height
 6648            } else {
 6649                Pixels::ZERO
 6650            };
 6651
 6652            for (player_color, selections) in &layout.selections {
 6653                for selection in selections.iter() {
 6654                    self.paint_highlighted_range(
 6655                        selection.range.clone(),
 6656                        true,
 6657                        player_color.selection,
 6658                        corner_radius,
 6659                        corner_radius * 2.,
 6660                        layout,
 6661                        window,
 6662                    );
 6663
 6664                    if selection.is_local && !selection.range.is_empty() {
 6665                        invisible_display_ranges.push(selection.range.clone());
 6666                    }
 6667                }
 6668            }
 6669            invisible_display_ranges
 6670        })
 6671    }
 6672
 6673    fn paint_lines(
 6674        &mut self,
 6675        invisible_display_ranges: &[Range<DisplayPoint>],
 6676        layout: &mut EditorLayout,
 6677        window: &mut Window,
 6678        cx: &mut App,
 6679    ) {
 6680        let whitespace_setting = self
 6681            .editor
 6682            .read(cx)
 6683            .buffer
 6684            .read(cx)
 6685            .language_settings(cx)
 6686            .show_whitespaces;
 6687
 6688        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
 6689            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
 6690            line_with_invisibles.draw(
 6691                layout,
 6692                row,
 6693                layout.content_origin,
 6694                whitespace_setting,
 6695                invisible_display_ranges,
 6696                window,
 6697                cx,
 6698            )
 6699        }
 6700
 6701        for line_element in &mut layout.line_elements {
 6702            line_element.paint(window, cx);
 6703        }
 6704    }
 6705
 6706    fn paint_sticky_headers(
 6707        &mut self,
 6708        layout: &mut EditorLayout,
 6709        window: &mut Window,
 6710        cx: &mut App,
 6711    ) {
 6712        let Some(mut sticky_headers) = layout.sticky_headers.take() else {
 6713            return;
 6714        };
 6715
 6716        if sticky_headers.lines.is_empty() {
 6717            layout.sticky_headers = Some(sticky_headers);
 6718            return;
 6719        }
 6720
 6721        let whitespace_setting = self
 6722            .editor
 6723            .read(cx)
 6724            .buffer
 6725            .read(cx)
 6726            .language_settings(cx)
 6727            .show_whitespaces;
 6728        sticky_headers.paint(layout, whitespace_setting, window, cx);
 6729
 6730        let sticky_header_hitboxes: Vec<Hitbox> = sticky_headers
 6731            .lines
 6732            .iter()
 6733            .map(|line| line.hitbox.clone())
 6734            .collect();
 6735        let hovered_hitbox = sticky_header_hitboxes
 6736            .iter()
 6737            .find_map(|hitbox| hitbox.is_hovered(window).then_some(hitbox.id));
 6738
 6739        window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, _cx| {
 6740            if !phase.bubble() {
 6741                return;
 6742            }
 6743
 6744            let current_hover = sticky_header_hitboxes
 6745                .iter()
 6746                .find_map(|hitbox| hitbox.is_hovered(window).then_some(hitbox.id));
 6747            if hovered_hitbox != current_hover {
 6748                window.refresh();
 6749            }
 6750        });
 6751
 6752        for (line_index, line) in sticky_headers.lines.iter().enumerate() {
 6753            let editor = self.editor.clone();
 6754            let hitbox = line.hitbox.clone();
 6755            let target_anchor = line.target_anchor;
 6756            window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
 6757                if !phase.bubble() {
 6758                    return;
 6759                }
 6760
 6761                if event.button == MouseButton::Left && hitbox.is_hovered(window) {
 6762                    editor.update(cx, |editor, cx| {
 6763                        editor.change_selections(
 6764                            SelectionEffects::scroll(Autoscroll::top_relative(line_index)),
 6765                            window,
 6766                            cx,
 6767                            |selections| selections.select_ranges([target_anchor..target_anchor]),
 6768                        );
 6769                        cx.stop_propagation();
 6770                    });
 6771                }
 6772            });
 6773        }
 6774
 6775        let text_bounds = layout.position_map.text_hitbox.bounds;
 6776        let border_top = text_bounds.top()
 6777            + sticky_headers.lines.last().unwrap().offset
 6778            + layout.position_map.line_height;
 6779        let separator_height = px(1.);
 6780        let border_bounds = Bounds::from_corners(
 6781            point(layout.gutter_hitbox.bounds.left(), border_top),
 6782            point(text_bounds.right(), border_top + separator_height),
 6783        );
 6784        window.paint_quad(fill(border_bounds, cx.theme().colors().border_variant));
 6785
 6786        layout.sticky_headers = Some(sticky_headers);
 6787    }
 6788
 6789    fn paint_lines_background(
 6790        &mut self,
 6791        layout: &mut EditorLayout,
 6792        window: &mut Window,
 6793        cx: &mut App,
 6794    ) {
 6795        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
 6796            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
 6797            line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
 6798        }
 6799    }
 6800
 6801    fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
 6802        if layout.redacted_ranges.is_empty() {
 6803            return;
 6804        }
 6805
 6806        let line_end_overshoot = layout.line_end_overshoot();
 6807
 6808        // A softer than perfect black
 6809        let redaction_color = gpui::rgb(0x0e1111);
 6810
 6811        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 6812            for range in layout.redacted_ranges.iter() {
 6813                self.paint_highlighted_range(
 6814                    range.clone(),
 6815                    true,
 6816                    redaction_color.into(),
 6817                    Pixels::ZERO,
 6818                    line_end_overshoot,
 6819                    layout,
 6820                    window,
 6821                );
 6822            }
 6823        });
 6824    }
 6825
 6826    fn paint_document_colors(&self, layout: &mut EditorLayout, window: &mut Window) {
 6827        let Some((colors_render_mode, image_colors)) = &layout.document_colors else {
 6828            return;
 6829        };
 6830        if image_colors.is_empty()
 6831            || colors_render_mode == &DocumentColorsRenderMode::None
 6832            || colors_render_mode == &DocumentColorsRenderMode::Inlay
 6833        {
 6834            return;
 6835        }
 6836
 6837        let line_end_overshoot = layout.line_end_overshoot();
 6838
 6839        for (range, color) in image_colors {
 6840            match colors_render_mode {
 6841                DocumentColorsRenderMode::Inlay | DocumentColorsRenderMode::None => return,
 6842                DocumentColorsRenderMode::Background => {
 6843                    self.paint_highlighted_range(
 6844                        range.clone(),
 6845                        true,
 6846                        *color,
 6847                        Pixels::ZERO,
 6848                        line_end_overshoot,
 6849                        layout,
 6850                        window,
 6851                    );
 6852                }
 6853                DocumentColorsRenderMode::Border => {
 6854                    self.paint_highlighted_range(
 6855                        range.clone(),
 6856                        false,
 6857                        *color,
 6858                        Pixels::ZERO,
 6859                        line_end_overshoot,
 6860                        layout,
 6861                        window,
 6862                    );
 6863                }
 6864            }
 6865        }
 6866    }
 6867
 6868    fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6869        for cursor in &mut layout.visible_cursors {
 6870            cursor.paint(layout.content_origin, window, cx);
 6871        }
 6872    }
 6873
 6874    fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 6875        let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
 6876            return;
 6877        };
 6878        let any_scrollbar_dragged = self.editor.read(cx).scroll_manager.any_scrollbar_dragged();
 6879
 6880        for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
 6881            let hitbox = &scrollbar_layout.hitbox;
 6882            if scrollbars_layout.visible {
 6883                let scrollbar_edges = match axis {
 6884                    ScrollbarAxis::Horizontal => Edges {
 6885                        top: Pixels::ZERO,
 6886                        right: Pixels::ZERO,
 6887                        bottom: Pixels::ZERO,
 6888                        left: Pixels::ZERO,
 6889                    },
 6890                    ScrollbarAxis::Vertical => Edges {
 6891                        top: Pixels::ZERO,
 6892                        right: Pixels::ZERO,
 6893                        bottom: Pixels::ZERO,
 6894                        left: ScrollbarLayout::BORDER_WIDTH,
 6895                    },
 6896                };
 6897
 6898                window.paint_layer(hitbox.bounds, |window| {
 6899                    window.paint_quad(quad(
 6900                        hitbox.bounds,
 6901                        Corners::default(),
 6902                        cx.theme().colors().scrollbar_track_background,
 6903                        scrollbar_edges,
 6904                        cx.theme().colors().scrollbar_track_border,
 6905                        BorderStyle::Solid,
 6906                    ));
 6907
 6908                    if axis == ScrollbarAxis::Vertical {
 6909                        let fast_markers =
 6910                            self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
 6911                        // Refresh slow scrollbar markers in the background. Below, we
 6912                        // paint whatever markers have already been computed.
 6913                        self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, window, cx);
 6914
 6915                        let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
 6916                        for marker in markers.iter().chain(&fast_markers) {
 6917                            let mut marker = marker.clone();
 6918                            marker.bounds.origin += hitbox.origin;
 6919                            window.paint_quad(marker);
 6920                        }
 6921                    }
 6922
 6923                    if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
 6924                        let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
 6925                            ScrollbarThumbState::Dragging => {
 6926                                cx.theme().colors().scrollbar_thumb_active_background
 6927                            }
 6928                            ScrollbarThumbState::Hovered => {
 6929                                cx.theme().colors().scrollbar_thumb_hover_background
 6930                            }
 6931                            ScrollbarThumbState::Idle => {
 6932                                cx.theme().colors().scrollbar_thumb_background
 6933                            }
 6934                        };
 6935                        window.paint_quad(quad(
 6936                            thumb_bounds,
 6937                            Corners::default(),
 6938                            scrollbar_thumb_color,
 6939                            scrollbar_edges,
 6940                            cx.theme().colors().scrollbar_thumb_border,
 6941                            BorderStyle::Solid,
 6942                        ));
 6943
 6944                        if any_scrollbar_dragged {
 6945                            window.set_window_cursor_style(CursorStyle::Arrow);
 6946                        } else {
 6947                            window.set_cursor_style(CursorStyle::Arrow, hitbox);
 6948                        }
 6949                    }
 6950                })
 6951            }
 6952        }
 6953
 6954        window.on_mouse_event({
 6955            let editor = self.editor.clone();
 6956            let scrollbars_layout = scrollbars_layout.clone();
 6957
 6958            let mut mouse_position = window.mouse_position();
 6959            move |event: &MouseMoveEvent, phase, window, cx| {
 6960                if phase == DispatchPhase::Capture {
 6961                    return;
 6962                }
 6963
 6964                editor.update(cx, |editor, cx| {
 6965                    if let Some((scrollbar_layout, axis)) = event
 6966                        .pressed_button
 6967                        .filter(|button| *button == MouseButton::Left)
 6968                        .and(editor.scroll_manager.dragging_scrollbar_axis())
 6969                        .and_then(|axis| {
 6970                            scrollbars_layout
 6971                                .iter_scrollbars()
 6972                                .find(|(_, a)| *a == axis)
 6973                        })
 6974                    {
 6975                        let ScrollbarLayout {
 6976                            hitbox,
 6977                            text_unit_size,
 6978                            ..
 6979                        } = scrollbar_layout;
 6980
 6981                        let old_position = mouse_position.along(axis);
 6982                        let new_position = event.position.along(axis);
 6983                        if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
 6984                            .contains(&old_position)
 6985                        {
 6986                            let position = editor.scroll_position(cx).apply_along(axis, |p| {
 6987                                (p + ScrollOffset::from(
 6988                                    (new_position - old_position) / *text_unit_size,
 6989                                ))
 6990                                .max(0.)
 6991                            });
 6992                            editor.set_scroll_position(position, window, cx);
 6993                        }
 6994
 6995                        editor.scroll_manager.show_scrollbars(window, cx);
 6996                        cx.stop_propagation();
 6997                    } else if let Some((layout, axis)) = scrollbars_layout
 6998                        .get_hovered_axis(window)
 6999                        .filter(|_| !event.dragging())
 7000                    {
 7001                        if layout.thumb_hovered(&event.position) {
 7002                            editor
 7003                                .scroll_manager
 7004                                .set_hovered_scroll_thumb_axis(axis, cx);
 7005                        } else {
 7006                            editor.scroll_manager.reset_scrollbar_state(cx);
 7007                        }
 7008
 7009                        editor.scroll_manager.show_scrollbars(window, cx);
 7010                    } else {
 7011                        editor.scroll_manager.reset_scrollbar_state(cx);
 7012                    }
 7013
 7014                    mouse_position = event.position;
 7015                })
 7016            }
 7017        });
 7018
 7019        if any_scrollbar_dragged {
 7020            window.on_mouse_event({
 7021                let editor = self.editor.clone();
 7022                move |_: &MouseUpEvent, phase, window, cx| {
 7023                    if phase == DispatchPhase::Capture {
 7024                        return;
 7025                    }
 7026
 7027                    editor.update(cx, |editor, cx| {
 7028                        if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
 7029                            editor
 7030                                .scroll_manager
 7031                                .set_hovered_scroll_thumb_axis(axis, cx);
 7032                        } else {
 7033                            editor.scroll_manager.reset_scrollbar_state(cx);
 7034                        }
 7035                        cx.stop_propagation();
 7036                    });
 7037                }
 7038            });
 7039        } else {
 7040            window.on_mouse_event({
 7041                let editor = self.editor.clone();
 7042
 7043                move |event: &MouseDownEvent, phase, window, cx| {
 7044                    if phase == DispatchPhase::Capture {
 7045                        return;
 7046                    }
 7047                    let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
 7048                    else {
 7049                        return;
 7050                    };
 7051
 7052                    let ScrollbarLayout {
 7053                        hitbox,
 7054                        visible_range,
 7055                        text_unit_size,
 7056                        thumb_bounds,
 7057                        ..
 7058                    } = scrollbar_layout;
 7059
 7060                    let Some(thumb_bounds) = thumb_bounds else {
 7061                        return;
 7062                    };
 7063
 7064                    editor.update(cx, |editor, cx| {
 7065                        editor
 7066                            .scroll_manager
 7067                            .set_dragged_scroll_thumb_axis(axis, cx);
 7068
 7069                        let event_position = event.position.along(axis);
 7070
 7071                        if event_position < thumb_bounds.origin.along(axis)
 7072                            || thumb_bounds.bottom_right().along(axis) < event_position
 7073                        {
 7074                            let center_position = ((event_position - hitbox.origin.along(axis))
 7075                                / *text_unit_size)
 7076                                .round() as u32;
 7077                            let start_position = center_position.saturating_sub(
 7078                                (visible_range.end - visible_range.start) as u32 / 2,
 7079                            );
 7080
 7081                            let position = editor
 7082                                .scroll_position(cx)
 7083                                .apply_along(axis, |_| start_position as ScrollOffset);
 7084
 7085                            editor.set_scroll_position(position, window, cx);
 7086                        } else {
 7087                            editor.scroll_manager.show_scrollbars(window, cx);
 7088                        }
 7089
 7090                        cx.stop_propagation();
 7091                    });
 7092                }
 7093            });
 7094        }
 7095    }
 7096
 7097    fn collect_fast_scrollbar_markers(
 7098        &self,
 7099        layout: &EditorLayout,
 7100        scrollbar_layout: &ScrollbarLayout,
 7101        cx: &mut App,
 7102    ) -> Vec<PaintQuad> {
 7103        const LIMIT: usize = 100;
 7104        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
 7105            return vec![];
 7106        }
 7107        let cursor_ranges = layout
 7108            .cursors
 7109            .iter()
 7110            .map(|(point, color)| ColoredRange {
 7111                start: point.row(),
 7112                end: point.row(),
 7113                color: *color,
 7114            })
 7115            .collect_vec();
 7116        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
 7117    }
 7118
 7119    fn refresh_slow_scrollbar_markers(
 7120        &self,
 7121        layout: &EditorLayout,
 7122        scrollbar_layout: &ScrollbarLayout,
 7123        window: &mut Window,
 7124        cx: &mut App,
 7125    ) {
 7126        self.editor.update(cx, |editor, cx| {
 7127            if editor.buffer_kind(cx) != ItemBufferKind::Singleton
 7128                || !editor
 7129                    .scrollbar_marker_state
 7130                    .should_refresh(scrollbar_layout.hitbox.size)
 7131            {
 7132                return;
 7133            }
 7134
 7135            let scrollbar_layout = scrollbar_layout.clone();
 7136            let background_highlights = editor.background_highlights.clone();
 7137            let snapshot = layout.position_map.snapshot.clone();
 7138            let theme = cx.theme().clone();
 7139            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
 7140
 7141            editor.scrollbar_marker_state.dirty = false;
 7142            editor.scrollbar_marker_state.pending_refresh =
 7143                Some(cx.spawn_in(window, async move |editor, cx| {
 7144                    let scrollbar_size = scrollbar_layout.hitbox.size;
 7145                    let scrollbar_markers = cx
 7146                        .background_spawn(async move {
 7147                            let max_point = snapshot.display_snapshot.buffer_snapshot().max_point();
 7148                            let mut marker_quads = Vec::new();
 7149                            if scrollbar_settings.git_diff {
 7150                                let marker_row_ranges =
 7151                                    snapshot.buffer_snapshot().diff_hunks().map(|hunk| {
 7152                                        let start_display_row =
 7153                                            MultiBufferPoint::new(hunk.row_range.start.0, 0)
 7154                                                .to_display_point(&snapshot.display_snapshot)
 7155                                                .row();
 7156                                        let mut end_display_row =
 7157                                            MultiBufferPoint::new(hunk.row_range.end.0, 0)
 7158                                                .to_display_point(&snapshot.display_snapshot)
 7159                                                .row();
 7160                                        if end_display_row != start_display_row {
 7161                                            end_display_row.0 -= 1;
 7162                                        }
 7163                                        let color = match &hunk.status().kind {
 7164                                            DiffHunkStatusKind::Added => {
 7165                                                theme.colors().version_control_added
 7166                                            }
 7167                                            DiffHunkStatusKind::Modified => {
 7168                                                theme.colors().version_control_modified
 7169                                            }
 7170                                            DiffHunkStatusKind::Deleted => {
 7171                                                theme.colors().version_control_deleted
 7172                                            }
 7173                                        };
 7174                                        ColoredRange {
 7175                                            start: start_display_row,
 7176                                            end: end_display_row,
 7177                                            color,
 7178                                        }
 7179                                    });
 7180
 7181                                marker_quads.extend(
 7182                                    scrollbar_layout
 7183                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
 7184                                );
 7185                            }
 7186
 7187                            for (background_highlight_id, (_, background_ranges)) in
 7188                                background_highlights.iter()
 7189                            {
 7190                                let is_search_highlights = *background_highlight_id
 7191                                    == HighlightKey::Type(TypeId::of::<BufferSearchHighlights>());
 7192                                let is_text_highlights = *background_highlight_id
 7193                                    == HighlightKey::Type(TypeId::of::<SelectedTextHighlight>());
 7194                                let is_symbol_occurrences = *background_highlight_id
 7195                                    == HighlightKey::Type(TypeId::of::<DocumentHighlightRead>())
 7196                                    || *background_highlight_id
 7197                                        == HighlightKey::Type(
 7198                                            TypeId::of::<DocumentHighlightWrite>(),
 7199                                        );
 7200                                if (is_search_highlights && scrollbar_settings.search_results)
 7201                                    || (is_text_highlights && scrollbar_settings.selected_text)
 7202                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
 7203                                {
 7204                                    let mut color = theme.status().info;
 7205                                    if is_symbol_occurrences {
 7206                                        color.fade_out(0.5);
 7207                                    }
 7208                                    let marker_row_ranges = background_ranges.iter().map(|range| {
 7209                                        let display_start = range
 7210                                            .start
 7211                                            .to_display_point(&snapshot.display_snapshot);
 7212                                        let display_end =
 7213                                            range.end.to_display_point(&snapshot.display_snapshot);
 7214                                        ColoredRange {
 7215                                            start: display_start.row(),
 7216                                            end: display_end.row(),
 7217                                            color,
 7218                                        }
 7219                                    });
 7220                                    marker_quads.extend(
 7221                                        scrollbar_layout
 7222                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
 7223                                    );
 7224                                }
 7225                            }
 7226
 7227                            if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
 7228                                let diagnostics = snapshot
 7229                                    .buffer_snapshot()
 7230                                    .diagnostics_in_range::<Point>(Point::zero()..max_point)
 7231                                    // Don't show diagnostics the user doesn't care about
 7232                                    .filter(|diagnostic| {
 7233                                        match (
 7234                                            scrollbar_settings.diagnostics,
 7235                                            diagnostic.diagnostic.severity,
 7236                                        ) {
 7237                                            (ScrollbarDiagnostics::All, _) => true,
 7238                                            (
 7239                                                ScrollbarDiagnostics::Error,
 7240                                                lsp::DiagnosticSeverity::ERROR,
 7241                                            ) => true,
 7242                                            (
 7243                                                ScrollbarDiagnostics::Warning,
 7244                                                lsp::DiagnosticSeverity::ERROR
 7245                                                | lsp::DiagnosticSeverity::WARNING,
 7246                                            ) => true,
 7247                                            (
 7248                                                ScrollbarDiagnostics::Information,
 7249                                                lsp::DiagnosticSeverity::ERROR
 7250                                                | lsp::DiagnosticSeverity::WARNING
 7251                                                | lsp::DiagnosticSeverity::INFORMATION,
 7252                                            ) => true,
 7253                                            (_, _) => false,
 7254                                        }
 7255                                    })
 7256                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
 7257                                    .sorted_by_key(|diagnostic| {
 7258                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
 7259                                    });
 7260
 7261                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
 7262                                    let start_display = diagnostic
 7263                                        .range
 7264                                        .start
 7265                                        .to_display_point(&snapshot.display_snapshot);
 7266                                    let end_display = diagnostic
 7267                                        .range
 7268                                        .end
 7269                                        .to_display_point(&snapshot.display_snapshot);
 7270                                    let color = match diagnostic.diagnostic.severity {
 7271                                        lsp::DiagnosticSeverity::ERROR => theme.status().error,
 7272                                        lsp::DiagnosticSeverity::WARNING => theme.status().warning,
 7273                                        lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
 7274                                        _ => theme.status().hint,
 7275                                    };
 7276                                    ColoredRange {
 7277                                        start: start_display.row(),
 7278                                        end: end_display.row(),
 7279                                        color,
 7280                                    }
 7281                                });
 7282                                marker_quads.extend(
 7283                                    scrollbar_layout
 7284                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
 7285                                );
 7286                            }
 7287
 7288                            Arc::from(marker_quads)
 7289                        })
 7290                        .await;
 7291
 7292                    editor.update(cx, |editor, cx| {
 7293                        editor.scrollbar_marker_state.markers = scrollbar_markers;
 7294                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
 7295                        editor.scrollbar_marker_state.pending_refresh = None;
 7296                        cx.notify();
 7297                    })?;
 7298
 7299                    Ok(())
 7300                }));
 7301        });
 7302    }
 7303
 7304    fn paint_highlighted_range(
 7305        &self,
 7306        range: Range<DisplayPoint>,
 7307        fill: bool,
 7308        color: Hsla,
 7309        corner_radius: Pixels,
 7310        line_end_overshoot: Pixels,
 7311        layout: &EditorLayout,
 7312        window: &mut Window,
 7313    ) {
 7314        let start_row = layout.visible_display_row_range.start;
 7315        let end_row = layout.visible_display_row_range.end;
 7316        if range.start != range.end {
 7317            let row_range = if range.end.column() == 0 {
 7318                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
 7319            } else {
 7320                cmp::max(range.start.row(), start_row)
 7321                    ..cmp::min(range.end.row().next_row(), end_row)
 7322            };
 7323
 7324            let highlighted_range = HighlightedRange {
 7325                color,
 7326                line_height: layout.position_map.line_height,
 7327                corner_radius,
 7328                start_y: layout.content_origin.y
 7329                    + Pixels::from(
 7330                        (row_range.start.as_f64() - layout.position_map.scroll_position.y)
 7331                            * ScrollOffset::from(layout.position_map.line_height),
 7332                    ),
 7333                lines: row_range
 7334                    .iter_rows()
 7335                    .map(|row| {
 7336                        let line_layout =
 7337                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
 7338                        let alignment_offset =
 7339                            line_layout.alignment_offset(layout.text_align, layout.content_width);
 7340                        HighlightedRangeLine {
 7341                            start_x: if row == range.start.row() {
 7342                                layout.content_origin.x
 7343                                    + Pixels::from(
 7344                                        ScrollPixelOffset::from(
 7345                                            line_layout.x_for_index(range.start.column() as usize)
 7346                                                + alignment_offset,
 7347                                        ) - layout.position_map.scroll_pixel_position.x,
 7348                                    )
 7349                            } else {
 7350                                layout.content_origin.x + alignment_offset
 7351                                    - Pixels::from(layout.position_map.scroll_pixel_position.x)
 7352                            },
 7353                            end_x: if row == range.end.row() {
 7354                                layout.content_origin.x
 7355                                    + Pixels::from(
 7356                                        ScrollPixelOffset::from(
 7357                                            line_layout.x_for_index(range.end.column() as usize)
 7358                                                + alignment_offset,
 7359                                        ) - layout.position_map.scroll_pixel_position.x,
 7360                                    )
 7361                            } else {
 7362                                Pixels::from(
 7363                                    ScrollPixelOffset::from(
 7364                                        layout.content_origin.x
 7365                                            + line_layout.width
 7366                                            + alignment_offset
 7367                                            + line_end_overshoot,
 7368                                    ) - layout.position_map.scroll_pixel_position.x,
 7369                                )
 7370                            },
 7371                        }
 7372                    })
 7373                    .collect(),
 7374            };
 7375
 7376            highlighted_range.paint(fill, layout.position_map.text_hitbox.bounds, window);
 7377        }
 7378    }
 7379
 7380    fn paint_inline_diagnostics(
 7381        &mut self,
 7382        layout: &mut EditorLayout,
 7383        window: &mut Window,
 7384        cx: &mut App,
 7385    ) {
 7386        for mut inline_diagnostic in layout.inline_diagnostics.drain() {
 7387            inline_diagnostic.1.paint(window, cx);
 7388        }
 7389    }
 7390
 7391    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 7392        if let Some(mut blame_layout) = layout.inline_blame_layout.take() {
 7393            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 7394                blame_layout.element.paint(window, cx);
 7395            })
 7396        }
 7397    }
 7398
 7399    fn paint_inline_code_actions(
 7400        &mut self,
 7401        layout: &mut EditorLayout,
 7402        window: &mut Window,
 7403        cx: &mut App,
 7404    ) {
 7405        if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
 7406            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
 7407                inline_code_actions.paint(window, cx);
 7408            })
 7409        }
 7410    }
 7411
 7412    fn paint_diff_hunk_controls(
 7413        &mut self,
 7414        layout: &mut EditorLayout,
 7415        window: &mut Window,
 7416        cx: &mut App,
 7417    ) {
 7418        for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
 7419            diff_hunk_control.paint(window, cx);
 7420        }
 7421    }
 7422
 7423    fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 7424        if let Some(mut layout) = layout.minimap.take() {
 7425            let minimap_hitbox = layout.thumb_layout.hitbox.clone();
 7426            let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
 7427
 7428            window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
 7429                window.with_element_namespace("minimap", |window| {
 7430                    layout.minimap.paint(window, cx);
 7431                    if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
 7432                        let minimap_thumb_color = match layout.thumb_layout.thumb_state {
 7433                            ScrollbarThumbState::Idle => {
 7434                                cx.theme().colors().minimap_thumb_background
 7435                            }
 7436                            ScrollbarThumbState::Hovered => {
 7437                                cx.theme().colors().minimap_thumb_hover_background
 7438                            }
 7439                            ScrollbarThumbState::Dragging => {
 7440                                cx.theme().colors().minimap_thumb_active_background
 7441                            }
 7442                        };
 7443                        let minimap_thumb_border = match layout.thumb_border_style {
 7444                            MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
 7445                            MinimapThumbBorder::LeftOnly => Edges {
 7446                                left: ScrollbarLayout::BORDER_WIDTH,
 7447                                ..Default::default()
 7448                            },
 7449                            MinimapThumbBorder::LeftOpen => Edges {
 7450                                right: ScrollbarLayout::BORDER_WIDTH,
 7451                                top: ScrollbarLayout::BORDER_WIDTH,
 7452                                bottom: ScrollbarLayout::BORDER_WIDTH,
 7453                                ..Default::default()
 7454                            },
 7455                            MinimapThumbBorder::RightOpen => Edges {
 7456                                left: ScrollbarLayout::BORDER_WIDTH,
 7457                                top: ScrollbarLayout::BORDER_WIDTH,
 7458                                bottom: ScrollbarLayout::BORDER_WIDTH,
 7459                                ..Default::default()
 7460                            },
 7461                            MinimapThumbBorder::None => Default::default(),
 7462                        };
 7463
 7464                        window.paint_layer(minimap_hitbox.bounds, |window| {
 7465                            window.paint_quad(quad(
 7466                                thumb_bounds,
 7467                                Corners::default(),
 7468                                minimap_thumb_color,
 7469                                minimap_thumb_border,
 7470                                cx.theme().colors().minimap_thumb_border,
 7471                                BorderStyle::Solid,
 7472                            ));
 7473                        });
 7474                    }
 7475                });
 7476            });
 7477
 7478            if dragging_minimap {
 7479                window.set_window_cursor_style(CursorStyle::Arrow);
 7480            } else {
 7481                window.set_cursor_style(CursorStyle::Arrow, &minimap_hitbox);
 7482            }
 7483
 7484            let minimap_axis = ScrollbarAxis::Vertical;
 7485            let pixels_per_line = Pixels::from(
 7486                ScrollPixelOffset::from(minimap_hitbox.size.height) / layout.max_scroll_top,
 7487            )
 7488            .min(layout.minimap_line_height);
 7489
 7490            let mut mouse_position = window.mouse_position();
 7491
 7492            window.on_mouse_event({
 7493                let editor = self.editor.clone();
 7494
 7495                let minimap_hitbox = minimap_hitbox.clone();
 7496
 7497                move |event: &MouseMoveEvent, phase, window, cx| {
 7498                    if phase == DispatchPhase::Capture {
 7499                        return;
 7500                    }
 7501
 7502                    editor.update(cx, |editor, cx| {
 7503                        if event.pressed_button == Some(MouseButton::Left)
 7504                            && editor.scroll_manager.is_dragging_minimap()
 7505                        {
 7506                            let old_position = mouse_position.along(minimap_axis);
 7507                            let new_position = event.position.along(minimap_axis);
 7508                            if (minimap_hitbox.origin.along(minimap_axis)
 7509                                ..minimap_hitbox.bottom_right().along(minimap_axis))
 7510                                .contains(&old_position)
 7511                            {
 7512                                let position =
 7513                                    editor.scroll_position(cx).apply_along(minimap_axis, |p| {
 7514                                        (p + ScrollPixelOffset::from(
 7515                                            (new_position - old_position) / pixels_per_line,
 7516                                        ))
 7517                                        .max(0.)
 7518                                    });
 7519
 7520                                editor.set_scroll_position(position, window, cx);
 7521                            }
 7522                            cx.stop_propagation();
 7523                        } else if minimap_hitbox.is_hovered(window) {
 7524                            editor.scroll_manager.set_is_hovering_minimap_thumb(
 7525                                !event.dragging()
 7526                                    && layout
 7527                                        .thumb_layout
 7528                                        .thumb_bounds
 7529                                        .is_some_and(|bounds| bounds.contains(&event.position)),
 7530                                cx,
 7531                            );
 7532
 7533                            // Stop hover events from propagating to the
 7534                            // underlying editor if the minimap hitbox is hovered
 7535                            if !event.dragging() {
 7536                                cx.stop_propagation();
 7537                            }
 7538                        } else {
 7539                            editor.scroll_manager.hide_minimap_thumb(cx);
 7540                        }
 7541                        mouse_position = event.position;
 7542                    });
 7543                }
 7544            });
 7545
 7546            if dragging_minimap {
 7547                window.on_mouse_event({
 7548                    let editor = self.editor.clone();
 7549                    move |event: &MouseUpEvent, phase, window, cx| {
 7550                        if phase == DispatchPhase::Capture {
 7551                            return;
 7552                        }
 7553
 7554                        editor.update(cx, |editor, cx| {
 7555                            if minimap_hitbox.is_hovered(window) {
 7556                                editor.scroll_manager.set_is_hovering_minimap_thumb(
 7557                                    layout
 7558                                        .thumb_layout
 7559                                        .thumb_bounds
 7560                                        .is_some_and(|bounds| bounds.contains(&event.position)),
 7561                                    cx,
 7562                                );
 7563                            } else {
 7564                                editor.scroll_manager.hide_minimap_thumb(cx);
 7565                            }
 7566                            cx.stop_propagation();
 7567                        });
 7568                    }
 7569                });
 7570            } else {
 7571                window.on_mouse_event({
 7572                    let editor = self.editor.clone();
 7573
 7574                    move |event: &MouseDownEvent, phase, window, cx| {
 7575                        if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
 7576                            return;
 7577                        }
 7578
 7579                        let event_position = event.position;
 7580
 7581                        let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
 7582                            return;
 7583                        };
 7584
 7585                        editor.update(cx, |editor, cx| {
 7586                            if !thumb_bounds.contains(&event_position) {
 7587                                let click_position =
 7588                                    event_position.relative_to(&minimap_hitbox.origin).y;
 7589
 7590                                let top_position = (click_position
 7591                                    - thumb_bounds.size.along(minimap_axis) / 2.0)
 7592                                    .max(Pixels::ZERO);
 7593
 7594                                let scroll_offset = (layout.minimap_scroll_top
 7595                                    + ScrollPixelOffset::from(
 7596                                        top_position / layout.minimap_line_height,
 7597                                    ))
 7598                                .min(layout.max_scroll_top);
 7599
 7600                                let scroll_position = editor
 7601                                    .scroll_position(cx)
 7602                                    .apply_along(minimap_axis, |_| scroll_offset);
 7603                                editor.set_scroll_position(scroll_position, window, cx);
 7604                            }
 7605
 7606                            editor.scroll_manager.set_is_dragging_minimap(cx);
 7607                            cx.stop_propagation();
 7608                        });
 7609                    }
 7610                });
 7611            }
 7612        }
 7613    }
 7614
 7615    fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
 7616        for mut block in layout.blocks.drain(..) {
 7617            if block.overlaps_gutter {
 7618                block.element.paint(window, cx);
 7619            } else {
 7620                let mut bounds = layout.hitbox.bounds;
 7621                bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
 7622                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 7623                    block.element.paint(window, cx);
 7624                })
 7625            }
 7626        }
 7627    }
 7628
 7629    fn paint_edit_prediction_popover(
 7630        &mut self,
 7631        layout: &mut EditorLayout,
 7632        window: &mut Window,
 7633        cx: &mut App,
 7634    ) {
 7635        if let Some(edit_prediction_popover) = layout.edit_prediction_popover.as_mut() {
 7636            edit_prediction_popover.paint(window, cx);
 7637        }
 7638    }
 7639
 7640    fn paint_mouse_context_menu(
 7641        &mut self,
 7642        layout: &mut EditorLayout,
 7643        window: &mut Window,
 7644        cx: &mut App,
 7645    ) {
 7646        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
 7647            mouse_context_menu.paint(window, cx);
 7648        }
 7649    }
 7650
 7651    fn paint_scroll_wheel_listener(
 7652        &mut self,
 7653        layout: &EditorLayout,
 7654        window: &mut Window,
 7655        cx: &mut App,
 7656    ) {
 7657        window.on_mouse_event({
 7658            let position_map = layout.position_map.clone();
 7659            let editor = self.editor.clone();
 7660            let hitbox = layout.hitbox.clone();
 7661            let mut delta = ScrollDelta::default();
 7662
 7663            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
 7664            // accidentally turn off their scrolling.
 7665            let base_scroll_sensitivity =
 7666                EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
 7667
 7668            // Use a minimum fast_scroll_sensitivity for same reason above
 7669            let fast_scroll_sensitivity = EditorSettings::get_global(cx)
 7670                .fast_scroll_sensitivity
 7671                .max(0.01);
 7672
 7673            move |event: &ScrollWheelEvent, phase, window, cx| {
 7674                let scroll_sensitivity = {
 7675                    if event.modifiers.alt {
 7676                        fast_scroll_sensitivity
 7677                    } else {
 7678                        base_scroll_sensitivity
 7679                    }
 7680                };
 7681
 7682                if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
 7683                    delta = delta.coalesce(event.delta);
 7684                    editor.update(cx, |editor, cx| {
 7685                        let position_map: &PositionMap = &position_map;
 7686
 7687                        let line_height = position_map.line_height;
 7688                        let max_glyph_advance = position_map.em_advance;
 7689                        let (delta, axis) = match delta {
 7690                            gpui::ScrollDelta::Pixels(mut pixels) => {
 7691                                //Trackpad
 7692                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
 7693                                (pixels, axis)
 7694                            }
 7695
 7696                            gpui::ScrollDelta::Lines(lines) => {
 7697                                //Not trackpad
 7698                                let pixels =
 7699                                    point(lines.x * max_glyph_advance, lines.y * line_height);
 7700                                (pixels, None)
 7701                            }
 7702                        };
 7703
 7704                        let current_scroll_position = position_map.snapshot.scroll_position();
 7705                        let x = (current_scroll_position.x
 7706                            * ScrollPixelOffset::from(max_glyph_advance)
 7707                            - ScrollPixelOffset::from(delta.x * scroll_sensitivity))
 7708                            / ScrollPixelOffset::from(max_glyph_advance);
 7709                        let y = (current_scroll_position.y * ScrollPixelOffset::from(line_height)
 7710                            - ScrollPixelOffset::from(delta.y * scroll_sensitivity))
 7711                            / ScrollPixelOffset::from(line_height);
 7712                        let mut scroll_position =
 7713                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
 7714                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
 7715                        if forbid_vertical_scroll {
 7716                            scroll_position.y = current_scroll_position.y;
 7717                        }
 7718
 7719                        if scroll_position != current_scroll_position {
 7720                            editor.scroll(scroll_position, axis, window, cx);
 7721                            cx.stop_propagation();
 7722                        } else if y < 0. {
 7723                            // Due to clamping, we may fail to detect cases of overscroll to the top;
 7724                            // We want the scroll manager to get an update in such cases and detect the change of direction
 7725                            // on the next frame.
 7726                            cx.notify();
 7727                        }
 7728                    });
 7729                }
 7730            }
 7731        });
 7732    }
 7733
 7734    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
 7735        if layout.mode.is_minimap() {
 7736            return;
 7737        }
 7738
 7739        self.paint_scroll_wheel_listener(layout, window, cx);
 7740
 7741        window.on_mouse_event({
 7742            let position_map = layout.position_map.clone();
 7743            let editor = self.editor.clone();
 7744            let line_numbers = layout.line_numbers.clone();
 7745
 7746            move |event: &MouseDownEvent, phase, window, cx| {
 7747                if phase == DispatchPhase::Bubble {
 7748                    match event.button {
 7749                        MouseButton::Left => editor.update(cx, |editor, cx| {
 7750                            let pending_mouse_down = editor
 7751                                .pending_mouse_down
 7752                                .get_or_insert_with(Default::default)
 7753                                .clone();
 7754
 7755                            *pending_mouse_down.borrow_mut() = Some(event.clone());
 7756
 7757                            Self::mouse_left_down(
 7758                                editor,
 7759                                event,
 7760                                &position_map,
 7761                                line_numbers.as_ref(),
 7762                                window,
 7763                                cx,
 7764                            );
 7765                        }),
 7766                        MouseButton::Right => editor.update(cx, |editor, cx| {
 7767                            Self::mouse_right_down(editor, event, &position_map, window, cx);
 7768                        }),
 7769                        MouseButton::Middle => editor.update(cx, |editor, cx| {
 7770                            Self::mouse_middle_down(editor, event, &position_map, window, cx);
 7771                        }),
 7772                        _ => {}
 7773                    };
 7774                }
 7775            }
 7776        });
 7777
 7778        window.on_mouse_event({
 7779            let editor = self.editor.clone();
 7780            let position_map = layout.position_map.clone();
 7781
 7782            move |event: &MouseUpEvent, phase, window, cx| {
 7783                if phase == DispatchPhase::Bubble {
 7784                    editor.update(cx, |editor, cx| {
 7785                        Self::mouse_up(editor, event, &position_map, window, cx)
 7786                    });
 7787                }
 7788            }
 7789        });
 7790
 7791        window.on_mouse_event({
 7792            let editor = self.editor.clone();
 7793            let position_map = layout.position_map.clone();
 7794            let mut captured_mouse_down = None;
 7795
 7796            move |event: &MouseUpEvent, phase, window, cx| match phase {
 7797                // Clear the pending mouse down during the capture phase,
 7798                // so that it happens even if another event handler stops
 7799                // propagation.
 7800                DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
 7801                    let pending_mouse_down = editor
 7802                        .pending_mouse_down
 7803                        .get_or_insert_with(Default::default)
 7804                        .clone();
 7805
 7806                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
 7807                    if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
 7808                        captured_mouse_down = pending_mouse_down.take();
 7809                        window.refresh();
 7810                    }
 7811                }),
 7812                // Fire click handlers during the bubble phase.
 7813                DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
 7814                    if let Some(mouse_down) = captured_mouse_down.take() {
 7815                        let event = ClickEvent::Mouse(MouseClickEvent {
 7816                            down: mouse_down,
 7817                            up: event.clone(),
 7818                        });
 7819                        Self::click(editor, &event, &position_map, window, cx);
 7820                    }
 7821                }),
 7822            }
 7823        });
 7824
 7825        window.on_mouse_event({
 7826            let position_map = layout.position_map.clone();
 7827            let editor = self.editor.clone();
 7828
 7829            move |event: &MousePressureEvent, phase, window, cx| {
 7830                if phase == DispatchPhase::Bubble {
 7831                    editor.update(cx, |editor, cx| {
 7832                        Self::pressure_click(editor, &event, &position_map, window, cx);
 7833                    })
 7834                }
 7835            }
 7836        });
 7837
 7838        window.on_mouse_event({
 7839            let position_map = layout.position_map.clone();
 7840            let editor = self.editor.clone();
 7841
 7842            move |event: &MouseMoveEvent, phase, window, cx| {
 7843                if phase == DispatchPhase::Bubble {
 7844                    editor.update(cx, |editor, cx| {
 7845                        if editor.hover_state.focused(window, cx) {
 7846                            return;
 7847                        }
 7848                        if event.pressed_button == Some(MouseButton::Left)
 7849                            || event.pressed_button == Some(MouseButton::Middle)
 7850                        {
 7851                            Self::mouse_dragged(editor, event, &position_map, window, cx)
 7852                        }
 7853
 7854                        Self::mouse_moved(editor, event, &position_map, window, cx)
 7855                    });
 7856                }
 7857            }
 7858        });
 7859    }
 7860
 7861    fn shape_line_number(
 7862        &self,
 7863        text: SharedString,
 7864        color: Hsla,
 7865        window: &mut Window,
 7866    ) -> ShapedLine {
 7867        let run = TextRun {
 7868            len: text.len(),
 7869            font: self.style.text.font(),
 7870            color,
 7871            ..Default::default()
 7872        };
 7873        window.text_system().shape_line(
 7874            text,
 7875            self.style.text.font_size.to_pixels(window.rem_size()),
 7876            &[run],
 7877            None,
 7878        )
 7879    }
 7880
 7881    fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
 7882        let unstaged = status.has_secondary_hunk();
 7883        let unstaged_hollow = matches!(
 7884            ProjectSettings::get_global(cx).git.hunk_style,
 7885            GitHunkStyleSetting::UnstagedHollow
 7886        );
 7887
 7888        unstaged == unstaged_hollow
 7889    }
 7890
 7891    #[cfg(debug_assertions)]
 7892    fn layout_debug_ranges(
 7893        selections: &mut Vec<(PlayerColor, Vec<SelectionLayout>)>,
 7894        anchor_range: Range<Anchor>,
 7895        display_snapshot: &DisplaySnapshot,
 7896        cx: &App,
 7897    ) {
 7898        let theme = cx.theme();
 7899        text::debug::GlobalDebugRanges::with_locked(|debug_ranges| {
 7900            if debug_ranges.ranges.is_empty() {
 7901                return;
 7902            }
 7903            let buffer_snapshot = &display_snapshot.buffer_snapshot();
 7904            for (buffer, buffer_range, excerpt_id) in
 7905                buffer_snapshot.range_to_buffer_ranges(anchor_range)
 7906            {
 7907                let buffer_range =
 7908                    buffer.anchor_after(buffer_range.start)..buffer.anchor_before(buffer_range.end);
 7909                selections.extend(debug_ranges.ranges.iter().flat_map(|debug_range| {
 7910                    let player_color = theme
 7911                        .players()
 7912                        .color_for_participant(debug_range.occurrence_index as u32 + 1);
 7913                    debug_range.ranges.iter().filter_map(move |range| {
 7914                        if range.start.buffer_id != Some(buffer.remote_id()) {
 7915                            return None;
 7916                        }
 7917                        let clipped_start = range.start.max(&buffer_range.start, buffer);
 7918                        let clipped_end = range.end.min(&buffer_range.end, buffer);
 7919                        let range = buffer_snapshot
 7920                            .anchor_range_in_excerpt(excerpt_id, *clipped_start..*clipped_end)?;
 7921                        let start = range.start.to_display_point(display_snapshot);
 7922                        let end = range.end.to_display_point(display_snapshot);
 7923                        let selection_layout = SelectionLayout {
 7924                            head: start,
 7925                            range: start..end,
 7926                            cursor_shape: CursorShape::Bar,
 7927                            is_newest: false,
 7928                            is_local: false,
 7929                            active_rows: start.row()..end.row(),
 7930                            user_name: Some(SharedString::new(debug_range.value.clone())),
 7931                        };
 7932                        Some((player_color, vec![selection_layout]))
 7933                    })
 7934                }));
 7935            }
 7936        });
 7937    }
 7938}
 7939
 7940pub fn render_breadcrumb_text(
 7941    mut segments: Vec<BreadcrumbText>,
 7942    prefix: Option<gpui::AnyElement>,
 7943    active_item: &dyn ItemHandle,
 7944    multibuffer_header: bool,
 7945    window: &mut Window,
 7946    cx: &App,
 7947) -> impl IntoElement {
 7948    const MAX_SEGMENTS: usize = 12;
 7949
 7950    let element = h_flex().flex_grow().text_ui(cx);
 7951
 7952    let prefix_end_ix = cmp::min(segments.len(), MAX_SEGMENTS / 2);
 7953    let suffix_start_ix = cmp::max(
 7954        prefix_end_ix,
 7955        segments.len().saturating_sub(MAX_SEGMENTS / 2),
 7956    );
 7957
 7958    if suffix_start_ix > prefix_end_ix {
 7959        segments.splice(
 7960            prefix_end_ix..suffix_start_ix,
 7961            Some(BreadcrumbText {
 7962                text: "β‹―".into(),
 7963                highlights: None,
 7964                font: None,
 7965            }),
 7966        );
 7967    }
 7968
 7969    let highlighted_segments = segments.into_iter().enumerate().map(|(index, segment)| {
 7970        let mut text_style = window.text_style();
 7971        if let Some(ref font) = segment.font {
 7972            text_style.font_family = font.family.clone();
 7973            text_style.font_features = font.features.clone();
 7974            text_style.font_style = font.style;
 7975            text_style.font_weight = font.weight;
 7976        }
 7977        text_style.color = Color::Muted.color(cx);
 7978
 7979        if index == 0
 7980            && !workspace::TabBarSettings::get_global(cx).show
 7981            && active_item.is_dirty(cx)
 7982            && let Some(styled_element) = apply_dirty_filename_style(&segment, &text_style, cx)
 7983        {
 7984            return styled_element;
 7985        }
 7986
 7987        StyledText::new(segment.text.replace('\n', "⏎"))
 7988            .with_default_highlights(&text_style, segment.highlights.unwrap_or_default())
 7989            .into_any()
 7990    });
 7991
 7992    let breadcrumbs = Itertools::intersperse_with(highlighted_segments, || {
 7993        Label::new("β€Ί").color(Color::Placeholder).into_any_element()
 7994    });
 7995
 7996    let breadcrumbs_stack = h_flex()
 7997        .gap_1()
 7998        .when(multibuffer_header, |this| {
 7999            this.pl_2()
 8000                .border_l_1()
 8001                .border_color(cx.theme().colors().border.opacity(0.6))
 8002        })
 8003        .children(breadcrumbs);
 8004
 8005    let breadcrumbs = if let Some(prefix) = prefix {
 8006        h_flex().gap_1p5().child(prefix).child(breadcrumbs_stack)
 8007    } else {
 8008        breadcrumbs_stack
 8009    };
 8010
 8011    let editor = active_item
 8012        .downcast::<Editor>()
 8013        .map(|editor| editor.downgrade());
 8014
 8015    match editor {
 8016        Some(editor) => element
 8017            .id("breadcrumb_container")
 8018            .when(!multibuffer_header, |this| this.overflow_x_scroll())
 8019            .child(
 8020                ButtonLike::new("toggle outline view")
 8021                    .child(breadcrumbs)
 8022                    .when(multibuffer_header, |this| {
 8023                        this.style(ButtonStyle::Transparent)
 8024                    })
 8025                    .when(!multibuffer_header, |this| {
 8026                        let focus_handle = editor.upgrade().unwrap().focus_handle(&cx);
 8027
 8028                        this.tooltip(move |_window, cx| {
 8029                            Tooltip::for_action_in(
 8030                                "Show Symbol Outline",
 8031                                &zed_actions::outline::ToggleOutline,
 8032                                &focus_handle,
 8033                                cx,
 8034                            )
 8035                        })
 8036                        .on_click({
 8037                            let editor = editor.clone();
 8038                            move |_, window, cx| {
 8039                                if let Some((editor, callback)) = editor
 8040                                    .upgrade()
 8041                                    .zip(zed_actions::outline::TOGGLE_OUTLINE.get())
 8042                                {
 8043                                    callback(editor.to_any_view(), window, cx);
 8044                                }
 8045                            }
 8046                        })
 8047                    }),
 8048            )
 8049            .into_any_element(),
 8050        None => element
 8051            // Match the height and padding of the `ButtonLike` in the other arm.
 8052            .h(rems_from_px(22.))
 8053            .pl_1()
 8054            .child(breadcrumbs)
 8055            .into_any_element(),
 8056    }
 8057}
 8058
 8059fn apply_dirty_filename_style(
 8060    segment: &BreadcrumbText,
 8061    text_style: &gpui::TextStyle,
 8062    cx: &App,
 8063) -> Option<gpui::AnyElement> {
 8064    let text = segment.text.replace('\n', "⏎");
 8065
 8066    let filename_position = std::path::Path::new(&segment.text)
 8067        .file_name()
 8068        .and_then(|f| {
 8069            let filename_str = f.to_string_lossy();
 8070            segment.text.rfind(filename_str.as_ref())
 8071        })?;
 8072
 8073    let bold_weight = FontWeight::BOLD;
 8074    let default_color = Color::Default.color(cx);
 8075
 8076    if filename_position == 0 {
 8077        let mut filename_style = text_style.clone();
 8078        filename_style.font_weight = bold_weight;
 8079        filename_style.color = default_color;
 8080
 8081        return Some(
 8082            StyledText::new(text)
 8083                .with_default_highlights(&filename_style, [])
 8084                .into_any(),
 8085        );
 8086    }
 8087
 8088    let highlight_style = gpui::HighlightStyle {
 8089        font_weight: Some(bold_weight),
 8090        color: Some(default_color),
 8091        ..Default::default()
 8092    };
 8093
 8094    let highlight = vec![(filename_position..text.len(), highlight_style)];
 8095    Some(
 8096        StyledText::new(text)
 8097            .with_default_highlights(text_style, highlight)
 8098            .into_any(),
 8099    )
 8100}
 8101
 8102fn file_status_label_color(file_status: Option<FileStatus>) -> Color {
 8103    file_status.map_or(Color::Default, |status| {
 8104        if status.is_conflicted() {
 8105            Color::Conflict
 8106        } else if status.is_modified() {
 8107            Color::Modified
 8108        } else if status.is_deleted() {
 8109            Color::Disabled
 8110        } else if status.is_created() {
 8111            Color::Created
 8112        } else {
 8113            Color::Default
 8114        }
 8115    })
 8116}
 8117
 8118fn header_jump_data(
 8119    editor_snapshot: &EditorSnapshot,
 8120    block_row_start: DisplayRow,
 8121    height: u32,
 8122    first_excerpt: &ExcerptInfo,
 8123    latest_selection_anchors: &HashMap<BufferId, Anchor>,
 8124) -> JumpData {
 8125    let jump_target = if let Some(anchor) = latest_selection_anchors.get(&first_excerpt.buffer_id)
 8126        && let Some(range) = editor_snapshot.context_range_for_excerpt(anchor.excerpt_id)
 8127        && let Some(buffer) = editor_snapshot
 8128            .buffer_snapshot()
 8129            .buffer_for_excerpt(anchor.excerpt_id)
 8130    {
 8131        JumpTargetInExcerptInput {
 8132            id: anchor.excerpt_id,
 8133            buffer,
 8134            excerpt_start_anchor: range.start,
 8135            jump_anchor: anchor.text_anchor,
 8136        }
 8137    } else {
 8138        JumpTargetInExcerptInput {
 8139            id: first_excerpt.id,
 8140            buffer: &first_excerpt.buffer,
 8141            excerpt_start_anchor: first_excerpt.range.context.start,
 8142            jump_anchor: first_excerpt.range.primary.start,
 8143        }
 8144    };
 8145    header_jump_data_inner(editor_snapshot, block_row_start, height, &jump_target)
 8146}
 8147
 8148struct JumpTargetInExcerptInput<'a> {
 8149    id: ExcerptId,
 8150    buffer: &'a language::BufferSnapshot,
 8151    excerpt_start_anchor: text::Anchor,
 8152    jump_anchor: text::Anchor,
 8153}
 8154
 8155fn header_jump_data_inner(
 8156    snapshot: &EditorSnapshot,
 8157    block_row_start: DisplayRow,
 8158    height: u32,
 8159    for_excerpt: &JumpTargetInExcerptInput,
 8160) -> JumpData {
 8161    let buffer = &for_excerpt.buffer;
 8162    let jump_position = language::ToPoint::to_point(&for_excerpt.jump_anchor, buffer);
 8163    let excerpt_start = for_excerpt.excerpt_start_anchor;
 8164    let rows_from_excerpt_start = if for_excerpt.jump_anchor == excerpt_start {
 8165        0
 8166    } else {
 8167        let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
 8168        jump_position.row.saturating_sub(excerpt_start_point.row)
 8169    };
 8170
 8171    let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
 8172        .saturating_sub(
 8173            snapshot
 8174                .scroll_anchor
 8175                .scroll_position(&snapshot.display_snapshot)
 8176                .y as u32,
 8177        );
 8178
 8179    JumpData::MultiBufferPoint {
 8180        excerpt_id: for_excerpt.id,
 8181        anchor: for_excerpt.jump_anchor,
 8182        position: jump_position,
 8183        line_offset_from_top,
 8184    }
 8185}
 8186
 8187pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
 8188
 8189impl AcceptEditPredictionBinding {
 8190    pub fn keystroke(&self) -> Option<&KeybindingKeystroke> {
 8191        if let Some(binding) = self.0.as_ref() {
 8192            match &binding.keystrokes() {
 8193                [keystroke, ..] => Some(keystroke),
 8194                _ => None,
 8195            }
 8196        } else {
 8197            None
 8198        }
 8199    }
 8200}
 8201
 8202fn prepaint_gutter_button(
 8203    button: IconButton,
 8204    row: DisplayRow,
 8205    line_height: Pixels,
 8206    gutter_dimensions: &GutterDimensions,
 8207    scroll_position: gpui::Point<ScrollOffset>,
 8208    gutter_hitbox: &Hitbox,
 8209    display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
 8210    window: &mut Window,
 8211    cx: &mut App,
 8212) -> AnyElement {
 8213    let mut button = button.into_any_element();
 8214
 8215    let available_space = size(
 8216        AvailableSpace::MinContent,
 8217        AvailableSpace::Definite(line_height),
 8218    );
 8219    let indicator_size = button.layout_as_root(available_space, window, cx);
 8220
 8221    let blame_width = gutter_dimensions.git_blame_entries_width;
 8222    let gutter_width = display_hunks
 8223        .binary_search_by(|(hunk, _)| match hunk {
 8224            DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
 8225            DisplayDiffHunk::Unfolded {
 8226                display_row_range, ..
 8227            } => {
 8228                if display_row_range.end <= row {
 8229                    Ordering::Less
 8230                } else if display_row_range.start > row {
 8231                    Ordering::Greater
 8232                } else {
 8233                    Ordering::Equal
 8234                }
 8235            }
 8236        })
 8237        .ok()
 8238        .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
 8239    let left_offset = blame_width.max(gutter_width).unwrap_or_default();
 8240
 8241    let mut x = left_offset;
 8242    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
 8243        - indicator_size.width
 8244        - left_offset;
 8245    x += available_width / 2.;
 8246
 8247    let mut y =
 8248        Pixels::from((row.as_f64() - scroll_position.y) * ScrollPixelOffset::from(line_height));
 8249    y += (line_height - indicator_size.height) / 2.;
 8250
 8251    button.prepaint_as_root(
 8252        gutter_hitbox.origin + point(x, y),
 8253        available_space,
 8254        window,
 8255        cx,
 8256    );
 8257    button
 8258}
 8259
 8260fn render_inline_blame_entry(
 8261    blame_entry: BlameEntry,
 8262    style: &EditorStyle,
 8263    cx: &mut App,
 8264) -> Option<AnyElement> {
 8265    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 8266    renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
 8267}
 8268
 8269fn render_blame_entry_popover(
 8270    blame_entry: BlameEntry,
 8271    scroll_handle: ScrollHandle,
 8272    commit_message: Option<ParsedCommitMessage>,
 8273    markdown: Entity<Markdown>,
 8274    workspace: WeakEntity<Workspace>,
 8275    blame: &Entity<GitBlame>,
 8276    buffer: BufferId,
 8277    window: &mut Window,
 8278    cx: &mut App,
 8279) -> Option<AnyElement> {
 8280    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
 8281    let blame = blame.read(cx);
 8282    let repository = blame.repository(cx, buffer)?;
 8283    renderer.render_blame_entry_popover(
 8284        blame_entry,
 8285        scroll_handle,
 8286        commit_message,
 8287        markdown,
 8288        repository,
 8289        workspace,
 8290        window,
 8291        cx,
 8292    )
 8293}
 8294
 8295fn render_blame_entry(
 8296    ix: usize,
 8297    blame: &Entity<GitBlame>,
 8298    blame_entry: BlameEntry,
 8299    style: &EditorStyle,
 8300    last_used_color: &mut Option<(Hsla, Oid)>,
 8301    editor: Entity<Editor>,
 8302    workspace: Entity<Workspace>,
 8303    buffer: BufferId,
 8304    renderer: &dyn BlameRenderer,
 8305    window: &mut Window,
 8306    cx: &mut App,
 8307) -> Option<AnyElement> {
 8308    let index: u32 = blame_entry.sha.into();
 8309    let mut sha_color = cx.theme().players().color_for_participant(index).cursor;
 8310
 8311    // If the last color we used is the same as the one we get for this line, but
 8312    // the commit SHAs are different, then we try again to get a different color.
 8313    if let Some((color, sha)) = *last_used_color
 8314        && sha != blame_entry.sha
 8315        && color == sha_color
 8316    {
 8317        sha_color = cx.theme().players().color_for_participant(index + 1).cursor;
 8318    }
 8319    last_used_color.replace((sha_color, blame_entry.sha));
 8320
 8321    let blame = blame.read(cx);
 8322    let details = blame.details_for_entry(buffer, &blame_entry);
 8323    let repository = blame.repository(cx, buffer)?;
 8324    renderer.render_blame_entry(
 8325        &style.text,
 8326        blame_entry,
 8327        details,
 8328        repository,
 8329        workspace.downgrade(),
 8330        editor,
 8331        ix,
 8332        sha_color,
 8333        window,
 8334        cx,
 8335    )
 8336}
 8337
 8338#[derive(Debug)]
 8339pub(crate) struct LineWithInvisibles {
 8340    fragments: SmallVec<[LineFragment; 1]>,
 8341    invisibles: Vec<Invisible>,
 8342    len: usize,
 8343    pub(crate) width: Pixels,
 8344    font_size: Pixels,
 8345}
 8346
 8347enum LineFragment {
 8348    Text(ShapedLine),
 8349    Element {
 8350        id: ChunkRendererId,
 8351        element: Option<AnyElement>,
 8352        size: Size<Pixels>,
 8353        len: usize,
 8354    },
 8355}
 8356
 8357impl fmt::Debug for LineFragment {
 8358    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 8359        match self {
 8360            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
 8361            LineFragment::Element { size, len, .. } => f
 8362                .debug_struct("Element")
 8363                .field("size", size)
 8364                .field("len", len)
 8365                .finish(),
 8366        }
 8367    }
 8368}
 8369
 8370impl LineWithInvisibles {
 8371    fn from_chunks<'a>(
 8372        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
 8373        editor_style: &EditorStyle,
 8374        max_line_len: usize,
 8375        max_line_count: usize,
 8376        editor_mode: &EditorMode,
 8377        text_width: Pixels,
 8378        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
 8379        bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
 8380        window: &mut Window,
 8381        cx: &mut App,
 8382    ) -> Vec<Self> {
 8383        let text_style = &editor_style.text;
 8384        let mut layouts = Vec::with_capacity(max_line_count);
 8385        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
 8386        let mut line = String::new();
 8387        let mut invisibles = Vec::new();
 8388        let mut width = Pixels::ZERO;
 8389        let mut len = 0;
 8390        let mut styles = Vec::new();
 8391        let mut non_whitespace_added = false;
 8392        let mut row = 0;
 8393        let mut line_exceeded_max_len = false;
 8394        let font_size = text_style.font_size.to_pixels(window.rem_size());
 8395        let min_contrast = EditorSettings::get_global(cx).minimum_contrast_for_highlights;
 8396
 8397        let ellipsis = SharedString::from("β‹―");
 8398
 8399        for highlighted_chunk in chunks.chain([HighlightedChunk {
 8400            text: "\n",
 8401            style: None,
 8402            is_tab: false,
 8403            is_inlay: false,
 8404            replacement: None,
 8405        }]) {
 8406            if let Some(replacement) = highlighted_chunk.replacement {
 8407                if !line.is_empty() {
 8408                    let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
 8409                    let text_runs: &[TextRun] = if segments.is_empty() {
 8410                        &styles
 8411                    } else {
 8412                        &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
 8413                    };
 8414                    let shaped_line = window.text_system().shape_line(
 8415                        line.clone().into(),
 8416                        font_size,
 8417                        text_runs,
 8418                        None,
 8419                    );
 8420                    width += shaped_line.width;
 8421                    len += shaped_line.len;
 8422                    fragments.push(LineFragment::Text(shaped_line));
 8423                    line.clear();
 8424                    styles.clear();
 8425                }
 8426
 8427                match replacement {
 8428                    ChunkReplacement::Renderer(renderer) => {
 8429                        let available_width = if renderer.constrain_width {
 8430                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
 8431                                ellipsis.clone()
 8432                            } else {
 8433                                SharedString::from(Arc::from(highlighted_chunk.text))
 8434                            };
 8435                            let shaped_line = window.text_system().shape_line(
 8436                                chunk,
 8437                                font_size,
 8438                                &[text_style.to_run(highlighted_chunk.text.len())],
 8439                                None,
 8440                            );
 8441                            AvailableSpace::Definite(shaped_line.width)
 8442                        } else {
 8443                            AvailableSpace::MinContent
 8444                        };
 8445
 8446                        let mut element = (renderer.render)(&mut ChunkRendererContext {
 8447                            context: cx,
 8448                            window,
 8449                            max_width: text_width,
 8450                        });
 8451                        let line_height = text_style.line_height_in_pixels(window.rem_size());
 8452                        let size = element.layout_as_root(
 8453                            size(available_width, AvailableSpace::Definite(line_height)),
 8454                            window,
 8455                            cx,
 8456                        );
 8457
 8458                        width += size.width;
 8459                        len += highlighted_chunk.text.len();
 8460                        fragments.push(LineFragment::Element {
 8461                            id: renderer.id,
 8462                            element: Some(element),
 8463                            size,
 8464                            len: highlighted_chunk.text.len(),
 8465                        });
 8466                    }
 8467                    ChunkReplacement::Str(x) => {
 8468                        let text_style = if let Some(style) = highlighted_chunk.style {
 8469                            Cow::Owned(text_style.clone().highlight(style))
 8470                        } else {
 8471                            Cow::Borrowed(text_style)
 8472                        };
 8473
 8474                        let run = TextRun {
 8475                            len: x.len(),
 8476                            font: text_style.font(),
 8477                            color: text_style.color,
 8478                            background_color: text_style.background_color,
 8479                            underline: text_style.underline,
 8480                            strikethrough: text_style.strikethrough,
 8481                        };
 8482                        let line_layout = window
 8483                            .text_system()
 8484                            .shape_line(x, font_size, &[run], None)
 8485                            .with_len(highlighted_chunk.text.len());
 8486
 8487                        width += line_layout.width;
 8488                        len += highlighted_chunk.text.len();
 8489                        fragments.push(LineFragment::Text(line_layout))
 8490                    }
 8491                }
 8492            } else {
 8493                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
 8494                    if ix > 0 {
 8495                        let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
 8496                        let text_runs = if segments.is_empty() {
 8497                            &styles
 8498                        } else {
 8499                            &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
 8500                        };
 8501                        let shaped_line = window.text_system().shape_line(
 8502                            line.clone().into(),
 8503                            font_size,
 8504                            text_runs,
 8505                            None,
 8506                        );
 8507                        width += shaped_line.width;
 8508                        len += shaped_line.len;
 8509                        fragments.push(LineFragment::Text(shaped_line));
 8510                        layouts.push(Self {
 8511                            width: mem::take(&mut width),
 8512                            len: mem::take(&mut len),
 8513                            fragments: mem::take(&mut fragments),
 8514                            invisibles: std::mem::take(&mut invisibles),
 8515                            font_size,
 8516                        });
 8517
 8518                        line.clear();
 8519                        styles.clear();
 8520                        row += 1;
 8521                        line_exceeded_max_len = false;
 8522                        non_whitespace_added = false;
 8523                        if row == max_line_count {
 8524                            return layouts;
 8525                        }
 8526                    }
 8527
 8528                    if !line_chunk.is_empty() && !line_exceeded_max_len {
 8529                        let text_style = if let Some(style) = highlighted_chunk.style {
 8530                            Cow::Owned(text_style.clone().highlight(style))
 8531                        } else {
 8532                            Cow::Borrowed(text_style)
 8533                        };
 8534
 8535                        if line.len() + line_chunk.len() > max_line_len {
 8536                            let mut chunk_len = max_line_len - line.len();
 8537                            while !line_chunk.is_char_boundary(chunk_len) {
 8538                                chunk_len -= 1;
 8539                            }
 8540                            line_chunk = &line_chunk[..chunk_len];
 8541                            line_exceeded_max_len = true;
 8542                        }
 8543
 8544                        styles.push(TextRun {
 8545                            len: line_chunk.len(),
 8546                            font: text_style.font(),
 8547                            color: text_style.color,
 8548                            background_color: text_style.background_color,
 8549                            underline: text_style.underline,
 8550                            strikethrough: text_style.strikethrough,
 8551                        });
 8552
 8553                        if editor_mode.is_full() && !highlighted_chunk.is_inlay {
 8554                            // Line wrap pads its contents with fake whitespaces,
 8555                            // avoid printing them
 8556                            let is_soft_wrapped = is_row_soft_wrapped(row);
 8557                            if highlighted_chunk.is_tab {
 8558                                if non_whitespace_added || !is_soft_wrapped {
 8559                                    invisibles.push(Invisible::Tab {
 8560                                        line_start_offset: line.len(),
 8561                                        line_end_offset: line.len() + line_chunk.len(),
 8562                                    });
 8563                                }
 8564                            } else {
 8565                                invisibles.extend(line_chunk.char_indices().filter_map(
 8566                                    |(index, c)| {
 8567                                        let is_whitespace = c.is_whitespace();
 8568                                        non_whitespace_added |= !is_whitespace;
 8569                                        if is_whitespace
 8570                                            && (non_whitespace_added || !is_soft_wrapped)
 8571                                        {
 8572                                            Some(Invisible::Whitespace {
 8573                                                line_offset: line.len() + index,
 8574                                            })
 8575                                        } else {
 8576                                            None
 8577                                        }
 8578                                    },
 8579                                ))
 8580                            }
 8581                        }
 8582
 8583                        line.push_str(line_chunk);
 8584                    }
 8585                }
 8586            }
 8587        }
 8588
 8589        layouts
 8590    }
 8591
 8592    /// Takes text runs and non-overlapping left-to-right background ranges with color.
 8593    /// Returns new text runs with adjusted contrast as per background ranges.
 8594    fn split_runs_by_bg_segments(
 8595        text_runs: &[TextRun],
 8596        bg_segments: &[(Range<DisplayPoint>, Hsla)],
 8597        min_contrast: f32,
 8598        start_col_offset: usize,
 8599    ) -> Vec<TextRun> {
 8600        let mut output_runs: Vec<TextRun> = Vec::with_capacity(text_runs.len());
 8601        let mut line_col = start_col_offset;
 8602        let mut segment_ix = 0usize;
 8603
 8604        for text_run in text_runs.iter() {
 8605            let run_start_col = line_col;
 8606            let run_end_col = run_start_col + text_run.len;
 8607            while segment_ix < bg_segments.len()
 8608                && (bg_segments[segment_ix].0.end.column() as usize) <= run_start_col
 8609            {
 8610                segment_ix += 1;
 8611            }
 8612            let mut cursor_col = run_start_col;
 8613            let mut local_segment_ix = segment_ix;
 8614            while local_segment_ix < bg_segments.len() {
 8615                let (range, segment_color) = &bg_segments[local_segment_ix];
 8616                let segment_start_col = range.start.column() as usize;
 8617                let segment_end_col = range.end.column() as usize;
 8618                if segment_start_col >= run_end_col {
 8619                    break;
 8620                }
 8621                if segment_start_col > cursor_col {
 8622                    let span_len = segment_start_col - cursor_col;
 8623                    output_runs.push(TextRun {
 8624                        len: span_len,
 8625                        font: text_run.font.clone(),
 8626                        color: text_run.color,
 8627                        background_color: text_run.background_color,
 8628                        underline: text_run.underline,
 8629                        strikethrough: text_run.strikethrough,
 8630                    });
 8631                    cursor_col = segment_start_col;
 8632                }
 8633                let segment_slice_end_col = segment_end_col.min(run_end_col);
 8634                if segment_slice_end_col > cursor_col {
 8635                    let new_text_color =
 8636                        ensure_minimum_contrast(text_run.color, *segment_color, min_contrast);
 8637                    output_runs.push(TextRun {
 8638                        len: segment_slice_end_col - cursor_col,
 8639                        font: text_run.font.clone(),
 8640                        color: new_text_color,
 8641                        background_color: text_run.background_color,
 8642                        underline: text_run.underline,
 8643                        strikethrough: text_run.strikethrough,
 8644                    });
 8645                    cursor_col = segment_slice_end_col;
 8646                }
 8647                if segment_end_col >= run_end_col {
 8648                    break;
 8649                }
 8650                local_segment_ix += 1;
 8651            }
 8652            if cursor_col < run_end_col {
 8653                output_runs.push(TextRun {
 8654                    len: run_end_col - cursor_col,
 8655                    font: text_run.font.clone(),
 8656                    color: text_run.color,
 8657                    background_color: text_run.background_color,
 8658                    underline: text_run.underline,
 8659                    strikethrough: text_run.strikethrough,
 8660                });
 8661            }
 8662            line_col = run_end_col;
 8663            segment_ix = local_segment_ix;
 8664        }
 8665        output_runs
 8666    }
 8667
 8668    fn prepaint(
 8669        &mut self,
 8670        line_height: Pixels,
 8671        scroll_position: gpui::Point<ScrollOffset>,
 8672        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 8673        row: DisplayRow,
 8674        content_origin: gpui::Point<Pixels>,
 8675        line_elements: &mut SmallVec<[AnyElement; 1]>,
 8676        window: &mut Window,
 8677        cx: &mut App,
 8678    ) {
 8679        let line_y = f32::from(line_height) * Pixels::from(row.as_f64() - scroll_position.y);
 8680        self.prepaint_with_custom_offset(
 8681            line_height,
 8682            scroll_pixel_position,
 8683            content_origin,
 8684            line_y,
 8685            line_elements,
 8686            window,
 8687            cx,
 8688        );
 8689    }
 8690
 8691    fn prepaint_with_custom_offset(
 8692        &mut self,
 8693        line_height: Pixels,
 8694        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
 8695        content_origin: gpui::Point<Pixels>,
 8696        line_y: Pixels,
 8697        line_elements: &mut SmallVec<[AnyElement; 1]>,
 8698        window: &mut Window,
 8699        cx: &mut App,
 8700    ) {
 8701        let mut fragment_origin =
 8702            content_origin + gpui::point(Pixels::from(-scroll_pixel_position.x), line_y);
 8703        for fragment in &mut self.fragments {
 8704            match fragment {
 8705                LineFragment::Text(line) => {
 8706                    fragment_origin.x += line.width;
 8707                }
 8708                LineFragment::Element { element, size, .. } => {
 8709                    let mut element = element
 8710                        .take()
 8711                        .expect("you can't prepaint LineWithInvisibles twice");
 8712
 8713                    // Center the element vertically within the line.
 8714                    let mut element_origin = fragment_origin;
 8715                    element_origin.y += (line_height - size.height) / 2.;
 8716                    element.prepaint_at(element_origin, window, cx);
 8717                    line_elements.push(element);
 8718
 8719                    fragment_origin.x += size.width;
 8720                }
 8721            }
 8722        }
 8723    }
 8724
 8725    fn draw(
 8726        &self,
 8727        layout: &EditorLayout,
 8728        row: DisplayRow,
 8729        content_origin: gpui::Point<Pixels>,
 8730        whitespace_setting: ShowWhitespaceSetting,
 8731        selection_ranges: &[Range<DisplayPoint>],
 8732        window: &mut Window,
 8733        cx: &mut App,
 8734    ) {
 8735        self.draw_with_custom_offset(
 8736            layout,
 8737            row,
 8738            content_origin,
 8739            layout.position_map.line_height
 8740                * (row.as_f64() - layout.position_map.scroll_position.y) as f32,
 8741            whitespace_setting,
 8742            selection_ranges,
 8743            window,
 8744            cx,
 8745        );
 8746    }
 8747
 8748    fn draw_with_custom_offset(
 8749        &self,
 8750        layout: &EditorLayout,
 8751        row: DisplayRow,
 8752        content_origin: gpui::Point<Pixels>,
 8753        line_y: Pixels,
 8754        whitespace_setting: ShowWhitespaceSetting,
 8755        selection_ranges: &[Range<DisplayPoint>],
 8756        window: &mut Window,
 8757        cx: &mut App,
 8758    ) {
 8759        let line_height = layout.position_map.line_height;
 8760        let mut fragment_origin = content_origin
 8761            + gpui::point(
 8762                Pixels::from(-layout.position_map.scroll_pixel_position.x),
 8763                line_y,
 8764            );
 8765
 8766        for fragment in &self.fragments {
 8767            match fragment {
 8768                LineFragment::Text(line) => {
 8769                    line.paint(
 8770                        fragment_origin,
 8771                        line_height,
 8772                        layout.text_align,
 8773                        Some(layout.content_width),
 8774                        window,
 8775                        cx,
 8776                    )
 8777                    .log_err();
 8778                    fragment_origin.x += line.width;
 8779                }
 8780                LineFragment::Element { size, .. } => {
 8781                    fragment_origin.x += size.width;
 8782                }
 8783            }
 8784        }
 8785
 8786        self.draw_invisibles(
 8787            selection_ranges,
 8788            layout,
 8789            content_origin,
 8790            line_y,
 8791            row,
 8792            line_height,
 8793            whitespace_setting,
 8794            window,
 8795            cx,
 8796        );
 8797    }
 8798
 8799    fn draw_background(
 8800        &self,
 8801        layout: &EditorLayout,
 8802        row: DisplayRow,
 8803        content_origin: gpui::Point<Pixels>,
 8804        window: &mut Window,
 8805        cx: &mut App,
 8806    ) {
 8807        let line_height = layout.position_map.line_height;
 8808        let line_y = line_height * (row.as_f64() - layout.position_map.scroll_position.y) as f32;
 8809
 8810        let mut fragment_origin = content_origin
 8811            + gpui::point(
 8812                Pixels::from(-layout.position_map.scroll_pixel_position.x),
 8813                line_y,
 8814            );
 8815
 8816        for fragment in &self.fragments {
 8817            match fragment {
 8818                LineFragment::Text(line) => {
 8819                    line.paint_background(
 8820                        fragment_origin,
 8821                        line_height,
 8822                        layout.text_align,
 8823                        Some(layout.content_width),
 8824                        window,
 8825                        cx,
 8826                    )
 8827                    .log_err();
 8828                    fragment_origin.x += line.width;
 8829                }
 8830                LineFragment::Element { size, .. } => {
 8831                    fragment_origin.x += size.width;
 8832                }
 8833            }
 8834        }
 8835    }
 8836
 8837    fn draw_invisibles(
 8838        &self,
 8839        selection_ranges: &[Range<DisplayPoint>],
 8840        layout: &EditorLayout,
 8841        content_origin: gpui::Point<Pixels>,
 8842        line_y: Pixels,
 8843        row: DisplayRow,
 8844        line_height: Pixels,
 8845        whitespace_setting: ShowWhitespaceSetting,
 8846        window: &mut Window,
 8847        cx: &mut App,
 8848    ) {
 8849        let extract_whitespace_info = |invisible: &Invisible| {
 8850            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
 8851                Invisible::Tab {
 8852                    line_start_offset,
 8853                    line_end_offset,
 8854                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
 8855                Invisible::Whitespace { line_offset } => {
 8856                    (*line_offset, line_offset + 1, &layout.space_invisible)
 8857                }
 8858            };
 8859
 8860            let x_offset: ScrollPixelOffset = self.x_for_index(token_offset).into();
 8861            let invisible_offset: ScrollPixelOffset =
 8862                ((layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0)
 8863                    .into();
 8864            let origin = content_origin
 8865                + gpui::point(
 8866                    Pixels::from(
 8867                        x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
 8868                    ),
 8869                    line_y,
 8870                );
 8871
 8872            (
 8873                [token_offset, token_end_offset],
 8874                Box::new(move |window: &mut Window, cx: &mut App| {
 8875                    invisible_symbol
 8876                        .paint(origin, line_height, TextAlign::Left, None, window, cx)
 8877                        .log_err();
 8878                }),
 8879            )
 8880        };
 8881
 8882        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
 8883        match whitespace_setting {
 8884            ShowWhitespaceSetting::None => (),
 8885            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
 8886            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
 8887                let invisible_point = DisplayPoint::new(row, start as u32);
 8888                if !selection_ranges
 8889                    .iter()
 8890                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
 8891                {
 8892                    return;
 8893                }
 8894
 8895                paint(window, cx);
 8896            }),
 8897
 8898            ShowWhitespaceSetting::Trailing => {
 8899                let mut previous_start = self.len;
 8900                for ([start, end], paint) in invisible_iter.rev() {
 8901                    if previous_start != end {
 8902                        break;
 8903                    }
 8904                    previous_start = start;
 8905                    paint(window, cx);
 8906                }
 8907            }
 8908
 8909            // For a whitespace to be on a boundary, any of the following conditions need to be met:
 8910            // - It is a tab
 8911            // - It is adjacent to an edge (start or end)
 8912            // - It is adjacent to a whitespace (left or right)
 8913            ShowWhitespaceSetting::Boundary => {
 8914                // 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
 8915                // the above cases.
 8916                // Note: We zip in the original `invisibles` to check for tab equality
 8917                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
 8918                for (([start, end], paint), invisible) in
 8919                    invisible_iter.zip_eq(self.invisibles.iter())
 8920                {
 8921                    let should_render = match (&last_seen, invisible) {
 8922                        (_, Invisible::Tab { .. }) => true,
 8923                        (Some((_, last_end, _)), _) => *last_end == start,
 8924                        _ => false,
 8925                    };
 8926
 8927                    if should_render || start == 0 || end == self.len {
 8928                        paint(window, cx);
 8929
 8930                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
 8931                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
 8932                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
 8933                            // Note that we need to make sure that the last one is actually adjacent
 8934                            if !should_render_last && last_end == start {
 8935                                paint_last(window, cx);
 8936                            }
 8937                        }
 8938                    }
 8939
 8940                    // Manually render anything within a selection
 8941                    let invisible_point = DisplayPoint::new(row, start as u32);
 8942                    if selection_ranges.iter().any(|region| {
 8943                        region.start <= invisible_point && invisible_point < region.end
 8944                    }) {
 8945                        paint(window, cx);
 8946                    }
 8947
 8948                    last_seen = Some((should_render, end, paint));
 8949                }
 8950            }
 8951        }
 8952    }
 8953
 8954    pub fn x_for_index(&self, index: usize) -> Pixels {
 8955        let mut fragment_start_x = Pixels::ZERO;
 8956        let mut fragment_start_index = 0;
 8957
 8958        for fragment in &self.fragments {
 8959            match fragment {
 8960                LineFragment::Text(shaped_line) => {
 8961                    let fragment_end_index = fragment_start_index + shaped_line.len;
 8962                    if index < fragment_end_index {
 8963                        return fragment_start_x
 8964                            + shaped_line.x_for_index(index - fragment_start_index);
 8965                    }
 8966                    fragment_start_x += shaped_line.width;
 8967                    fragment_start_index = fragment_end_index;
 8968                }
 8969                LineFragment::Element { len, size, .. } => {
 8970                    let fragment_end_index = fragment_start_index + len;
 8971                    if index < fragment_end_index {
 8972                        return fragment_start_x;
 8973                    }
 8974                    fragment_start_x += size.width;
 8975                    fragment_start_index = fragment_end_index;
 8976                }
 8977            }
 8978        }
 8979
 8980        fragment_start_x
 8981    }
 8982
 8983    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
 8984        let mut fragment_start_x = Pixels::ZERO;
 8985        let mut fragment_start_index = 0;
 8986
 8987        for fragment in &self.fragments {
 8988            match fragment {
 8989                LineFragment::Text(shaped_line) => {
 8990                    let fragment_end_x = fragment_start_x + shaped_line.width;
 8991                    if x < fragment_end_x {
 8992                        return Some(
 8993                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
 8994                        );
 8995                    }
 8996                    fragment_start_x = fragment_end_x;
 8997                    fragment_start_index += shaped_line.len;
 8998                }
 8999                LineFragment::Element { len, size, .. } => {
 9000                    let fragment_end_x = fragment_start_x + size.width;
 9001                    if x < fragment_end_x {
 9002                        return Some(fragment_start_index);
 9003                    }
 9004                    fragment_start_index += len;
 9005                    fragment_start_x = fragment_end_x;
 9006                }
 9007            }
 9008        }
 9009
 9010        None
 9011    }
 9012
 9013    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
 9014        let mut fragment_start_index = 0;
 9015
 9016        for fragment in &self.fragments {
 9017            match fragment {
 9018                LineFragment::Text(shaped_line) => {
 9019                    let fragment_end_index = fragment_start_index + shaped_line.len;
 9020                    if index < fragment_end_index {
 9021                        return shaped_line.font_id_for_index(index - fragment_start_index);
 9022                    }
 9023                    fragment_start_index = fragment_end_index;
 9024                }
 9025                LineFragment::Element { len, .. } => {
 9026                    let fragment_end_index = fragment_start_index + len;
 9027                    if index < fragment_end_index {
 9028                        return None;
 9029                    }
 9030                    fragment_start_index = fragment_end_index;
 9031                }
 9032            }
 9033        }
 9034
 9035        None
 9036    }
 9037
 9038    pub fn alignment_offset(&self, text_align: TextAlign, content_width: Pixels) -> Pixels {
 9039        let line_width = self.width;
 9040        match text_align {
 9041            TextAlign::Left => px(0.0),
 9042            TextAlign::Center => (content_width - line_width) / 2.0,
 9043            TextAlign::Right => content_width - line_width,
 9044        }
 9045    }
 9046}
 9047
 9048#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 9049enum Invisible {
 9050    /// A tab character
 9051    ///
 9052    /// A tab character is internally represented by spaces (configured by the user's tab width)
 9053    /// aligned to the nearest column, so it's necessary to store the start and end offset for
 9054    /// adjacency checks.
 9055    Tab {
 9056        line_start_offset: usize,
 9057        line_end_offset: usize,
 9058    },
 9059    Whitespace {
 9060        line_offset: usize,
 9061    },
 9062}
 9063
 9064impl EditorElement {
 9065    /// Returns the rem size to use when rendering the [`EditorElement`].
 9066    ///
 9067    /// This allows UI elements to scale based on the `buffer_font_size`.
 9068    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
 9069        match self.editor.read(cx).mode {
 9070            EditorMode::Full {
 9071                scale_ui_elements_with_buffer_font_size: true,
 9072                ..
 9073            }
 9074            | EditorMode::Minimap { .. } => {
 9075                let buffer_font_size = self.style.text.font_size;
 9076                match buffer_font_size {
 9077                    AbsoluteLength::Pixels(pixels) => {
 9078                        let rem_size_scale = {
 9079                            // Our default UI font size is 14px on a 16px base scale.
 9080                            // This means the default UI font size is 0.875rems.
 9081                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
 9082
 9083                            // We then determine the delta between a single rem and the default font
 9084                            // size scale.
 9085                            let default_font_size_delta = 1. - default_font_size_scale;
 9086
 9087                            // Finally, we add this delta to 1rem to get the scale factor that
 9088                            // should be used to scale up the UI.
 9089                            1. + default_font_size_delta
 9090                        };
 9091
 9092                        Some(pixels * rem_size_scale)
 9093                    }
 9094                    AbsoluteLength::Rems(rems) => {
 9095                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
 9096                    }
 9097                }
 9098            }
 9099            // We currently use single-line and auto-height editors in UI contexts,
 9100            // so we don't want to scale everything with the buffer font size, as it
 9101            // ends up looking off.
 9102            _ => None,
 9103        }
 9104    }
 9105
 9106    fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
 9107        if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
 9108            parent.upgrade()
 9109        } else {
 9110            Some(self.editor.clone())
 9111        }
 9112    }
 9113}
 9114
 9115#[derive(Default)]
 9116pub struct EditorRequestLayoutState {
 9117    // We use prepaint depth to limit the number of times prepaint is
 9118    // called recursively. We need this so that we can update stale
 9119    // data for e.g. block heights in block map.
 9120    prepaint_depth: Rc<Cell<usize>>,
 9121}
 9122
 9123impl EditorRequestLayoutState {
 9124    // In ideal conditions we only need one more subsequent prepaint call for resize to take effect.
 9125    // i.e. MAX_PREPAINT_DEPTH = 2, but since moving blocks inline (place_near), more lines from
 9126    // below get exposed, and we end up querying blocks for those lines too in subsequent renders.
 9127    // Setting MAX_PREPAINT_DEPTH = 3, passes all tests. Just to be on the safe side we set it to 5, so
 9128    // that subsequent shrinking does not lead to incorrect block placing.
 9129    const MAX_PREPAINT_DEPTH: usize = 5;
 9130
 9131    fn increment_prepaint_depth(&self) -> EditorPrepaintGuard {
 9132        let depth = self.prepaint_depth.get();
 9133        self.prepaint_depth.set(depth + 1);
 9134        EditorPrepaintGuard {
 9135            prepaint_depth: self.prepaint_depth.clone(),
 9136        }
 9137    }
 9138
 9139    fn can_prepaint(&self) -> bool {
 9140        self.prepaint_depth.get() < Self::MAX_PREPAINT_DEPTH
 9141    }
 9142}
 9143
 9144struct EditorPrepaintGuard {
 9145    prepaint_depth: Rc<Cell<usize>>,
 9146}
 9147
 9148impl Drop for EditorPrepaintGuard {
 9149    fn drop(&mut self) {
 9150        let depth = self.prepaint_depth.get();
 9151        self.prepaint_depth.set(depth.saturating_sub(1));
 9152    }
 9153}
 9154
 9155impl Element for EditorElement {
 9156    type RequestLayoutState = EditorRequestLayoutState;
 9157    type PrepaintState = EditorLayout;
 9158
 9159    fn id(&self) -> Option<ElementId> {
 9160        None
 9161    }
 9162
 9163    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
 9164        None
 9165    }
 9166
 9167    fn request_layout(
 9168        &mut self,
 9169        _: Option<&GlobalElementId>,
 9170        _inspector_id: Option<&gpui::InspectorElementId>,
 9171        window: &mut Window,
 9172        cx: &mut App,
 9173    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
 9174        let rem_size = self.rem_size(cx);
 9175        window.with_rem_size(rem_size, |window| {
 9176            self.editor.update(cx, |editor, cx| {
 9177                editor.set_style(self.style.clone(), window, cx);
 9178
 9179                let layout_id = match editor.mode {
 9180                    EditorMode::SingleLine => {
 9181                        let rem_size = window.rem_size();
 9182                        let height = self.style.text.line_height_in_pixels(rem_size);
 9183                        let mut style = Style::default();
 9184                        style.size.height = height.into();
 9185                        style.size.width = relative(1.).into();
 9186                        window.request_layout(style, None, cx)
 9187                    }
 9188                    EditorMode::AutoHeight {
 9189                        min_lines,
 9190                        max_lines,
 9191                    } => {
 9192                        let editor_handle = cx.entity();
 9193                        window.request_measured_layout(
 9194                            Style::default(),
 9195                            move |known_dimensions, available_space, window, cx| {
 9196                                editor_handle
 9197                                    .update(cx, |editor, cx| {
 9198                                        compute_auto_height_layout(
 9199                                            editor,
 9200                                            min_lines,
 9201                                            max_lines,
 9202                                            known_dimensions,
 9203                                            available_space.width,
 9204                                            window,
 9205                                            cx,
 9206                                        )
 9207                                    })
 9208                                    .unwrap_or_default()
 9209                            },
 9210                        )
 9211                    }
 9212                    EditorMode::Minimap { .. } => {
 9213                        let mut style = Style::default();
 9214                        style.size.width = relative(1.).into();
 9215                        style.size.height = relative(1.).into();
 9216                        window.request_layout(style, None, cx)
 9217                    }
 9218                    EditorMode::Full {
 9219                        sizing_behavior, ..
 9220                    } => {
 9221                        let mut style = Style::default();
 9222                        style.size.width = relative(1.).into();
 9223                        if sizing_behavior == SizingBehavior::SizeByContent {
 9224                            let snapshot = editor.snapshot(window, cx);
 9225                            let line_height =
 9226                                self.style.text.line_height_in_pixels(window.rem_size());
 9227                            let scroll_height =
 9228                                (snapshot.max_point().row().next_row().0 as f32) * line_height;
 9229                            style.size.height = scroll_height.into();
 9230                        } else {
 9231                            style.size.height = relative(1.).into();
 9232                        }
 9233                        window.request_layout(style, None, cx)
 9234                    }
 9235                };
 9236
 9237                (layout_id, EditorRequestLayoutState::default())
 9238            })
 9239        })
 9240    }
 9241
 9242    fn prepaint(
 9243        &mut self,
 9244        _: Option<&GlobalElementId>,
 9245        _inspector_id: Option<&gpui::InspectorElementId>,
 9246        bounds: Bounds<Pixels>,
 9247        request_layout: &mut Self::RequestLayoutState,
 9248        window: &mut Window,
 9249        cx: &mut App,
 9250    ) -> Self::PrepaintState {
 9251        let _prepaint_depth_guard = request_layout.increment_prepaint_depth();
 9252        let text_style = TextStyleRefinement {
 9253            font_size: Some(self.style.text.font_size),
 9254            line_height: Some(self.style.text.line_height),
 9255            ..Default::default()
 9256        };
 9257
 9258        let is_minimap = self.editor.read(cx).mode.is_minimap();
 9259        let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
 9260
 9261        if !is_minimap {
 9262            let focus_handle = self.editor.focus_handle(cx);
 9263            window.set_view_id(self.editor.entity_id());
 9264            window.set_focus_handle(&focus_handle, cx);
 9265        }
 9266
 9267        let rem_size = self.rem_size(cx);
 9268        window.with_rem_size(rem_size, |window| {
 9269            window.with_text_style(Some(text_style), |window| {
 9270                window.with_content_mask(Some(ContentMask { bounds }), |window| {
 9271                    let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
 9272                        (editor.snapshot(window, cx), editor.read_only(cx))
 9273                    });
 9274                    let style = &self.style;
 9275
 9276                    let rem_size = window.rem_size();
 9277                    let font_id = window.text_system().resolve_font(&style.text.font());
 9278                    let font_size = style.text.font_size.to_pixels(rem_size);
 9279                    let line_height = style.text.line_height_in_pixels(rem_size);
 9280                    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
 9281                    let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
 9282                    let glyph_grid_cell = size(em_advance, line_height);
 9283
 9284                    let gutter_dimensions =
 9285                        snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
 9286                    let text_width = bounds.size.width - gutter_dimensions.width;
 9287
 9288                    let settings = EditorSettings::get_global(cx);
 9289                    let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
 9290                    let vertical_scrollbar_width = (scrollbars_shown
 9291                        && settings.scrollbar.axes.vertical
 9292                        && self.editor.read(cx).show_scrollbars.vertical)
 9293                        .then_some(style.scrollbar_width)
 9294                        .unwrap_or_default();
 9295                    let minimap_width = self
 9296                        .get_minimap_width(
 9297                            &settings.minimap,
 9298                            scrollbars_shown,
 9299                            text_width,
 9300                            em_width,
 9301                            font_size,
 9302                            rem_size,
 9303                            cx,
 9304                        )
 9305                        .unwrap_or_default();
 9306
 9307                    let right_margin = minimap_width + vertical_scrollbar_width;
 9308
 9309                    let editor_width =
 9310                        text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
 9311                    let editor_margins = EditorMargins {
 9312                        gutter: gutter_dimensions,
 9313                        right: right_margin,
 9314                    };
 9315
 9316                    snapshot = self.editor.update(cx, |editor, cx| {
 9317                        editor.last_bounds = Some(bounds);
 9318                        editor.gutter_dimensions = gutter_dimensions;
 9319                        editor.set_visible_line_count(
 9320                            (bounds.size.height / line_height) as f64,
 9321                            window,
 9322                            cx,
 9323                        );
 9324                        editor.set_visible_column_count(f64::from(editor_width / em_advance));
 9325
 9326                        if matches!(
 9327                            editor.mode,
 9328                            EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
 9329                        ) {
 9330                            snapshot
 9331                        } else {
 9332                            let wrap_width_for = |column: u32| (column as f32 * em_advance).ceil();
 9333                            let wrap_width = match editor.soft_wrap_mode(cx) {
 9334                                SoftWrap::GitDiff => None,
 9335                                SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
 9336                                SoftWrap::EditorWidth => Some(editor_width),
 9337                                SoftWrap::Column(column) => Some(wrap_width_for(column)),
 9338                                SoftWrap::Bounded(column) => {
 9339                                    Some(editor_width.min(wrap_width_for(column)))
 9340                                }
 9341                            };
 9342
 9343                            if editor.set_wrap_width(wrap_width, cx) {
 9344                                editor.snapshot(window, cx)
 9345                            } else {
 9346                                snapshot
 9347                            }
 9348                        }
 9349                    });
 9350
 9351                    let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
 9352                    let gutter_hitbox = window.insert_hitbox(
 9353                        gutter_bounds(bounds, gutter_dimensions),
 9354                        HitboxBehavior::Normal,
 9355                    );
 9356                    let text_hitbox = window.insert_hitbox(
 9357                        Bounds {
 9358                            origin: gutter_hitbox.top_right(),
 9359                            size: size(text_width, bounds.size.height),
 9360                        },
 9361                        HitboxBehavior::Normal,
 9362                    );
 9363
 9364                    // Offset the content_bounds from the text_bounds by the gutter margin (which
 9365                    // is roughly half a character wide) to make hit testing work more like how we want.
 9366                    let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
 9367                    let content_origin = text_hitbox.origin + content_offset;
 9368
 9369                    let height_in_lines = f64::from(bounds.size.height / line_height);
 9370                    let max_row = snapshot.max_point().row().as_f64();
 9371
 9372                    // Calculate how much of the editor is clipped by parent containers (e.g., List).
 9373                    // This allows us to only render lines that are actually visible, which is
 9374                    // critical for performance when large AutoHeight editors are inside Lists.
 9375                    let visible_bounds = window.content_mask().bounds;
 9376                    let clipped_top = (visible_bounds.origin.y - bounds.origin.y).max(px(0.));
 9377                    let clipped_top_in_lines = f64::from(clipped_top / line_height);
 9378                    let visible_height_in_lines =
 9379                        f64::from(visible_bounds.size.height / line_height);
 9380
 9381                    // The max scroll position for the top of the window
 9382                    let max_scroll_top = if matches!(
 9383                        snapshot.mode,
 9384                        EditorMode::SingleLine
 9385                            | EditorMode::AutoHeight { .. }
 9386                            | EditorMode::Full {
 9387                                sizing_behavior: SizingBehavior::ExcludeOverscrollMargin
 9388                                    | SizingBehavior::SizeByContent,
 9389                                ..
 9390                            }
 9391                    ) {
 9392                        (max_row - height_in_lines + 1.).max(0.)
 9393                    } else {
 9394                        let settings = EditorSettings::get_global(cx);
 9395                        match settings.scroll_beyond_last_line {
 9396                            ScrollBeyondLastLine::OnePage => max_row,
 9397                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
 9398                            ScrollBeyondLastLine::VerticalScrollMargin => {
 9399                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
 9400                                    .max(0.)
 9401                            }
 9402                        }
 9403                    };
 9404
 9405                    let (
 9406                        autoscroll_request,
 9407                        autoscroll_containing_element,
 9408                        needs_horizontal_autoscroll,
 9409                    ) = self.editor.update(cx, |editor, cx| {
 9410                        let autoscroll_request = editor.scroll_manager.take_autoscroll_request();
 9411
 9412                        let autoscroll_containing_element =
 9413                            autoscroll_request.is_some() || editor.has_pending_selection();
 9414
 9415                        let (needs_horizontal_autoscroll, was_scrolled) = editor
 9416                            .autoscroll_vertically(
 9417                                bounds,
 9418                                line_height,
 9419                                max_scroll_top,
 9420                                autoscroll_request,
 9421                                window,
 9422                                cx,
 9423                            );
 9424                        if was_scrolled.0 {
 9425                            snapshot = editor.snapshot(window, cx);
 9426                        }
 9427                        (
 9428                            autoscroll_request,
 9429                            autoscroll_containing_element,
 9430                            needs_horizontal_autoscroll,
 9431                        )
 9432                    });
 9433
 9434                    let mut scroll_position = snapshot.scroll_position();
 9435                    // The scroll position is a fractional point, the whole number of which represents
 9436                    // the top of the window in terms of display rows.
 9437                    // We add clipped_top_in_lines to skip rows that are clipped by parent containers,
 9438                    // but we don't modify scroll_position itself since the parent handles positioning.
 9439                    let max_row = snapshot.max_point().row();
 9440                    let start_row = cmp::min(
 9441                        DisplayRow((scroll_position.y + clipped_top_in_lines).floor() as u32),
 9442                        max_row,
 9443                    );
 9444                    let end_row = cmp::min(
 9445                        (scroll_position.y + clipped_top_in_lines + visible_height_in_lines).ceil()
 9446                            as u32,
 9447                        max_row.next_row().0,
 9448                    );
 9449                    let end_row = DisplayRow(end_row);
 9450
 9451                    let row_infos = snapshot // note we only get the visual range
 9452                        .row_infos(start_row)
 9453                        .take((start_row..end_row).len())
 9454                        .collect::<Vec<RowInfo>>();
 9455                    let is_row_soft_wrapped = |row: usize| {
 9456                        row_infos
 9457                            .get(row)
 9458                            .is_none_or(|info| info.buffer_row.is_none())
 9459                    };
 9460
 9461                    let start_anchor = if start_row == Default::default() {
 9462                        Anchor::min()
 9463                    } else {
 9464                        snapshot.buffer_snapshot().anchor_before(
 9465                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
 9466                        )
 9467                    };
 9468                    let end_anchor = if end_row > max_row {
 9469                        Anchor::max()
 9470                    } else {
 9471                        snapshot.buffer_snapshot().anchor_before(
 9472                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
 9473                        )
 9474                    };
 9475
 9476                    let mut highlighted_rows = self
 9477                        .editor
 9478                        .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
 9479
 9480                    let is_light = cx.theme().appearance().is_light();
 9481
 9482                    let mut highlighted_ranges = self
 9483                        .editor_with_selections(cx)
 9484                        .map(|editor| {
 9485                            editor.read(cx).background_highlights_in_range(
 9486                                start_anchor..end_anchor,
 9487                                &snapshot.display_snapshot,
 9488                                cx.theme(),
 9489                            )
 9490                        })
 9491                        .unwrap_or_default();
 9492
 9493                    for (ix, row_info) in row_infos.iter().enumerate() {
 9494                        let Some(diff_status) = row_info.diff_status else {
 9495                            continue;
 9496                        };
 9497
 9498                        let background_color = match diff_status.kind {
 9499                            DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
 9500                            DiffHunkStatusKind::Deleted => {
 9501                                cx.theme().colors().version_control_deleted
 9502                            }
 9503                            DiffHunkStatusKind::Modified => {
 9504                                debug_panic!("modified diff status for row info");
 9505                                continue;
 9506                            }
 9507                        };
 9508
 9509                        let hunk_opacity = if is_light { 0.16 } else { 0.12 };
 9510
 9511                        let hollow_highlight = LineHighlight {
 9512                            background: (background_color.opacity(if is_light {
 9513                                0.08
 9514                            } else {
 9515                                0.06
 9516                            }))
 9517                            .into(),
 9518                            border: Some(if is_light {
 9519                                background_color.opacity(0.48)
 9520                            } else {
 9521                                background_color.opacity(0.36)
 9522                            }),
 9523                            include_gutter: true,
 9524                            type_id: None,
 9525                        };
 9526
 9527                        let filled_highlight = LineHighlight {
 9528                            background: solid_background(background_color.opacity(hunk_opacity)),
 9529                            border: None,
 9530                            include_gutter: true,
 9531                            type_id: None,
 9532                        };
 9533
 9534                        let background = if Self::diff_hunk_hollow(diff_status, cx) {
 9535                            hollow_highlight
 9536                        } else {
 9537                            filled_highlight
 9538                        };
 9539
 9540                        let base_display_point =
 9541                            DisplayPoint::new(start_row + DisplayRow(ix as u32), 0);
 9542
 9543                        highlighted_rows
 9544                            .entry(base_display_point.row())
 9545                            .or_insert(background);
 9546                    }
 9547
 9548                    let highlighted_gutter_ranges =
 9549                        self.editor.read(cx).gutter_highlights_in_range(
 9550                            start_anchor..end_anchor,
 9551                            &snapshot.display_snapshot,
 9552                            cx,
 9553                        );
 9554
 9555                    let document_colors = self
 9556                        .editor
 9557                        .read(cx)
 9558                        .colors
 9559                        .as_ref()
 9560                        .map(|colors| colors.editor_display_highlights(&snapshot));
 9561                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
 9562                        start_anchor..end_anchor,
 9563                        &snapshot.display_snapshot,
 9564                        cx,
 9565                    );
 9566
 9567                    let (local_selections, selected_buffer_ids, latest_selection_anchors): (
 9568                        Vec<Selection<Point>>,
 9569                        Vec<BufferId>,
 9570                        HashMap<BufferId, Anchor>,
 9571                    ) = self
 9572                        .editor_with_selections(cx)
 9573                        .map(|editor| {
 9574                            editor.update(cx, |editor, cx| {
 9575                                let all_selections =
 9576                                    editor.selections.all::<Point>(&snapshot.display_snapshot);
 9577                                let all_anchor_selections =
 9578                                    editor.selections.all_anchors(&snapshot.display_snapshot);
 9579                                let selected_buffer_ids =
 9580                                    if editor.buffer_kind(cx) == ItemBufferKind::Singleton {
 9581                                        Vec::new()
 9582                                    } else {
 9583                                        let mut selected_buffer_ids =
 9584                                            Vec::with_capacity(all_selections.len());
 9585
 9586                                        for selection in all_selections {
 9587                                            for buffer_id in snapshot
 9588                                                .buffer_snapshot()
 9589                                                .buffer_ids_for_range(selection.range())
 9590                                            {
 9591                                                if selected_buffer_ids.last() != Some(&buffer_id) {
 9592                                                    selected_buffer_ids.push(buffer_id);
 9593                                                }
 9594                                            }
 9595                                        }
 9596
 9597                                        selected_buffer_ids
 9598                                    };
 9599
 9600                                let mut selections = editor.selections.disjoint_in_range(
 9601                                    start_anchor..end_anchor,
 9602                                    &snapshot.display_snapshot,
 9603                                );
 9604                                selections
 9605                                    .extend(editor.selections.pending(&snapshot.display_snapshot));
 9606
 9607                                let mut anchors_by_buffer: HashMap<BufferId, (usize, Anchor)> =
 9608                                    HashMap::default();
 9609                                for selection in all_anchor_selections.iter() {
 9610                                    let head = selection.head();
 9611                                    if let Some(buffer_id) = head.text_anchor.buffer_id {
 9612                                        anchors_by_buffer
 9613                                            .entry(buffer_id)
 9614                                            .and_modify(|(latest_id, latest_anchor)| {
 9615                                                if selection.id > *latest_id {
 9616                                                    *latest_id = selection.id;
 9617                                                    *latest_anchor = head;
 9618                                                }
 9619                                            })
 9620                                            .or_insert((selection.id, head));
 9621                                    }
 9622                                }
 9623                                let latest_selection_anchors = anchors_by_buffer
 9624                                    .into_iter()
 9625                                    .map(|(buffer_id, (_, anchor))| (buffer_id, anchor))
 9626                                    .collect();
 9627
 9628                                (selections, selected_buffer_ids, latest_selection_anchors)
 9629                            })
 9630                        })
 9631                        .unwrap_or_else(|| (Vec::new(), Vec::new(), HashMap::default()));
 9632
 9633                    let (selections, mut active_rows, newest_selection_head) = self
 9634                        .layout_selections(
 9635                            start_anchor,
 9636                            end_anchor,
 9637                            &local_selections,
 9638                            &snapshot,
 9639                            start_row,
 9640                            end_row,
 9641                            window,
 9642                            cx,
 9643                        );
 9644
 9645                    // relative rows are based on newest selection, even outside the visible area
 9646                    let relative_row_base = self.editor.update(cx, |editor, cx| {
 9647                        (editor.selections.count() != 0).then(|| {
 9648                            let newest = editor
 9649                                .selections
 9650                                .newest::<Point>(&editor.display_snapshot(cx));
 9651
 9652                            SelectionLayout::new(
 9653                                newest,
 9654                                editor.selections.line_mode(),
 9655                                editor.cursor_offset_on_selection,
 9656                                editor.cursor_shape,
 9657                                &snapshot,
 9658                                true,
 9659                                true,
 9660                                None,
 9661                            )
 9662                            .head
 9663                            .row()
 9664                        })
 9665                    });
 9666
 9667                    let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
 9668                        editor.active_breakpoints(start_row..end_row, window, cx)
 9669                    });
 9670                    for (display_row, (_, bp, state)) in &breakpoint_rows {
 9671                        if bp.is_enabled() && state.is_none_or(|s| s.verified) {
 9672                            active_rows.entry(*display_row).or_default().breakpoint = true;
 9673                        }
 9674                    }
 9675
 9676                    let line_numbers = self.layout_line_numbers(
 9677                        Some(&gutter_hitbox),
 9678                        gutter_dimensions,
 9679                        line_height,
 9680                        scroll_position,
 9681                        start_row..end_row,
 9682                        &row_infos,
 9683                        &active_rows,
 9684                        relative_row_base,
 9685                        &snapshot,
 9686                        window,
 9687                        cx,
 9688                    );
 9689
 9690                    // We add the gutter breakpoint indicator to breakpoint_rows after painting
 9691                    // line numbers so we don't paint a line number debug accent color if a user
 9692                    // has their mouse over that line when a breakpoint isn't there
 9693                    self.editor.update(cx, |editor, _| {
 9694                        if let Some(phantom_breakpoint) = &mut editor
 9695                            .gutter_breakpoint_indicator
 9696                            .0
 9697                            .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
 9698                        {
 9699                            // Is there a non-phantom breakpoint on this line?
 9700                            phantom_breakpoint.collides_with_existing_breakpoint = true;
 9701                            breakpoint_rows
 9702                                .entry(phantom_breakpoint.display_row)
 9703                                .or_insert_with(|| {
 9704                                    let position = snapshot.display_point_to_anchor(
 9705                                        DisplayPoint::new(phantom_breakpoint.display_row, 0),
 9706                                        Bias::Right,
 9707                                    );
 9708                                    let breakpoint = Breakpoint::new_standard();
 9709                                    phantom_breakpoint.collides_with_existing_breakpoint = false;
 9710                                    (position, breakpoint, None)
 9711                                });
 9712                        }
 9713                    });
 9714
 9715                    let mut expand_toggles =
 9716                        window.with_element_namespace("expand_toggles", |window| {
 9717                            self.layout_expand_toggles(
 9718                                &gutter_hitbox,
 9719                                gutter_dimensions,
 9720                                em_width,
 9721                                line_height,
 9722                                scroll_position,
 9723                                &row_infos,
 9724                                window,
 9725                                cx,
 9726                            )
 9727                        });
 9728
 9729                    let mut crease_toggles =
 9730                        window.with_element_namespace("crease_toggles", |window| {
 9731                            self.layout_crease_toggles(
 9732                                start_row..end_row,
 9733                                &row_infos,
 9734                                &active_rows,
 9735                                &snapshot,
 9736                                window,
 9737                                cx,
 9738                            )
 9739                        });
 9740                    let crease_trailers =
 9741                        window.with_element_namespace("crease_trailers", |window| {
 9742                            self.layout_crease_trailers(
 9743                                row_infos.iter().cloned(),
 9744                                &snapshot,
 9745                                window,
 9746                                cx,
 9747                            )
 9748                        });
 9749
 9750                    let display_hunks = self.layout_gutter_diff_hunks(
 9751                        line_height,
 9752                        &gutter_hitbox,
 9753                        start_row..end_row,
 9754                        &snapshot,
 9755                        window,
 9756                        cx,
 9757                    );
 9758
 9759                    Self::layout_word_diff_highlights(
 9760                        &display_hunks,
 9761                        &row_infos,
 9762                        start_row,
 9763                        &snapshot,
 9764                        &mut highlighted_ranges,
 9765                        cx,
 9766                    );
 9767
 9768                    let merged_highlighted_ranges =
 9769                        if let Some((_, colors)) = document_colors.as_ref() {
 9770                            &highlighted_ranges
 9771                                .clone()
 9772                                .into_iter()
 9773                                .chain(colors.clone())
 9774                                .collect()
 9775                        } else {
 9776                            &highlighted_ranges
 9777                        };
 9778                    let bg_segments_per_row = Self::bg_segments_per_row(
 9779                        start_row..end_row,
 9780                        &selections,
 9781                        &merged_highlighted_ranges,
 9782                        self.style.background,
 9783                    );
 9784
 9785                    let mut line_layouts = Self::layout_lines(
 9786                        start_row..end_row,
 9787                        &snapshot,
 9788                        &self.style,
 9789                        editor_width,
 9790                        is_row_soft_wrapped,
 9791                        &bg_segments_per_row,
 9792                        window,
 9793                        cx,
 9794                    );
 9795                    let new_renderer_widths = (!is_minimap).then(|| {
 9796                        line_layouts
 9797                            .iter()
 9798                            .flat_map(|layout| &layout.fragments)
 9799                            .filter_map(|fragment| {
 9800                                if let LineFragment::Element { id, size, .. } = fragment {
 9801                                    Some((*id, size.width))
 9802                                } else {
 9803                                    None
 9804                                }
 9805                            })
 9806                    });
 9807                    if new_renderer_widths.is_some_and(|new_renderer_widths| {
 9808                        self.editor.update(cx, |editor, cx| {
 9809                            editor.update_renderer_widths(new_renderer_widths, cx)
 9810                        })
 9811                    }) {
 9812                        // If the fold widths have changed, we need to prepaint
 9813                        // the element again to account for any changes in
 9814                        // wrapping.
 9815                        if request_layout.can_prepaint() {
 9816                            return self.prepaint(
 9817                                None,
 9818                                _inspector_id,
 9819                                bounds,
 9820                                request_layout,
 9821                                window,
 9822                                cx,
 9823                            );
 9824                        } else {
 9825                            debug_panic!(concat!(
 9826                                "skipping recursive prepaint at max depth. ",
 9827                                "renderer widths may be stale."
 9828                            ));
 9829                        }
 9830                    }
 9831
 9832                    let longest_line_blame_width = self
 9833                        .editor
 9834                        .update(cx, |editor, cx| {
 9835                            if !editor.show_git_blame_inline {
 9836                                return None;
 9837                            }
 9838                            let blame = editor.blame.as_ref()?;
 9839                            let (_, blame_entry) = blame
 9840                                .update(cx, |blame, cx| {
 9841                                    let row_infos =
 9842                                        snapshot.row_infos(snapshot.longest_row()).next()?;
 9843                                    blame.blame_for_rows(&[row_infos], cx).next()
 9844                                })
 9845                                .flatten()?;
 9846                            let mut element = render_inline_blame_entry(blame_entry, style, cx)?;
 9847                            let inline_blame_padding =
 9848                                ProjectSettings::get_global(cx).git.inline_blame.padding as f32
 9849                                    * em_advance;
 9850                            Some(
 9851                                element
 9852                                    .layout_as_root(AvailableSpace::min_size(), window, cx)
 9853                                    .width
 9854                                    + inline_blame_padding,
 9855                            )
 9856                        })
 9857                        .unwrap_or(Pixels::ZERO);
 9858
 9859                    let longest_line_width = layout_line(
 9860                        snapshot.longest_row(),
 9861                        &snapshot,
 9862                        style,
 9863                        editor_width,
 9864                        is_row_soft_wrapped,
 9865                        window,
 9866                        cx,
 9867                    )
 9868                    .width;
 9869
 9870                    let scrollbar_layout_information = ScrollbarLayoutInformation::new(
 9871                        text_hitbox.bounds,
 9872                        glyph_grid_cell,
 9873                        size(
 9874                            longest_line_width,
 9875                            Pixels::from(max_row.as_f64() * f64::from(line_height)),
 9876                        ),
 9877                        longest_line_blame_width,
 9878                        EditorSettings::get_global(cx),
 9879                    );
 9880
 9881                    let mut scroll_width = scrollbar_layout_information.scroll_range.width;
 9882
 9883                    let sticky_header_excerpt = if snapshot.buffer_snapshot().show_headers() {
 9884                        snapshot.sticky_header_excerpt(scroll_position.y)
 9885                    } else {
 9886                        None
 9887                    };
 9888                    let sticky_header_excerpt_id =
 9889                        sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
 9890
 9891                    let blocks = (!is_minimap)
 9892                        .then(|| {
 9893                            window.with_element_namespace("blocks", |window| {
 9894                                self.render_blocks(
 9895                                    start_row..end_row,
 9896                                    &snapshot,
 9897                                    &hitbox,
 9898                                    &text_hitbox,
 9899                                    editor_width,
 9900                                    &mut scroll_width,
 9901                                    &editor_margins,
 9902                                    em_width,
 9903                                    gutter_dimensions.full_width(),
 9904                                    line_height,
 9905                                    &mut line_layouts,
 9906                                    &local_selections,
 9907                                    &selected_buffer_ids,
 9908                                    &latest_selection_anchors,
 9909                                    is_row_soft_wrapped,
 9910                                    sticky_header_excerpt_id,
 9911                                    window,
 9912                                    cx,
 9913                                )
 9914                            })
 9915                        })
 9916                        .unwrap_or_default();
 9917                    let RenderBlocksOutput {
 9918                        mut blocks,
 9919                        row_block_types,
 9920                        resized_blocks,
 9921                    } = blocks;
 9922                    if let Some(resized_blocks) = resized_blocks {
 9923                        self.editor.update(cx, |editor, cx| {
 9924                            editor.resize_blocks(
 9925                                resized_blocks,
 9926                                autoscroll_request.map(|(autoscroll, _)| autoscroll),
 9927                                cx,
 9928                            )
 9929                        });
 9930                        if request_layout.can_prepaint() {
 9931                            return self.prepaint(
 9932                                None,
 9933                                _inspector_id,
 9934                                bounds,
 9935                                request_layout,
 9936                                window,
 9937                                cx,
 9938                            );
 9939                        } else {
 9940                            debug_panic!(concat!(
 9941                                "skipping recursive prepaint at max depth. ",
 9942                                "block layout may be stale."
 9943                            ));
 9944                        }
 9945                    }
 9946
 9947                    let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
 9948                        window.with_element_namespace("blocks", |window| {
 9949                            self.layout_sticky_buffer_header(
 9950                                sticky_header_excerpt,
 9951                                scroll_position,
 9952                                line_height,
 9953                                right_margin,
 9954                                &snapshot,
 9955                                &hitbox,
 9956                                &selected_buffer_ids,
 9957                                &blocks,
 9958                                &latest_selection_anchors,
 9959                                window,
 9960                                cx,
 9961                            )
 9962                        })
 9963                    });
 9964
 9965                    let start_buffer_row =
 9966                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot()).row);
 9967                    let end_buffer_row =
 9968                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot()).row);
 9969
 9970                    let scroll_max: gpui::Point<ScrollPixelOffset> = point(
 9971                        ScrollPixelOffset::from(
 9972                            ((scroll_width - editor_width) / em_advance).max(0.0),
 9973                        ),
 9974                        max_scroll_top,
 9975                    );
 9976
 9977                    self.editor.update(cx, |editor, cx| {
 9978                        if editor.scroll_manager.clamp_scroll_left(scroll_max.x) {
 9979                            scroll_position.x = scroll_position.x.min(scroll_max.x);
 9980                        }
 9981
 9982                        if needs_horizontal_autoscroll.0
 9983                            && let Some(new_scroll_position) = editor.autoscroll_horizontally(
 9984                                start_row,
 9985                                editor_width,
 9986                                scroll_width,
 9987                                em_advance,
 9988                                &line_layouts,
 9989                                autoscroll_request,
 9990                                window,
 9991                                cx,
 9992                            )
 9993                        {
 9994                            scroll_position = new_scroll_position;
 9995                        }
 9996                    });
 9997
 9998                    let scroll_pixel_position = point(
 9999                        scroll_position.x * f64::from(em_advance),
10000                        scroll_position.y * f64::from(line_height),
10001                    );
10002                    let sticky_headers = if !is_minimap
10003                        && is_singleton
10004                        && EditorSettings::get_global(cx).sticky_scroll.enabled
10005                    {
10006                        let relative = self.editor.read(cx).relative_line_numbers(cx);
10007                        self.layout_sticky_headers(
10008                            &snapshot,
10009                            editor_width,
10010                            is_row_soft_wrapped,
10011                            line_height,
10012                            scroll_pixel_position,
10013                            content_origin,
10014                            &gutter_dimensions,
10015                            &gutter_hitbox,
10016                            &text_hitbox,
10017                            &style,
10018                            relative,
10019                            relative_row_base,
10020                            window,
10021                            cx,
10022                        )
10023                    } else {
10024                        None
10025                    };
10026                    let indent_guides = self.layout_indent_guides(
10027                        content_origin,
10028                        text_hitbox.origin,
10029                        start_buffer_row..end_buffer_row,
10030                        scroll_pixel_position,
10031                        line_height,
10032                        &snapshot,
10033                        window,
10034                        cx,
10035                    );
10036
10037                    let crease_trailers =
10038                        window.with_element_namespace("crease_trailers", |window| {
10039                            self.prepaint_crease_trailers(
10040                                crease_trailers,
10041                                &line_layouts,
10042                                line_height,
10043                                content_origin,
10044                                scroll_pixel_position,
10045                                em_width,
10046                                window,
10047                                cx,
10048                            )
10049                        });
10050
10051                    let (edit_prediction_popover, edit_prediction_popover_origin) = self
10052                        .editor
10053                        .update(cx, |editor, cx| {
10054                            editor.render_edit_prediction_popover(
10055                                &text_hitbox.bounds,
10056                                content_origin,
10057                                right_margin,
10058                                &snapshot,
10059                                start_row..end_row,
10060                                scroll_position.y,
10061                                scroll_position.y + height_in_lines,
10062                                &line_layouts,
10063                                line_height,
10064                                scroll_position,
10065                                scroll_pixel_position,
10066                                newest_selection_head,
10067                                editor_width,
10068                                style,
10069                                window,
10070                                cx,
10071                            )
10072                        })
10073                        .unzip();
10074
10075                    let mut inline_diagnostics = self.layout_inline_diagnostics(
10076                        &line_layouts,
10077                        &crease_trailers,
10078                        &row_block_types,
10079                        content_origin,
10080                        scroll_position,
10081                        scroll_pixel_position,
10082                        edit_prediction_popover_origin,
10083                        start_row,
10084                        end_row,
10085                        line_height,
10086                        em_width,
10087                        style,
10088                        window,
10089                        cx,
10090                    );
10091
10092                    let mut inline_blame_layout = None;
10093                    let mut inline_code_actions = None;
10094                    if let Some(newest_selection_head) = newest_selection_head {
10095                        let display_row = newest_selection_head.row();
10096                        if (start_row..end_row).contains(&display_row)
10097                            && !row_block_types.contains_key(&display_row)
10098                        {
10099                            inline_code_actions = self.layout_inline_code_actions(
10100                                newest_selection_head,
10101                                content_origin,
10102                                scroll_position,
10103                                scroll_pixel_position,
10104                                line_height,
10105                                &snapshot,
10106                                window,
10107                                cx,
10108                            );
10109
10110                            let line_ix = display_row.minus(start_row) as usize;
10111                            if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
10112                                row_infos.get(line_ix),
10113                                line_layouts.get(line_ix),
10114                                crease_trailers.get(line_ix),
10115                            ) {
10116                                let crease_trailer_layout = crease_trailer.as_ref();
10117                                if let Some(layout) = self.layout_inline_blame(
10118                                    display_row,
10119                                    row_info,
10120                                    line_layout,
10121                                    crease_trailer_layout,
10122                                    em_width,
10123                                    content_origin,
10124                                    scroll_position,
10125                                    scroll_pixel_position,
10126                                    line_height,
10127                                    window,
10128                                    cx,
10129                                ) {
10130                                    inline_blame_layout = Some(layout);
10131                                    // Blame overrides inline diagnostics
10132                                    inline_diagnostics.remove(&display_row);
10133                                }
10134                            } else {
10135                                log::error!(
10136                                    "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
10137                                    line_layouts.len(): {}, \
10138                                    crease_trailers.len(): {}",
10139                                    line_ix,
10140                                    row_infos.len(),
10141                                    line_layouts.len(),
10142                                    crease_trailers.len(),
10143                                );
10144                            }
10145                        }
10146                    }
10147
10148                    let blamed_display_rows = self.layout_blame_entries(
10149                        &row_infos,
10150                        em_width,
10151                        scroll_position,
10152                        line_height,
10153                        &gutter_hitbox,
10154                        gutter_dimensions.git_blame_entries_width,
10155                        window,
10156                        cx,
10157                    );
10158
10159                    let line_elements = self.prepaint_lines(
10160                        start_row,
10161                        &mut line_layouts,
10162                        line_height,
10163                        scroll_position,
10164                        scroll_pixel_position,
10165                        content_origin,
10166                        window,
10167                        cx,
10168                    );
10169
10170                    window.with_element_namespace("blocks", |window| {
10171                        self.layout_blocks(
10172                            &mut blocks,
10173                            &hitbox,
10174                            line_height,
10175                            scroll_position,
10176                            scroll_pixel_position,
10177                            window,
10178                            cx,
10179                        );
10180                    });
10181
10182                    let cursors = self.collect_cursors(&snapshot, cx);
10183                    let visible_row_range = start_row..end_row;
10184                    let non_visible_cursors = cursors
10185                        .iter()
10186                        .any(|c| !visible_row_range.contains(&c.0.row()));
10187
10188                    let visible_cursors = self.layout_visible_cursors(
10189                        &snapshot,
10190                        &selections,
10191                        &row_block_types,
10192                        start_row..end_row,
10193                        &line_layouts,
10194                        &text_hitbox,
10195                        content_origin,
10196                        scroll_position,
10197                        scroll_pixel_position,
10198                        line_height,
10199                        em_width,
10200                        em_advance,
10201                        autoscroll_containing_element,
10202                        window,
10203                        cx,
10204                    );
10205
10206                    let scrollbars_layout = self.layout_scrollbars(
10207                        &snapshot,
10208                        &scrollbar_layout_information,
10209                        content_offset,
10210                        scroll_position,
10211                        non_visible_cursors,
10212                        right_margin,
10213                        editor_width,
10214                        window,
10215                        cx,
10216                    );
10217
10218                    let gutter_settings = EditorSettings::get_global(cx).gutter;
10219
10220                    let context_menu_layout =
10221                        if let Some(newest_selection_head) = newest_selection_head {
10222                            let newest_selection_point =
10223                                newest_selection_head.to_point(&snapshot.display_snapshot);
10224                            if (start_row..end_row).contains(&newest_selection_head.row()) {
10225                                self.layout_cursor_popovers(
10226                                    line_height,
10227                                    &text_hitbox,
10228                                    content_origin,
10229                                    right_margin,
10230                                    start_row,
10231                                    scroll_pixel_position,
10232                                    &line_layouts,
10233                                    newest_selection_head,
10234                                    newest_selection_point,
10235                                    style,
10236                                    window,
10237                                    cx,
10238                                )
10239                            } else {
10240                                None
10241                            }
10242                        } else {
10243                            None
10244                        };
10245
10246                    self.layout_gutter_menu(
10247                        line_height,
10248                        &text_hitbox,
10249                        content_origin,
10250                        right_margin,
10251                        scroll_pixel_position,
10252                        gutter_dimensions.width - gutter_dimensions.left_padding,
10253                        window,
10254                        cx,
10255                    );
10256
10257                    let test_indicators = if gutter_settings.runnables {
10258                        self.layout_run_indicators(
10259                            line_height,
10260                            start_row..end_row,
10261                            &row_infos,
10262                            scroll_position,
10263                            &gutter_dimensions,
10264                            &gutter_hitbox,
10265                            &display_hunks,
10266                            &snapshot,
10267                            &mut breakpoint_rows,
10268                            window,
10269                            cx,
10270                        )
10271                    } else {
10272                        Vec::new()
10273                    };
10274
10275                    let show_breakpoints = snapshot
10276                        .show_breakpoints
10277                        .unwrap_or(gutter_settings.breakpoints);
10278                    let breakpoints = if show_breakpoints {
10279                        self.layout_breakpoints(
10280                            line_height,
10281                            start_row..end_row,
10282                            scroll_position,
10283                            &gutter_dimensions,
10284                            &gutter_hitbox,
10285                            &display_hunks,
10286                            &snapshot,
10287                            breakpoint_rows,
10288                            &row_infos,
10289                            window,
10290                            cx,
10291                        )
10292                    } else {
10293                        Vec::new()
10294                    };
10295
10296                    self.layout_signature_help(
10297                        &hitbox,
10298                        content_origin,
10299                        scroll_pixel_position,
10300                        newest_selection_head,
10301                        start_row,
10302                        &line_layouts,
10303                        line_height,
10304                        em_width,
10305                        context_menu_layout,
10306                        window,
10307                        cx,
10308                    );
10309
10310                    if !cx.has_active_drag() {
10311                        self.layout_hover_popovers(
10312                            &snapshot,
10313                            &hitbox,
10314                            start_row..end_row,
10315                            content_origin,
10316                            scroll_pixel_position,
10317                            &line_layouts,
10318                            line_height,
10319                            em_width,
10320                            context_menu_layout,
10321                            window,
10322                            cx,
10323                        );
10324
10325                        self.layout_blame_popover(&snapshot, &hitbox, line_height, window, cx);
10326                    }
10327
10328                    let mouse_context_menu = self.layout_mouse_context_menu(
10329                        &snapshot,
10330                        start_row..end_row,
10331                        content_origin,
10332                        window,
10333                        cx,
10334                    );
10335
10336                    window.with_element_namespace("crease_toggles", |window| {
10337                        self.prepaint_crease_toggles(
10338                            &mut crease_toggles,
10339                            line_height,
10340                            &gutter_dimensions,
10341                            gutter_settings,
10342                            scroll_pixel_position,
10343                            &gutter_hitbox,
10344                            window,
10345                            cx,
10346                        )
10347                    });
10348
10349                    window.with_element_namespace("expand_toggles", |window| {
10350                        self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
10351                    });
10352
10353                    let wrap_guides = self.layout_wrap_guides(
10354                        em_advance,
10355                        scroll_position,
10356                        content_origin,
10357                        scrollbars_layout.as_ref(),
10358                        vertical_scrollbar_width,
10359                        &hitbox,
10360                        window,
10361                        cx,
10362                    );
10363
10364                    let minimap = window.with_element_namespace("minimap", |window| {
10365                        self.layout_minimap(
10366                            &snapshot,
10367                            minimap_width,
10368                            scroll_position,
10369                            &scrollbar_layout_information,
10370                            scrollbars_layout.as_ref(),
10371                            window,
10372                            cx,
10373                        )
10374                    });
10375
10376                    let invisible_symbol_font_size = font_size / 2.;
10377                    let whitespace_map = &self
10378                        .editor
10379                        .read(cx)
10380                        .buffer
10381                        .read(cx)
10382                        .language_settings(cx)
10383                        .whitespace_map;
10384
10385                    let tab_char = whitespace_map.tab.clone();
10386                    let tab_len = tab_char.len();
10387                    let tab_invisible = window.text_system().shape_line(
10388                        tab_char,
10389                        invisible_symbol_font_size,
10390                        &[TextRun {
10391                            len: tab_len,
10392                            font: self.style.text.font(),
10393                            color: cx.theme().colors().editor_invisible,
10394                            ..Default::default()
10395                        }],
10396                        None,
10397                    );
10398
10399                    let space_char = whitespace_map.space.clone();
10400                    let space_len = space_char.len();
10401                    let space_invisible = window.text_system().shape_line(
10402                        space_char,
10403                        invisible_symbol_font_size,
10404                        &[TextRun {
10405                            len: space_len,
10406                            font: self.style.text.font(),
10407                            color: cx.theme().colors().editor_invisible,
10408                            ..Default::default()
10409                        }],
10410                        None,
10411                    );
10412
10413                    let mode = snapshot.mode.clone();
10414
10415                    let (diff_hunk_controls, diff_hunk_control_bounds) = if is_read_only {
10416                        (vec![], vec![])
10417                    } else {
10418                        self.layout_diff_hunk_controls(
10419                            start_row..end_row,
10420                            &row_infos,
10421                            &text_hitbox,
10422                            newest_selection_head,
10423                            line_height,
10424                            right_margin,
10425                            scroll_pixel_position,
10426                            &display_hunks,
10427                            &highlighted_rows,
10428                            self.editor.clone(),
10429                            window,
10430                            cx,
10431                        )
10432                    };
10433
10434                    let position_map = Rc::new(PositionMap {
10435                        size: bounds.size,
10436                        visible_row_range,
10437                        scroll_position,
10438                        scroll_pixel_position,
10439                        scroll_max,
10440                        line_layouts,
10441                        line_height,
10442                        em_width,
10443                        em_advance,
10444                        snapshot,
10445                        text_align: self.style.text.text_align,
10446                        content_width: text_hitbox.size.width,
10447                        gutter_hitbox: gutter_hitbox.clone(),
10448                        text_hitbox: text_hitbox.clone(),
10449                        inline_blame_bounds: inline_blame_layout
10450                            .as_ref()
10451                            .map(|layout| (layout.bounds, layout.buffer_id, layout.entry.clone())),
10452                        display_hunks: display_hunks.clone(),
10453                        diff_hunk_control_bounds,
10454                    });
10455
10456                    self.editor.update(cx, |editor, _| {
10457                        editor.last_position_map = Some(position_map.clone())
10458                    });
10459
10460                    EditorLayout {
10461                        mode,
10462                        position_map,
10463                        visible_display_row_range: start_row..end_row,
10464                        wrap_guides,
10465                        indent_guides,
10466                        hitbox,
10467                        gutter_hitbox,
10468                        display_hunks,
10469                        content_origin,
10470                        scrollbars_layout,
10471                        minimap,
10472                        active_rows,
10473                        highlighted_rows,
10474                        highlighted_ranges,
10475                        highlighted_gutter_ranges,
10476                        redacted_ranges,
10477                        document_colors,
10478                        line_elements,
10479                        line_numbers,
10480                        blamed_display_rows,
10481                        inline_diagnostics,
10482                        inline_blame_layout,
10483                        inline_code_actions,
10484                        blocks,
10485                        cursors,
10486                        visible_cursors,
10487                        selections,
10488                        edit_prediction_popover,
10489                        diff_hunk_controls,
10490                        mouse_context_menu,
10491                        test_indicators,
10492                        breakpoints,
10493                        crease_toggles,
10494                        crease_trailers,
10495                        tab_invisible,
10496                        space_invisible,
10497                        sticky_buffer_header,
10498                        sticky_headers,
10499                        expand_toggles,
10500                        text_align: self.style.text.text_align,
10501                        content_width: text_hitbox.size.width,
10502                    }
10503                })
10504            })
10505        })
10506    }
10507
10508    fn paint(
10509        &mut self,
10510        _: Option<&GlobalElementId>,
10511        _inspector_id: Option<&gpui::InspectorElementId>,
10512        bounds: Bounds<gpui::Pixels>,
10513        _: &mut Self::RequestLayoutState,
10514        layout: &mut Self::PrepaintState,
10515        window: &mut Window,
10516        cx: &mut App,
10517    ) {
10518        if !layout.mode.is_minimap() {
10519            let focus_handle = self.editor.focus_handle(cx);
10520            let key_context = self
10521                .editor
10522                .update(cx, |editor, cx| editor.key_context(window, cx));
10523
10524            window.set_key_context(key_context);
10525            window.handle_input(
10526                &focus_handle,
10527                ElementInputHandler::new(bounds, self.editor.clone()),
10528                cx,
10529            );
10530            self.register_actions(window, cx);
10531            self.register_key_listeners(window, cx, layout);
10532        }
10533
10534        let text_style = TextStyleRefinement {
10535            font_size: Some(self.style.text.font_size),
10536            line_height: Some(self.style.text.line_height),
10537            ..Default::default()
10538        };
10539        let rem_size = self.rem_size(cx);
10540        window.with_rem_size(rem_size, |window| {
10541            window.with_text_style(Some(text_style), |window| {
10542                window.with_content_mask(Some(ContentMask { bounds }), |window| {
10543                    self.paint_mouse_listeners(layout, window, cx);
10544                    self.paint_background(layout, window, cx);
10545                    self.paint_indent_guides(layout, window, cx);
10546
10547                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
10548                        self.paint_blamed_display_rows(layout, window, cx);
10549                        self.paint_line_numbers(layout, window, cx);
10550                    }
10551
10552                    self.paint_text(layout, window, cx);
10553
10554                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
10555                        self.paint_gutter_highlights(layout, window, cx);
10556                        self.paint_gutter_indicators(layout, window, cx);
10557                    }
10558
10559                    if !layout.blocks.is_empty() {
10560                        window.with_element_namespace("blocks", |window| {
10561                            self.paint_blocks(layout, window, cx);
10562                        });
10563                    }
10564
10565                    window.with_element_namespace("blocks", |window| {
10566                        if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
10567                            sticky_header.paint(window, cx)
10568                        }
10569                    });
10570
10571                    self.paint_sticky_headers(layout, window, cx);
10572                    self.paint_minimap(layout, window, cx);
10573                    self.paint_scrollbars(layout, window, cx);
10574                    self.paint_edit_prediction_popover(layout, window, cx);
10575                    self.paint_mouse_context_menu(layout, window, cx);
10576                });
10577            })
10578        })
10579    }
10580}
10581
10582pub(super) fn gutter_bounds(
10583    editor_bounds: Bounds<Pixels>,
10584    gutter_dimensions: GutterDimensions,
10585) -> Bounds<Pixels> {
10586    Bounds {
10587        origin: editor_bounds.origin,
10588        size: size(gutter_dimensions.width, editor_bounds.size.height),
10589    }
10590}
10591
10592#[derive(Clone, Copy)]
10593struct ContextMenuLayout {
10594    y_flipped: bool,
10595    bounds: Bounds<Pixels>,
10596}
10597
10598/// Holds information required for layouting the editor scrollbars.
10599struct ScrollbarLayoutInformation {
10600    /// The bounds of the editor area (excluding the content offset).
10601    editor_bounds: Bounds<Pixels>,
10602    /// The available range to scroll within the document.
10603    scroll_range: Size<Pixels>,
10604    /// The space available for one glyph in the editor.
10605    glyph_grid_cell: Size<Pixels>,
10606}
10607
10608impl ScrollbarLayoutInformation {
10609    pub fn new(
10610        editor_bounds: Bounds<Pixels>,
10611        glyph_grid_cell: Size<Pixels>,
10612        document_size: Size<Pixels>,
10613        longest_line_blame_width: Pixels,
10614        settings: &EditorSettings,
10615    ) -> Self {
10616        let vertical_overscroll = match settings.scroll_beyond_last_line {
10617            ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
10618            ScrollBeyondLastLine::Off => glyph_grid_cell.height,
10619            ScrollBeyondLastLine::VerticalScrollMargin => {
10620                (1.0 + settings.vertical_scroll_margin) as f32 * glyph_grid_cell.height
10621            }
10622        };
10623
10624        let overscroll = size(longest_line_blame_width, vertical_overscroll);
10625
10626        ScrollbarLayoutInformation {
10627            editor_bounds,
10628            scroll_range: document_size + overscroll,
10629            glyph_grid_cell,
10630        }
10631    }
10632}
10633
10634impl IntoElement for EditorElement {
10635    type Element = Self;
10636
10637    fn into_element(self) -> Self::Element {
10638        self
10639    }
10640}
10641
10642pub struct EditorLayout {
10643    position_map: Rc<PositionMap>,
10644    hitbox: Hitbox,
10645    gutter_hitbox: Hitbox,
10646    content_origin: gpui::Point<Pixels>,
10647    scrollbars_layout: Option<EditorScrollbars>,
10648    minimap: Option<MinimapLayout>,
10649    mode: EditorMode,
10650    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
10651    indent_guides: Option<Vec<IndentGuideLayout>>,
10652    visible_display_row_range: Range<DisplayRow>,
10653    active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
10654    highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
10655    line_elements: SmallVec<[AnyElement; 1]>,
10656    line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
10657    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
10658    blamed_display_rows: Option<Vec<AnyElement>>,
10659    inline_diagnostics: HashMap<DisplayRow, AnyElement>,
10660    inline_blame_layout: Option<InlineBlameLayout>,
10661    inline_code_actions: Option<AnyElement>,
10662    blocks: Vec<BlockLayout>,
10663    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
10664    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
10665    redacted_ranges: Vec<Range<DisplayPoint>>,
10666    cursors: Vec<(DisplayPoint, Hsla)>,
10667    visible_cursors: Vec<CursorLayout>,
10668    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
10669    test_indicators: Vec<AnyElement>,
10670    breakpoints: Vec<AnyElement>,
10671    crease_toggles: Vec<Option<AnyElement>>,
10672    expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
10673    diff_hunk_controls: Vec<AnyElement>,
10674    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
10675    edit_prediction_popover: Option<AnyElement>,
10676    mouse_context_menu: Option<AnyElement>,
10677    tab_invisible: ShapedLine,
10678    space_invisible: ShapedLine,
10679    sticky_buffer_header: Option<AnyElement>,
10680    sticky_headers: Option<StickyHeaders>,
10681    document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
10682    text_align: TextAlign,
10683    content_width: Pixels,
10684}
10685
10686struct StickyHeaders {
10687    lines: Vec<StickyHeaderLine>,
10688    gutter_background: Hsla,
10689    content_background: Hsla,
10690    gutter_right_padding: Pixels,
10691}
10692
10693struct StickyHeaderLine {
10694    row: DisplayRow,
10695    offset: Pixels,
10696    line: LineWithInvisibles,
10697    line_number: Option<ShapedLine>,
10698    elements: SmallVec<[AnyElement; 1]>,
10699    available_text_width: Pixels,
10700    target_anchor: Anchor,
10701    hitbox: Hitbox,
10702}
10703
10704impl EditorLayout {
10705    fn line_end_overshoot(&self) -> Pixels {
10706        0.15 * self.position_map.line_height
10707    }
10708}
10709
10710impl StickyHeaders {
10711    fn paint(
10712        &mut self,
10713        layout: &mut EditorLayout,
10714        whitespace_setting: ShowWhitespaceSetting,
10715        window: &mut Window,
10716        cx: &mut App,
10717    ) {
10718        let line_height = layout.position_map.line_height;
10719
10720        for line in self.lines.iter_mut().rev() {
10721            window.paint_layer(
10722                Bounds::new(
10723                    layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
10724                    size(line.hitbox.size.width, line_height),
10725                ),
10726                |window| {
10727                    let gutter_bounds = Bounds::new(
10728                        layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
10729                        size(layout.gutter_hitbox.size.width, line_height),
10730                    );
10731                    window.paint_quad(fill(gutter_bounds, self.gutter_background));
10732
10733                    let text_bounds = Bounds::new(
10734                        layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset),
10735                        size(line.available_text_width, line_height),
10736                    );
10737                    window.paint_quad(fill(text_bounds, self.content_background));
10738
10739                    if line.hitbox.is_hovered(window) {
10740                        let hover_overlay = cx.theme().colors().panel_overlay_hover;
10741                        window.paint_quad(fill(gutter_bounds, hover_overlay));
10742                        window.paint_quad(fill(text_bounds, hover_overlay));
10743                    }
10744
10745                    line.paint(
10746                        layout,
10747                        self.gutter_right_padding,
10748                        line.available_text_width,
10749                        layout.content_origin,
10750                        line_height,
10751                        whitespace_setting,
10752                        window,
10753                        cx,
10754                    );
10755                },
10756            );
10757
10758            window.set_cursor_style(CursorStyle::PointingHand, &line.hitbox);
10759        }
10760    }
10761}
10762
10763impl StickyHeaderLine {
10764    fn new(
10765        row: DisplayRow,
10766        offset: Pixels,
10767        mut line: LineWithInvisibles,
10768        line_number: Option<ShapedLine>,
10769        target_anchor: Anchor,
10770        line_height: Pixels,
10771        scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
10772        content_origin: gpui::Point<Pixels>,
10773        gutter_hitbox: &Hitbox,
10774        text_hitbox: &Hitbox,
10775        window: &mut Window,
10776        cx: &mut App,
10777    ) -> Self {
10778        let mut elements = SmallVec::<[AnyElement; 1]>::new();
10779        line.prepaint_with_custom_offset(
10780            line_height,
10781            scroll_pixel_position,
10782            content_origin,
10783            offset,
10784            &mut elements,
10785            window,
10786            cx,
10787        );
10788
10789        let hitbox_bounds = Bounds::new(
10790            gutter_hitbox.origin + point(Pixels::ZERO, offset),
10791            size(text_hitbox.right() - gutter_hitbox.left(), line_height),
10792        );
10793        let available_text_width =
10794            (hitbox_bounds.size.width - gutter_hitbox.size.width).max(Pixels::ZERO);
10795
10796        Self {
10797            row,
10798            offset,
10799            line,
10800            line_number,
10801            elements,
10802            available_text_width,
10803            target_anchor,
10804            hitbox: window.insert_hitbox(hitbox_bounds, HitboxBehavior::BlockMouseExceptScroll),
10805        }
10806    }
10807
10808    fn paint(
10809        &mut self,
10810        layout: &EditorLayout,
10811        gutter_right_padding: Pixels,
10812        available_text_width: Pixels,
10813        content_origin: gpui::Point<Pixels>,
10814        line_height: Pixels,
10815        whitespace_setting: ShowWhitespaceSetting,
10816        window: &mut Window,
10817        cx: &mut App,
10818    ) {
10819        window.with_content_mask(
10820            Some(ContentMask {
10821                bounds: Bounds::new(
10822                    layout.position_map.text_hitbox.bounds.origin
10823                        + point(Pixels::ZERO, self.offset),
10824                    size(available_text_width, line_height),
10825                ),
10826            }),
10827            |window| {
10828                self.line.draw_with_custom_offset(
10829                    layout,
10830                    self.row,
10831                    content_origin,
10832                    self.offset,
10833                    whitespace_setting,
10834                    &[],
10835                    window,
10836                    cx,
10837                );
10838                for element in &mut self.elements {
10839                    element.paint(window, cx);
10840                }
10841            },
10842        );
10843
10844        if let Some(line_number) = &self.line_number {
10845            let gutter_origin = layout.gutter_hitbox.origin + point(Pixels::ZERO, self.offset);
10846            let gutter_width = layout.gutter_hitbox.size.width;
10847            let origin = point(
10848                gutter_origin.x + gutter_width - gutter_right_padding - line_number.width,
10849                gutter_origin.y,
10850            );
10851            line_number
10852                .paint(origin, line_height, TextAlign::Left, None, window, cx)
10853                .log_err();
10854        }
10855    }
10856}
10857
10858#[derive(Debug)]
10859struct LineNumberSegment {
10860    shaped_line: ShapedLine,
10861    hitbox: Option<Hitbox>,
10862}
10863
10864#[derive(Debug)]
10865struct LineNumberLayout {
10866    segments: SmallVec<[LineNumberSegment; 1]>,
10867}
10868
10869struct ColoredRange<T> {
10870    start: T,
10871    end: T,
10872    color: Hsla,
10873}
10874
10875impl Along for ScrollbarAxes {
10876    type Unit = bool;
10877
10878    fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
10879        match axis {
10880            ScrollbarAxis::Horizontal => self.horizontal,
10881            ScrollbarAxis::Vertical => self.vertical,
10882        }
10883    }
10884
10885    fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
10886        match axis {
10887            ScrollbarAxis::Horizontal => ScrollbarAxes {
10888                horizontal: f(self.horizontal),
10889                vertical: self.vertical,
10890            },
10891            ScrollbarAxis::Vertical => ScrollbarAxes {
10892                horizontal: self.horizontal,
10893                vertical: f(self.vertical),
10894            },
10895        }
10896    }
10897}
10898
10899#[derive(Clone)]
10900struct EditorScrollbars {
10901    pub vertical: Option<ScrollbarLayout>,
10902    pub horizontal: Option<ScrollbarLayout>,
10903    pub visible: bool,
10904}
10905
10906impl EditorScrollbars {
10907    pub fn from_scrollbar_axes(
10908        show_scrollbar: ScrollbarAxes,
10909        layout_information: &ScrollbarLayoutInformation,
10910        content_offset: gpui::Point<Pixels>,
10911        scroll_position: gpui::Point<f64>,
10912        scrollbar_width: Pixels,
10913        right_margin: Pixels,
10914        editor_width: Pixels,
10915        show_scrollbars: bool,
10916        scrollbar_state: Option<&ActiveScrollbarState>,
10917        window: &mut Window,
10918    ) -> Self {
10919        let ScrollbarLayoutInformation {
10920            editor_bounds,
10921            scroll_range,
10922            glyph_grid_cell,
10923        } = layout_information;
10924
10925        let viewport_size = size(editor_width, editor_bounds.size.height);
10926
10927        let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
10928            ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
10929                Corner::BottomLeft,
10930                editor_bounds.bottom_left(),
10931                size(
10932                    // The horizontal viewport size differs from the space available for the
10933                    // horizontal scrollbar, so we have to manually stitch it together here.
10934                    editor_bounds.size.width - right_margin,
10935                    scrollbar_width,
10936                ),
10937            ),
10938            ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
10939                Corner::TopRight,
10940                editor_bounds.top_right(),
10941                size(scrollbar_width, viewport_size.height),
10942            ),
10943        };
10944
10945        let mut create_scrollbar_layout = |axis| {
10946            let viewport_size = viewport_size.along(axis);
10947            let scroll_range = scroll_range.along(axis);
10948
10949            // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
10950            (show_scrollbar.along(axis)
10951                && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
10952                .then(|| {
10953                    ScrollbarLayout::new(
10954                        window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
10955                        viewport_size,
10956                        scroll_range,
10957                        glyph_grid_cell.along(axis),
10958                        content_offset.along(axis),
10959                        scroll_position.along(axis),
10960                        show_scrollbars,
10961                        axis,
10962                    )
10963                    .with_thumb_state(
10964                        scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
10965                    )
10966                })
10967        };
10968
10969        Self {
10970            vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
10971            horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
10972            visible: show_scrollbars,
10973        }
10974    }
10975
10976    pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
10977        [
10978            (&self.vertical, ScrollbarAxis::Vertical),
10979            (&self.horizontal, ScrollbarAxis::Horizontal),
10980        ]
10981        .into_iter()
10982        .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
10983    }
10984
10985    /// Returns the currently hovered scrollbar axis, if any.
10986    pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
10987        self.iter_scrollbars()
10988            .find(|s| s.0.hitbox.is_hovered(window))
10989    }
10990}
10991
10992#[derive(Clone)]
10993struct ScrollbarLayout {
10994    hitbox: Hitbox,
10995    visible_range: Range<ScrollOffset>,
10996    text_unit_size: Pixels,
10997    thumb_bounds: Option<Bounds<Pixels>>,
10998    thumb_state: ScrollbarThumbState,
10999}
11000
11001impl ScrollbarLayout {
11002    const BORDER_WIDTH: Pixels = px(1.0);
11003    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
11004    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
11005    const MIN_THUMB_SIZE: Pixels = px(25.0);
11006
11007    fn new(
11008        scrollbar_track_hitbox: Hitbox,
11009        viewport_size: Pixels,
11010        scroll_range: Pixels,
11011        glyph_space: Pixels,
11012        content_offset: Pixels,
11013        scroll_position: ScrollOffset,
11014        show_thumb: bool,
11015        axis: ScrollbarAxis,
11016    ) -> Self {
11017        let track_bounds = scrollbar_track_hitbox.bounds;
11018        // The length of the track available to the scrollbar thumb. We deliberately
11019        // exclude the content size here so that the thumb aligns with the content.
11020        let track_length = track_bounds.size.along(axis) - content_offset;
11021
11022        Self::new_with_hitbox_and_track_length(
11023            scrollbar_track_hitbox,
11024            track_length,
11025            viewport_size,
11026            scroll_range.into(),
11027            glyph_space,
11028            content_offset.into(),
11029            scroll_position,
11030            show_thumb,
11031            axis,
11032        )
11033    }
11034
11035    fn for_minimap(
11036        minimap_track_hitbox: Hitbox,
11037        visible_lines: f64,
11038        total_editor_lines: f64,
11039        minimap_line_height: Pixels,
11040        scroll_position: ScrollOffset,
11041        minimap_scroll_top: ScrollOffset,
11042        show_thumb: bool,
11043    ) -> Self {
11044        // The scrollbar thumb size is calculated as
11045        // (visible_content/total_content) Γ— scrollbar_track_length.
11046        //
11047        // For the minimap's thumb layout, we leverage this by setting the
11048        // scrollbar track length to the entire document size (using minimap line
11049        // height). This creates a thumb that exactly represents the editor
11050        // viewport scaled to minimap proportions.
11051        //
11052        // We adjust the thumb position relative to `minimap_scroll_top` to
11053        // accommodate for the deliberately oversized track.
11054        //
11055        // This approach ensures that the minimap thumb accurately reflects the
11056        // editor's current scroll position whilst nicely synchronizing the minimap
11057        // thumb and scrollbar thumb.
11058        let scroll_range = total_editor_lines * f64::from(minimap_line_height);
11059        let viewport_size = visible_lines * f64::from(minimap_line_height);
11060
11061        let track_top_offset = -minimap_scroll_top * f64::from(minimap_line_height);
11062
11063        Self::new_with_hitbox_and_track_length(
11064            minimap_track_hitbox,
11065            Pixels::from(scroll_range),
11066            Pixels::from(viewport_size),
11067            scroll_range,
11068            minimap_line_height,
11069            track_top_offset,
11070            scroll_position,
11071            show_thumb,
11072            ScrollbarAxis::Vertical,
11073        )
11074    }
11075
11076    fn new_with_hitbox_and_track_length(
11077        scrollbar_track_hitbox: Hitbox,
11078        track_length: Pixels,
11079        viewport_size: Pixels,
11080        scroll_range: f64,
11081        glyph_space: Pixels,
11082        content_offset: ScrollOffset,
11083        scroll_position: ScrollOffset,
11084        show_thumb: bool,
11085        axis: ScrollbarAxis,
11086    ) -> Self {
11087        let text_units_per_page = viewport_size.to_f64() / glyph_space.to_f64();
11088        let visible_range = scroll_position..scroll_position + text_units_per_page;
11089        let total_text_units = scroll_range / glyph_space.to_f64();
11090
11091        let thumb_percentage = text_units_per_page / total_text_units;
11092        let thumb_size = Pixels::from(ScrollOffset::from(track_length) * thumb_percentage)
11093            .max(ScrollbarLayout::MIN_THUMB_SIZE)
11094            .min(track_length);
11095
11096        let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
11097
11098        let content_larger_than_viewport = text_unit_divisor > 0.;
11099
11100        let text_unit_size = if content_larger_than_viewport {
11101            Pixels::from(ScrollOffset::from(track_length - thumb_size) / text_unit_divisor)
11102        } else {
11103            glyph_space
11104        };
11105
11106        let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
11107            Self::thumb_bounds(
11108                &scrollbar_track_hitbox,
11109                content_offset,
11110                visible_range.start,
11111                text_unit_size,
11112                thumb_size,
11113                axis,
11114            )
11115        });
11116
11117        ScrollbarLayout {
11118            hitbox: scrollbar_track_hitbox,
11119            visible_range,
11120            text_unit_size,
11121            thumb_bounds,
11122            thumb_state: Default::default(),
11123        }
11124    }
11125
11126    fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
11127        if let Some(thumb_state) = thumb_state {
11128            Self {
11129                thumb_state,
11130                ..self
11131            }
11132        } else {
11133            self
11134        }
11135    }
11136
11137    fn thumb_bounds(
11138        scrollbar_track: &Hitbox,
11139        content_offset: f64,
11140        visible_range_start: f64,
11141        text_unit_size: Pixels,
11142        thumb_size: Pixels,
11143        axis: ScrollbarAxis,
11144    ) -> Bounds<Pixels> {
11145        let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
11146            origin
11147                + Pixels::from(
11148                    content_offset + visible_range_start * ScrollOffset::from(text_unit_size),
11149                )
11150        });
11151        Bounds::new(
11152            thumb_origin,
11153            scrollbar_track.size.apply_along(axis, |_| thumb_size),
11154        )
11155    }
11156
11157    fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
11158        self.thumb_bounds
11159            .is_some_and(|bounds| bounds.contains(position))
11160    }
11161
11162    fn marker_quads_for_ranges(
11163        &self,
11164        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
11165        column: Option<usize>,
11166    ) -> Vec<PaintQuad> {
11167        struct MinMax {
11168            min: Pixels,
11169            max: Pixels,
11170        }
11171        let (x_range, height_limit) = if let Some(column) = column {
11172            let column_width = ((self.hitbox.size.width - Self::BORDER_WIDTH) / 3.0).floor();
11173            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
11174            let end = start + column_width;
11175            (
11176                Range { start, end },
11177                MinMax {
11178                    min: Self::MIN_MARKER_HEIGHT,
11179                    max: px(f32::MAX),
11180                },
11181            )
11182        } else {
11183            (
11184                Range {
11185                    start: Self::BORDER_WIDTH,
11186                    end: self.hitbox.size.width,
11187                },
11188                MinMax {
11189                    min: Self::LINE_MARKER_HEIGHT,
11190                    max: Self::LINE_MARKER_HEIGHT,
11191                },
11192            )
11193        };
11194
11195        let row_to_y = |row: DisplayRow| row.as_f64() as f32 * self.text_unit_size;
11196        let mut pixel_ranges = row_ranges
11197            .into_iter()
11198            .map(|range| {
11199                let start_y = row_to_y(range.start);
11200                let end_y = row_to_y(range.end)
11201                    + self
11202                        .text_unit_size
11203                        .max(height_limit.min)
11204                        .min(height_limit.max);
11205                ColoredRange {
11206                    start: start_y,
11207                    end: end_y,
11208                    color: range.color,
11209                }
11210            })
11211            .peekable();
11212
11213        let mut quads = Vec::new();
11214        while let Some(mut pixel_range) = pixel_ranges.next() {
11215            while let Some(next_pixel_range) = pixel_ranges.peek() {
11216                if pixel_range.end >= next_pixel_range.start - px(1.0)
11217                    && pixel_range.color == next_pixel_range.color
11218                {
11219                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
11220                    pixel_ranges.next();
11221                } else {
11222                    break;
11223                }
11224            }
11225
11226            let bounds = Bounds::from_corners(
11227                point(x_range.start, pixel_range.start),
11228                point(x_range.end, pixel_range.end),
11229            );
11230            quads.push(quad(
11231                bounds,
11232                Corners::default(),
11233                pixel_range.color,
11234                Edges::default(),
11235                Hsla::transparent_black(),
11236                BorderStyle::default(),
11237            ));
11238        }
11239
11240        quads
11241    }
11242}
11243
11244struct MinimapLayout {
11245    pub minimap: AnyElement,
11246    pub thumb_layout: ScrollbarLayout,
11247    pub minimap_scroll_top: ScrollOffset,
11248    pub minimap_line_height: Pixels,
11249    pub thumb_border_style: MinimapThumbBorder,
11250    pub max_scroll_top: ScrollOffset,
11251}
11252
11253impl MinimapLayout {
11254    /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
11255    const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
11256    /// The minimap width as a percentage of the editor width.
11257    const MINIMAP_WIDTH_PCT: f32 = 0.15;
11258    /// Calculates the scroll top offset the minimap editor has to have based on the
11259    /// current scroll progress.
11260    fn calculate_minimap_top_offset(
11261        document_lines: f64,
11262        visible_editor_lines: f64,
11263        visible_minimap_lines: f64,
11264        scroll_position: f64,
11265    ) -> ScrollOffset {
11266        let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
11267        if non_visible_document_lines == 0. {
11268            0.
11269        } else {
11270            let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
11271            scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
11272        }
11273    }
11274}
11275
11276struct CreaseTrailerLayout {
11277    element: AnyElement,
11278    bounds: Bounds<Pixels>,
11279}
11280
11281pub(crate) struct PositionMap {
11282    pub size: Size<Pixels>,
11283    pub line_height: Pixels,
11284    pub scroll_position: gpui::Point<ScrollOffset>,
11285    pub scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11286    pub scroll_max: gpui::Point<ScrollOffset>,
11287    pub em_width: Pixels,
11288    pub em_advance: Pixels,
11289    pub visible_row_range: Range<DisplayRow>,
11290    pub line_layouts: Vec<LineWithInvisibles>,
11291    pub snapshot: EditorSnapshot,
11292    pub text_align: TextAlign,
11293    pub content_width: Pixels,
11294    pub text_hitbox: Hitbox,
11295    pub gutter_hitbox: Hitbox,
11296    pub inline_blame_bounds: Option<(Bounds<Pixels>, BufferId, BlameEntry)>,
11297    pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
11298    pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
11299}
11300
11301#[derive(Debug, Copy, Clone)]
11302pub struct PointForPosition {
11303    pub previous_valid: DisplayPoint,
11304    pub next_valid: DisplayPoint,
11305    pub exact_unclipped: DisplayPoint,
11306    pub column_overshoot_after_line_end: u32,
11307}
11308
11309impl PointForPosition {
11310    pub fn as_valid(&self) -> Option<DisplayPoint> {
11311        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
11312            Some(self.previous_valid)
11313        } else {
11314            None
11315        }
11316    }
11317
11318    pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
11319        let Some(valid_point) = self.as_valid() else {
11320            return false;
11321        };
11322        let range = selection.range();
11323
11324        let candidate_row = valid_point.row();
11325        let candidate_col = valid_point.column();
11326
11327        let start_row = range.start.row();
11328        let start_col = range.start.column();
11329        let end_row = range.end.row();
11330        let end_col = range.end.column();
11331
11332        if candidate_row < start_row || candidate_row > end_row {
11333            false
11334        } else if start_row == end_row {
11335            candidate_col >= start_col && candidate_col < end_col
11336        } else if candidate_row == start_row {
11337            candidate_col >= start_col
11338        } else if candidate_row == end_row {
11339            candidate_col < end_col
11340        } else {
11341            true
11342        }
11343    }
11344}
11345
11346impl PositionMap {
11347    pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
11348        let text_bounds = self.text_hitbox.bounds;
11349        let scroll_position = self.snapshot.scroll_position();
11350        let position = position - text_bounds.origin;
11351        let y = position.y.max(px(0.)).min(self.size.height);
11352        let x = position.x + (scroll_position.x as f32 * self.em_advance);
11353        let row = ((y / self.line_height) as f64 + scroll_position.y) as u32;
11354
11355        let (column, x_overshoot_after_line_end) = if let Some(line) = self
11356            .line_layouts
11357            .get(row as usize - scroll_position.y as usize)
11358        {
11359            let alignment_offset = line.alignment_offset(self.text_align, self.content_width);
11360            let x_relative_to_text = x - alignment_offset;
11361            if let Some(ix) = line.index_for_x(x_relative_to_text) {
11362                (ix as u32, px(0.))
11363            } else {
11364                (line.len as u32, px(0.).max(x_relative_to_text - line.width))
11365            }
11366        } else {
11367            (0, x)
11368        };
11369
11370        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
11371        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
11372        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
11373
11374        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
11375        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
11376        PointForPosition {
11377            previous_valid,
11378            next_valid,
11379            exact_unclipped,
11380            column_overshoot_after_line_end,
11381        }
11382    }
11383}
11384
11385struct BlockLayout {
11386    id: BlockId,
11387    x_offset: Pixels,
11388    row: Option<DisplayRow>,
11389    element: AnyElement,
11390    available_space: Size<AvailableSpace>,
11391    style: BlockStyle,
11392    overlaps_gutter: bool,
11393    is_buffer_header: bool,
11394}
11395
11396pub fn layout_line(
11397    row: DisplayRow,
11398    snapshot: &EditorSnapshot,
11399    style: &EditorStyle,
11400    text_width: Pixels,
11401    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
11402    window: &mut Window,
11403    cx: &mut App,
11404) -> LineWithInvisibles {
11405    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
11406    LineWithInvisibles::from_chunks(
11407        chunks,
11408        style,
11409        MAX_LINE_LEN,
11410        1,
11411        &snapshot.mode,
11412        text_width,
11413        is_row_soft_wrapped,
11414        &[],
11415        window,
11416        cx,
11417    )
11418    .pop()
11419    .unwrap()
11420}
11421
11422#[derive(Debug)]
11423pub struct IndentGuideLayout {
11424    origin: gpui::Point<Pixels>,
11425    length: Pixels,
11426    single_indent_width: Pixels,
11427    depth: u32,
11428    active: bool,
11429    settings: IndentGuideSettings,
11430}
11431
11432pub struct CursorLayout {
11433    origin: gpui::Point<Pixels>,
11434    block_width: Pixels,
11435    line_height: Pixels,
11436    color: Hsla,
11437    shape: CursorShape,
11438    block_text: Option<ShapedLine>,
11439    cursor_name: Option<AnyElement>,
11440}
11441
11442#[derive(Debug)]
11443pub struct CursorName {
11444    string: SharedString,
11445    color: Hsla,
11446    is_top_row: bool,
11447}
11448
11449impl CursorLayout {
11450    pub fn new(
11451        origin: gpui::Point<Pixels>,
11452        block_width: Pixels,
11453        line_height: Pixels,
11454        color: Hsla,
11455        shape: CursorShape,
11456        block_text: Option<ShapedLine>,
11457    ) -> CursorLayout {
11458        CursorLayout {
11459            origin,
11460            block_width,
11461            line_height,
11462            color,
11463            shape,
11464            block_text,
11465            cursor_name: None,
11466        }
11467    }
11468
11469    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
11470        Bounds {
11471            origin: self.origin + origin,
11472            size: size(self.block_width, self.line_height),
11473        }
11474    }
11475
11476    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
11477        match self.shape {
11478            CursorShape::Bar => Bounds {
11479                origin: self.origin + origin,
11480                size: size(px(2.0), self.line_height),
11481            },
11482            CursorShape::Block | CursorShape::Hollow => Bounds {
11483                origin: self.origin + origin,
11484                size: size(self.block_width, self.line_height),
11485            },
11486            CursorShape::Underline => Bounds {
11487                origin: self.origin
11488                    + origin
11489                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
11490                size: size(self.block_width, px(2.0)),
11491            },
11492        }
11493    }
11494
11495    pub fn layout(
11496        &mut self,
11497        origin: gpui::Point<Pixels>,
11498        cursor_name: Option<CursorName>,
11499        window: &mut Window,
11500        cx: &mut App,
11501    ) {
11502        if let Some(cursor_name) = cursor_name {
11503            let bounds = self.bounds(origin);
11504            let text_size = self.line_height / 1.5;
11505
11506            let name_origin = if cursor_name.is_top_row {
11507                point(bounds.right() - px(1.), bounds.top())
11508            } else {
11509                match self.shape {
11510                    CursorShape::Bar => point(
11511                        bounds.right() - px(2.),
11512                        bounds.top() - text_size / 2. - px(1.),
11513                    ),
11514                    _ => point(
11515                        bounds.right() - px(1.),
11516                        bounds.top() - text_size / 2. - px(1.),
11517                    ),
11518                }
11519            };
11520            let mut name_element = div()
11521                .bg(self.color)
11522                .text_size(text_size)
11523                .px_0p5()
11524                .line_height(text_size + px(2.))
11525                .text_color(cursor_name.color)
11526                .child(cursor_name.string)
11527                .into_any_element();
11528
11529            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
11530
11531            self.cursor_name = Some(name_element);
11532        }
11533    }
11534
11535    pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
11536        let bounds = self.bounds(origin);
11537
11538        //Draw background or border quad
11539        let cursor = if matches!(self.shape, CursorShape::Hollow) {
11540            outline(bounds, self.color, BorderStyle::Solid)
11541        } else {
11542            fill(bounds, self.color)
11543        };
11544
11545        if let Some(name) = &mut self.cursor_name {
11546            name.paint(window, cx);
11547        }
11548
11549        window.paint_quad(cursor);
11550
11551        if let Some(block_text) = &self.block_text {
11552            block_text
11553                .paint(
11554                    self.origin + origin,
11555                    self.line_height,
11556                    TextAlign::Left,
11557                    None,
11558                    window,
11559                    cx,
11560                )
11561                .log_err();
11562        }
11563    }
11564
11565    pub fn shape(&self) -> CursorShape {
11566        self.shape
11567    }
11568}
11569
11570#[derive(Debug)]
11571pub struct HighlightedRange {
11572    pub start_y: Pixels,
11573    pub line_height: Pixels,
11574    pub lines: Vec<HighlightedRangeLine>,
11575    pub color: Hsla,
11576    pub corner_radius: Pixels,
11577}
11578
11579#[derive(Debug)]
11580pub struct HighlightedRangeLine {
11581    pub start_x: Pixels,
11582    pub end_x: Pixels,
11583}
11584
11585impl HighlightedRange {
11586    pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
11587        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
11588            self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
11589            self.paint_lines(
11590                self.start_y + self.line_height,
11591                &self.lines[1..],
11592                fill,
11593                bounds,
11594                window,
11595            );
11596        } else {
11597            self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
11598        }
11599    }
11600
11601    fn paint_lines(
11602        &self,
11603        start_y: Pixels,
11604        lines: &[HighlightedRangeLine],
11605        fill: bool,
11606        _bounds: Bounds<Pixels>,
11607        window: &mut Window,
11608    ) {
11609        if lines.is_empty() {
11610            return;
11611        }
11612
11613        let first_line = lines.first().unwrap();
11614        let last_line = lines.last().unwrap();
11615
11616        let first_top_left = point(first_line.start_x, start_y);
11617        let first_top_right = point(first_line.end_x, start_y);
11618
11619        let curve_height = point(Pixels::ZERO, self.corner_radius);
11620        let curve_width = |start_x: Pixels, end_x: Pixels| {
11621            let max = (end_x - start_x) / 2.;
11622            let width = if max < self.corner_radius {
11623                max
11624            } else {
11625                self.corner_radius
11626            };
11627
11628            point(width, Pixels::ZERO)
11629        };
11630
11631        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
11632        let mut builder = if fill {
11633            gpui::PathBuilder::fill()
11634        } else {
11635            gpui::PathBuilder::stroke(px(1.))
11636        };
11637        builder.move_to(first_top_right - top_curve_width);
11638        builder.curve_to(first_top_right + curve_height, first_top_right);
11639
11640        let mut iter = lines.iter().enumerate().peekable();
11641        while let Some((ix, line)) = iter.next() {
11642            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
11643
11644            if let Some((_, next_line)) = iter.peek() {
11645                let next_top_right = point(next_line.end_x, bottom_right.y);
11646
11647                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
11648                    Ordering::Equal => {
11649                        builder.line_to(bottom_right);
11650                    }
11651                    Ordering::Less => {
11652                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
11653                        builder.line_to(bottom_right - curve_height);
11654                        if self.corner_radius > Pixels::ZERO {
11655                            builder.curve_to(bottom_right - curve_width, bottom_right);
11656                        }
11657                        builder.line_to(next_top_right + curve_width);
11658                        if self.corner_radius > Pixels::ZERO {
11659                            builder.curve_to(next_top_right + curve_height, next_top_right);
11660                        }
11661                    }
11662                    Ordering::Greater => {
11663                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
11664                        builder.line_to(bottom_right - curve_height);
11665                        if self.corner_radius > Pixels::ZERO {
11666                            builder.curve_to(bottom_right + curve_width, bottom_right);
11667                        }
11668                        builder.line_to(next_top_right - curve_width);
11669                        if self.corner_radius > Pixels::ZERO {
11670                            builder.curve_to(next_top_right + curve_height, next_top_right);
11671                        }
11672                    }
11673                }
11674            } else {
11675                let curve_width = curve_width(line.start_x, line.end_x);
11676                builder.line_to(bottom_right - curve_height);
11677                if self.corner_radius > Pixels::ZERO {
11678                    builder.curve_to(bottom_right - curve_width, bottom_right);
11679                }
11680
11681                let bottom_left = point(line.start_x, bottom_right.y);
11682                builder.line_to(bottom_left + curve_width);
11683                if self.corner_radius > Pixels::ZERO {
11684                    builder.curve_to(bottom_left - curve_height, bottom_left);
11685                }
11686            }
11687        }
11688
11689        if first_line.start_x > last_line.start_x {
11690            let curve_width = curve_width(last_line.start_x, first_line.start_x);
11691            let second_top_left = point(last_line.start_x, start_y + self.line_height);
11692            builder.line_to(second_top_left + curve_height);
11693            if self.corner_radius > Pixels::ZERO {
11694                builder.curve_to(second_top_left + curve_width, second_top_left);
11695            }
11696            let first_bottom_left = point(first_line.start_x, second_top_left.y);
11697            builder.line_to(first_bottom_left - curve_width);
11698            if self.corner_radius > Pixels::ZERO {
11699                builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
11700            }
11701        }
11702
11703        builder.line_to(first_top_left + curve_height);
11704        if self.corner_radius > Pixels::ZERO {
11705            builder.curve_to(first_top_left + top_curve_width, first_top_left);
11706        }
11707        builder.line_to(first_top_right - top_curve_width);
11708
11709        if let Ok(path) = builder.build() {
11710            window.paint_path(path, self.color);
11711        }
11712    }
11713}
11714
11715pub(crate) struct StickyHeader {
11716    pub item: language::OutlineItem<Anchor>,
11717    pub sticky_row: DisplayRow,
11718    pub start_point: Point,
11719    pub offset: ScrollOffset,
11720}
11721
11722enum CursorPopoverType {
11723    CodeContextMenu,
11724    EditPrediction,
11725}
11726
11727pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
11728    (delta.pow(1.2) / 100.0).min(px(3.0)).into()
11729}
11730
11731fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
11732    (delta.pow(1.2) / 300.0).into()
11733}
11734
11735pub fn register_action<T: Action>(
11736    editor: &Entity<Editor>,
11737    window: &mut Window,
11738    listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
11739) {
11740    let editor = editor.clone();
11741    window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
11742        let action = action.downcast_ref().unwrap();
11743        if phase == DispatchPhase::Bubble {
11744            editor.update(cx, |editor, cx| {
11745                listener(editor, action, window, cx);
11746            })
11747        }
11748    })
11749}
11750
11751fn compute_auto_height_layout(
11752    editor: &mut Editor,
11753    min_lines: usize,
11754    max_lines: Option<usize>,
11755    known_dimensions: Size<Option<Pixels>>,
11756    available_width: AvailableSpace,
11757    window: &mut Window,
11758    cx: &mut Context<Editor>,
11759) -> Option<Size<Pixels>> {
11760    let width = known_dimensions.width.or({
11761        if let AvailableSpace::Definite(available_width) = available_width {
11762            Some(available_width)
11763        } else {
11764            None
11765        }
11766    })?;
11767    if let Some(height) = known_dimensions.height {
11768        return Some(size(width, height));
11769    }
11770
11771    let style = editor.style.as_ref().unwrap();
11772    let font_id = window.text_system().resolve_font(&style.text.font());
11773    let font_size = style.text.font_size.to_pixels(window.rem_size());
11774    let line_height = style.text.line_height_in_pixels(window.rem_size());
11775    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
11776
11777    let mut snapshot = editor.snapshot(window, cx);
11778    let gutter_dimensions = snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
11779
11780    editor.gutter_dimensions = gutter_dimensions;
11781    let text_width = width - gutter_dimensions.width;
11782    let overscroll = size(em_width, px(0.));
11783
11784    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
11785    if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None)
11786        && editor.set_wrap_width(Some(editor_width), cx)
11787    {
11788        snapshot = editor.snapshot(window, cx);
11789    }
11790
11791    let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
11792
11793    let min_height = line_height * min_lines as f32;
11794    let content_height = scroll_height.max(min_height);
11795
11796    let final_height = if let Some(max_lines) = max_lines {
11797        let max_height = line_height * max_lines as f32;
11798        content_height.min(max_height)
11799    } else {
11800        content_height
11801    };
11802
11803    Some(size(width, final_height))
11804}
11805
11806#[cfg(test)]
11807mod tests {
11808    use super::*;
11809    use crate::{
11810        Editor, MultiBuffer, SelectionEffects,
11811        display_map::{BlockPlacement, BlockProperties},
11812        editor_tests::{init_test, update_test_language_settings},
11813    };
11814    use gpui::{TestAppContext, VisualTestContext};
11815    use language::language_settings;
11816    use log::info;
11817    use std::num::NonZeroU32;
11818    use util::test::sample_text;
11819
11820    #[gpui::test]
11821    async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
11822        init_test(cx, |_| {});
11823
11824        let window = cx.add_window(|window, cx| {
11825            let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
11826            let mut editor = Editor::new(
11827                EditorMode::AutoHeight {
11828                    min_lines: 1,
11829                    max_lines: None,
11830                },
11831                buffer,
11832                None,
11833                window,
11834                cx,
11835            );
11836            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
11837            editor
11838        });
11839        let cx = &mut VisualTestContext::from_window(*window, cx);
11840        let editor = window.root(cx).unwrap();
11841        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
11842
11843        for x in 1..=100 {
11844            let (_, state) = cx.draw(
11845                Default::default(),
11846                size(px(200. + 0.13 * x as f32), px(500.)),
11847                |_, _| EditorElement::new(&editor, style.clone()),
11848            );
11849
11850            assert!(
11851                state.position_map.scroll_max.x == 0.,
11852                "Soft wrapped editor should have no horizontal scrolling!"
11853            );
11854        }
11855    }
11856
11857    #[gpui::test]
11858    async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
11859        init_test(cx, |_| {});
11860
11861        let window = cx.add_window(|window, cx| {
11862            let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
11863            let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
11864            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
11865            editor
11866        });
11867        let cx = &mut VisualTestContext::from_window(*window, cx);
11868        let editor = window.root(cx).unwrap();
11869        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
11870
11871        for x in 1..=100 {
11872            let (_, state) = cx.draw(
11873                Default::default(),
11874                size(px(200. + 0.13 * x as f32), px(500.)),
11875                |_, _| EditorElement::new(&editor, style.clone()),
11876            );
11877
11878            assert!(
11879                state.position_map.scroll_max.x == 0.,
11880                "Soft wrapped editor should have no horizontal scrolling!"
11881            );
11882        }
11883    }
11884
11885    #[gpui::test]
11886    fn test_layout_line_numbers(cx: &mut TestAppContext) {
11887        init_test(cx, |_| {});
11888        let window = cx.add_window(|window, cx| {
11889            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
11890            Editor::new(EditorMode::full(), buffer, None, window, cx)
11891        });
11892
11893        let editor = window.root(cx).unwrap();
11894        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
11895        let line_height = window
11896            .update(cx, |_, window, _| {
11897                style.text.line_height_in_pixels(window.rem_size())
11898            })
11899            .unwrap();
11900        let element = EditorElement::new(&editor, style);
11901        let snapshot = window
11902            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
11903            .unwrap();
11904
11905        let layouts = cx
11906            .update_window(*window, |_, window, cx| {
11907                element.layout_line_numbers(
11908                    None,
11909                    GutterDimensions {
11910                        left_padding: Pixels::ZERO,
11911                        right_padding: Pixels::ZERO,
11912                        width: px(30.0),
11913                        margin: Pixels::ZERO,
11914                        git_blame_entries_width: None,
11915                    },
11916                    line_height,
11917                    gpui::Point::default(),
11918                    DisplayRow(0)..DisplayRow(6),
11919                    &(0..6)
11920                        .map(|row| RowInfo {
11921                            buffer_row: Some(row),
11922                            ..Default::default()
11923                        })
11924                        .collect::<Vec<_>>(),
11925                    &BTreeMap::default(),
11926                    Some(DisplayRow(0)),
11927                    &snapshot,
11928                    window,
11929                    cx,
11930                )
11931            })
11932            .unwrap();
11933        assert_eq!(layouts.len(), 6);
11934
11935        let relative_rows = window
11936            .update(cx, |editor, window, cx| {
11937                let snapshot = editor.snapshot(window, cx);
11938                snapshot.calculate_relative_line_numbers(
11939                    &(DisplayRow(0)..DisplayRow(6)),
11940                    DisplayRow(3),
11941                    false,
11942                )
11943            })
11944            .unwrap();
11945        assert_eq!(relative_rows[&DisplayRow(0)], 3);
11946        assert_eq!(relative_rows[&DisplayRow(1)], 2);
11947        assert_eq!(relative_rows[&DisplayRow(2)], 1);
11948        // current line has no relative number
11949        assert!(!relative_rows.contains_key(&DisplayRow(3)));
11950        assert_eq!(relative_rows[&DisplayRow(4)], 1);
11951        assert_eq!(relative_rows[&DisplayRow(5)], 2);
11952
11953        // works if cursor is before screen
11954        let relative_rows = window
11955            .update(cx, |editor, window, cx| {
11956                let snapshot = editor.snapshot(window, cx);
11957                snapshot.calculate_relative_line_numbers(
11958                    &(DisplayRow(3)..DisplayRow(6)),
11959                    DisplayRow(1),
11960                    false,
11961                )
11962            })
11963            .unwrap();
11964        assert_eq!(relative_rows.len(), 3);
11965        assert_eq!(relative_rows[&DisplayRow(3)], 2);
11966        assert_eq!(relative_rows[&DisplayRow(4)], 3);
11967        assert_eq!(relative_rows[&DisplayRow(5)], 4);
11968
11969        // works if cursor is after screen
11970        let relative_rows = window
11971            .update(cx, |editor, window, cx| {
11972                let snapshot = editor.snapshot(window, cx);
11973                snapshot.calculate_relative_line_numbers(
11974                    &(DisplayRow(0)..DisplayRow(3)),
11975                    DisplayRow(6),
11976                    false,
11977                )
11978            })
11979            .unwrap();
11980        assert_eq!(relative_rows.len(), 3);
11981        assert_eq!(relative_rows[&DisplayRow(0)], 5);
11982        assert_eq!(relative_rows[&DisplayRow(1)], 4);
11983        assert_eq!(relative_rows[&DisplayRow(2)], 3);
11984
11985        const DELETED_LINE: u32 = 3;
11986        let layouts = cx
11987            .update_window(*window, |_, window, cx| {
11988                element.layout_line_numbers(
11989                    None,
11990                    GutterDimensions {
11991                        left_padding: Pixels::ZERO,
11992                        right_padding: Pixels::ZERO,
11993                        width: px(30.0),
11994                        margin: Pixels::ZERO,
11995                        git_blame_entries_width: None,
11996                    },
11997                    line_height,
11998                    gpui::Point::default(),
11999                    DisplayRow(0)..DisplayRow(6),
12000                    &(0..6)
12001                        .map(|row| RowInfo {
12002                            buffer_row: Some(row),
12003                            diff_status: (row == DELETED_LINE).then(|| {
12004                                DiffHunkStatus::deleted(
12005                                    buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12006                                )
12007                            }),
12008                            ..Default::default()
12009                        })
12010                        .collect::<Vec<_>>(),
12011                    &BTreeMap::default(),
12012                    Some(DisplayRow(0)),
12013                    &snapshot,
12014                    window,
12015                    cx,
12016                )
12017            })
12018            .unwrap();
12019        assert_eq!(layouts.len(), 5,);
12020        assert!(
12021            layouts.get(&MultiBufferRow(DELETED_LINE)).is_none(),
12022            "Deleted line should not have a line number"
12023        );
12024    }
12025
12026    #[gpui::test]
12027    fn test_layout_line_numbers_wrapping(cx: &mut TestAppContext) {
12028        init_test(cx, |_| {});
12029        let window = cx.add_window(|window, cx| {
12030            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12031            Editor::new(EditorMode::full(), buffer, None, window, cx)
12032        });
12033
12034        update_test_language_settings(cx, |s| {
12035            s.defaults.preferred_line_length = Some(5_u32);
12036            s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
12037        });
12038
12039        let editor = window.root(cx).unwrap();
12040        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12041        let line_height = window
12042            .update(cx, |_, window, _| {
12043                style.text.line_height_in_pixels(window.rem_size())
12044            })
12045            .unwrap();
12046        let element = EditorElement::new(&editor, style);
12047        let snapshot = window
12048            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12049            .unwrap();
12050
12051        let layouts = cx
12052            .update_window(*window, |_, window, cx| {
12053                element.layout_line_numbers(
12054                    None,
12055                    GutterDimensions {
12056                        left_padding: Pixels::ZERO,
12057                        right_padding: Pixels::ZERO,
12058                        width: px(30.0),
12059                        margin: Pixels::ZERO,
12060                        git_blame_entries_width: None,
12061                    },
12062                    line_height,
12063                    gpui::Point::default(),
12064                    DisplayRow(0)..DisplayRow(6),
12065                    &(0..6)
12066                        .map(|row| RowInfo {
12067                            buffer_row: Some(row),
12068                            ..Default::default()
12069                        })
12070                        .collect::<Vec<_>>(),
12071                    &BTreeMap::default(),
12072                    Some(DisplayRow(0)),
12073                    &snapshot,
12074                    window,
12075                    cx,
12076                )
12077            })
12078            .unwrap();
12079        assert_eq!(layouts.len(), 3);
12080
12081        let relative_rows = window
12082            .update(cx, |editor, window, cx| {
12083                let snapshot = editor.snapshot(window, cx);
12084                snapshot.calculate_relative_line_numbers(
12085                    &(DisplayRow(0)..DisplayRow(6)),
12086                    DisplayRow(3),
12087                    true,
12088                )
12089            })
12090            .unwrap();
12091
12092        assert_eq!(relative_rows[&DisplayRow(0)], 3);
12093        assert_eq!(relative_rows[&DisplayRow(1)], 2);
12094        assert_eq!(relative_rows[&DisplayRow(2)], 1);
12095        // current line has no relative number
12096        assert!(!relative_rows.contains_key(&DisplayRow(3)));
12097        assert_eq!(relative_rows[&DisplayRow(4)], 1);
12098        assert_eq!(relative_rows[&DisplayRow(5)], 2);
12099
12100        let layouts = cx
12101            .update_window(*window, |_, window, cx| {
12102                element.layout_line_numbers(
12103                    None,
12104                    GutterDimensions {
12105                        left_padding: Pixels::ZERO,
12106                        right_padding: Pixels::ZERO,
12107                        width: px(30.0),
12108                        margin: Pixels::ZERO,
12109                        git_blame_entries_width: None,
12110                    },
12111                    line_height,
12112                    gpui::Point::default(),
12113                    DisplayRow(0)..DisplayRow(6),
12114                    &(0..6)
12115                        .map(|row| RowInfo {
12116                            buffer_row: Some(row),
12117                            diff_status: Some(DiffHunkStatus::deleted(
12118                                buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12119                            )),
12120                            ..Default::default()
12121                        })
12122                        .collect::<Vec<_>>(),
12123                    &BTreeMap::from_iter([(DisplayRow(0), LineHighlightSpec::default())]),
12124                    Some(DisplayRow(0)),
12125                    &snapshot,
12126                    window,
12127                    cx,
12128                )
12129            })
12130            .unwrap();
12131        assert!(
12132            layouts.is_empty(),
12133            "Deleted lines should have no line number"
12134        );
12135
12136        let relative_rows = window
12137            .update(cx, |editor, window, cx| {
12138                let snapshot = editor.snapshot(window, cx);
12139                snapshot.calculate_relative_line_numbers(
12140                    &(DisplayRow(0)..DisplayRow(6)),
12141                    DisplayRow(3),
12142                    true,
12143                )
12144            })
12145            .unwrap();
12146
12147        // Deleted lines should still have relative numbers
12148        assert_eq!(relative_rows[&DisplayRow(0)], 3);
12149        assert_eq!(relative_rows[&DisplayRow(1)], 2);
12150        assert_eq!(relative_rows[&DisplayRow(2)], 1);
12151        // current line, even if deleted, has no relative number
12152        assert!(!relative_rows.contains_key(&DisplayRow(3)));
12153        assert_eq!(relative_rows[&DisplayRow(4)], 1);
12154        assert_eq!(relative_rows[&DisplayRow(5)], 2);
12155    }
12156
12157    #[gpui::test]
12158    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
12159        init_test(cx, |_| {});
12160
12161        let window = cx.add_window(|window, cx| {
12162            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
12163            Editor::new(EditorMode::full(), buffer, None, window, cx)
12164        });
12165        let cx = &mut VisualTestContext::from_window(*window, cx);
12166        let editor = window.root(cx).unwrap();
12167        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12168
12169        window
12170            .update(cx, |editor, window, cx| {
12171                editor.cursor_offset_on_selection = true;
12172                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
12173                    s.select_ranges([
12174                        Point::new(0, 0)..Point::new(1, 0),
12175                        Point::new(3, 2)..Point::new(3, 3),
12176                        Point::new(5, 6)..Point::new(6, 0),
12177                    ]);
12178                });
12179            })
12180            .unwrap();
12181
12182        let (_, state) = cx.draw(
12183            point(px(500.), px(500.)),
12184            size(px(500.), px(500.)),
12185            |_, _| EditorElement::new(&editor, style),
12186        );
12187
12188        assert_eq!(state.selections.len(), 1);
12189        let local_selections = &state.selections[0].1;
12190        assert_eq!(local_selections.len(), 3);
12191        // moves cursor back one line
12192        assert_eq!(
12193            local_selections[0].head,
12194            DisplayPoint::new(DisplayRow(0), 6)
12195        );
12196        assert_eq!(
12197            local_selections[0].range,
12198            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
12199        );
12200
12201        // moves cursor back one column
12202        assert_eq!(
12203            local_selections[1].range,
12204            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
12205        );
12206        assert_eq!(
12207            local_selections[1].head,
12208            DisplayPoint::new(DisplayRow(3), 2)
12209        );
12210
12211        // leaves cursor on the max point
12212        assert_eq!(
12213            local_selections[2].range,
12214            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
12215        );
12216        assert_eq!(
12217            local_selections[2].head,
12218            DisplayPoint::new(DisplayRow(6), 0)
12219        );
12220
12221        // active lines does not include 1 (even though the range of the selection does)
12222        assert_eq!(
12223            state.active_rows.keys().cloned().collect::<Vec<_>>(),
12224            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
12225        );
12226    }
12227
12228    #[gpui::test]
12229    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
12230        init_test(cx, |_| {});
12231
12232        let window = cx.add_window(|window, cx| {
12233            let buffer = MultiBuffer::build_simple("", cx);
12234            Editor::new(EditorMode::full(), buffer, None, window, cx)
12235        });
12236        let cx = &mut VisualTestContext::from_window(*window, cx);
12237        let editor = window.root(cx).unwrap();
12238        let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12239        window
12240            .update(cx, |editor, window, cx| {
12241                editor.set_placeholder_text("hello", window, cx);
12242                editor.insert_blocks(
12243                    [BlockProperties {
12244                        style: BlockStyle::Fixed,
12245                        placement: BlockPlacement::Above(Anchor::min()),
12246                        height: Some(3),
12247                        render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
12248                        priority: 0,
12249                    }],
12250                    None,
12251                    cx,
12252                );
12253
12254                // Blur the editor so that it displays placeholder text.
12255                window.blur();
12256            })
12257            .unwrap();
12258
12259        let (_, state) = cx.draw(
12260            point(px(500.), px(500.)),
12261            size(px(500.), px(500.)),
12262            |_, _| EditorElement::new(&editor, style),
12263        );
12264        assert_eq!(state.position_map.line_layouts.len(), 4);
12265        assert_eq!(state.line_numbers.len(), 1);
12266        assert_eq!(
12267            state
12268                .line_numbers
12269                .get(&MultiBufferRow(0))
12270                .map(|line_number| line_number
12271                    .segments
12272                    .first()
12273                    .unwrap()
12274                    .shaped_line
12275                    .text
12276                    .as_ref()),
12277            Some("1")
12278        );
12279    }
12280
12281    #[gpui::test]
12282    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
12283        const TAB_SIZE: u32 = 4;
12284
12285        let input_text = "\t \t|\t| a b";
12286        let expected_invisibles = vec![
12287            Invisible::Tab {
12288                line_start_offset: 0,
12289                line_end_offset: TAB_SIZE as usize,
12290            },
12291            Invisible::Whitespace {
12292                line_offset: TAB_SIZE as usize,
12293            },
12294            Invisible::Tab {
12295                line_start_offset: TAB_SIZE as usize + 1,
12296                line_end_offset: TAB_SIZE as usize * 2,
12297            },
12298            Invisible::Tab {
12299                line_start_offset: TAB_SIZE as usize * 2 + 1,
12300                line_end_offset: TAB_SIZE as usize * 3,
12301            },
12302            Invisible::Whitespace {
12303                line_offset: TAB_SIZE as usize * 3 + 1,
12304            },
12305            Invisible::Whitespace {
12306                line_offset: TAB_SIZE as usize * 3 + 3,
12307            },
12308        ];
12309        assert_eq!(
12310            expected_invisibles.len(),
12311            input_text
12312                .chars()
12313                .filter(|initial_char| initial_char.is_whitespace())
12314                .count(),
12315            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
12316        );
12317
12318        for show_line_numbers in [true, false] {
12319            init_test(cx, |s| {
12320                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12321                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
12322            });
12323
12324            let actual_invisibles = collect_invisibles_from_new_editor(
12325                cx,
12326                EditorMode::full(),
12327                input_text,
12328                px(500.0),
12329                show_line_numbers,
12330            );
12331
12332            assert_eq!(expected_invisibles, actual_invisibles);
12333        }
12334    }
12335
12336    #[gpui::test]
12337    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
12338        init_test(cx, |s| {
12339            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12340            s.defaults.tab_size = NonZeroU32::new(4);
12341        });
12342
12343        for editor_mode_without_invisibles in [
12344            EditorMode::SingleLine,
12345            EditorMode::AutoHeight {
12346                min_lines: 1,
12347                max_lines: Some(100),
12348            },
12349        ] {
12350            for show_line_numbers in [true, false] {
12351                let invisibles = collect_invisibles_from_new_editor(
12352                    cx,
12353                    editor_mode_without_invisibles.clone(),
12354                    "\t\t\t| | a b",
12355                    px(500.0),
12356                    show_line_numbers,
12357                );
12358                assert!(
12359                    invisibles.is_empty(),
12360                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
12361                );
12362            }
12363        }
12364    }
12365
12366    #[gpui::test]
12367    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
12368        let tab_size = 4;
12369        let input_text = "a\tbcd     ".repeat(9);
12370        let repeated_invisibles = [
12371            Invisible::Tab {
12372                line_start_offset: 1,
12373                line_end_offset: tab_size as usize,
12374            },
12375            Invisible::Whitespace {
12376                line_offset: tab_size as usize + 3,
12377            },
12378            Invisible::Whitespace {
12379                line_offset: tab_size as usize + 4,
12380            },
12381            Invisible::Whitespace {
12382                line_offset: tab_size as usize + 5,
12383            },
12384            Invisible::Whitespace {
12385                line_offset: tab_size as usize + 6,
12386            },
12387            Invisible::Whitespace {
12388                line_offset: tab_size as usize + 7,
12389            },
12390        ];
12391        let expected_invisibles = std::iter::once(repeated_invisibles)
12392            .cycle()
12393            .take(9)
12394            .flatten()
12395            .collect::<Vec<_>>();
12396        assert_eq!(
12397            expected_invisibles.len(),
12398            input_text
12399                .chars()
12400                .filter(|initial_char| initial_char.is_whitespace())
12401                .count(),
12402            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
12403        );
12404        info!("Expected invisibles: {expected_invisibles:?}");
12405
12406        init_test(cx, |_| {});
12407
12408        // Put the same string with repeating whitespace pattern into editors of various size,
12409        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
12410        let resize_step = 10.0;
12411        let mut editor_width = 200.0;
12412        while editor_width <= 1000.0 {
12413            for show_line_numbers in [true, false] {
12414                update_test_language_settings(cx, |s| {
12415                    s.defaults.tab_size = NonZeroU32::new(tab_size);
12416                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12417                    s.defaults.preferred_line_length = Some(editor_width as u32);
12418                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
12419                });
12420
12421                let actual_invisibles = collect_invisibles_from_new_editor(
12422                    cx,
12423                    EditorMode::full(),
12424                    &input_text,
12425                    px(editor_width),
12426                    show_line_numbers,
12427                );
12428
12429                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
12430                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
12431                let mut i = 0;
12432                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
12433                    i = actual_index;
12434                    match expected_invisibles.get(i) {
12435                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
12436                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
12437                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
12438                            _ => {
12439                                panic!(
12440                                    "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
12441                                )
12442                            }
12443                        },
12444                        None => {
12445                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
12446                        }
12447                    }
12448                }
12449                let missing_expected_invisibles = &expected_invisibles[i + 1..];
12450                assert!(
12451                    missing_expected_invisibles.is_empty(),
12452                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
12453                );
12454
12455                editor_width += resize_step;
12456            }
12457        }
12458    }
12459
12460    fn collect_invisibles_from_new_editor(
12461        cx: &mut TestAppContext,
12462        editor_mode: EditorMode,
12463        input_text: &str,
12464        editor_width: Pixels,
12465        show_line_numbers: bool,
12466    ) -> Vec<Invisible> {
12467        info!(
12468            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
12469            f32::from(editor_width)
12470        );
12471        let window = cx.add_window(|window, cx| {
12472            let buffer = MultiBuffer::build_simple(input_text, cx);
12473            Editor::new(editor_mode, buffer, None, window, cx)
12474        });
12475        let cx = &mut VisualTestContext::from_window(*window, cx);
12476        let editor = window.root(cx).unwrap();
12477
12478        let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12479        window
12480            .update(cx, |editor, _, cx| {
12481                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12482                editor.set_wrap_width(Some(editor_width), cx);
12483                editor.set_show_line_numbers(show_line_numbers, cx);
12484            })
12485            .unwrap();
12486        let (_, state) = cx.draw(
12487            point(px(500.), px(500.)),
12488            size(px(500.), px(500.)),
12489            |_, _| EditorElement::new(&editor, style),
12490        );
12491        state
12492            .position_map
12493            .line_layouts
12494            .iter()
12495            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
12496            .cloned()
12497            .collect()
12498    }
12499
12500    #[gpui::test]
12501    fn test_merge_overlapping_ranges() {
12502        let base_bg = Hsla::white();
12503        let color1 = Hsla {
12504            h: 0.0,
12505            s: 0.5,
12506            l: 0.5,
12507            a: 0.5,
12508        };
12509        let color2 = Hsla {
12510            h: 120.0,
12511            s: 0.5,
12512            l: 0.5,
12513            a: 0.5,
12514        };
12515
12516        let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
12517        let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
12518            v.iter()
12519                .map(|(r, _)| (r.start.column(), r.end.column()))
12520                .collect()
12521        };
12522
12523        // Test overlapping ranges blend colors
12524        let overlapping = vec![
12525            (display_point(5)..display_point(15), color1),
12526            (display_point(10)..display_point(20), color2),
12527        ];
12528        let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
12529        assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
12530
12531        // Test middle segment should have blended color
12532        let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
12533        assert_eq!(result[1].1, blended);
12534
12535        // Test adjacent same-color ranges merge
12536        let adjacent_same = vec![
12537            (display_point(5)..display_point(10), color1),
12538            (display_point(10)..display_point(15), color1),
12539        ];
12540        let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
12541        assert_eq!(cols(&result), vec![(5, 15)]);
12542
12543        // Test contained range splits
12544        let contained = vec![
12545            (display_point(5)..display_point(20), color1),
12546            (display_point(10)..display_point(15), color2),
12547        ];
12548        let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
12549        assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
12550
12551        // Test multiple overlaps split at every boundary
12552        let color3 = Hsla {
12553            h: 240.0,
12554            s: 0.5,
12555            l: 0.5,
12556            a: 0.5,
12557        };
12558        let complex = vec![
12559            (display_point(5)..display_point(12), color1),
12560            (display_point(8)..display_point(16), color2),
12561            (display_point(10)..display_point(14), color3),
12562        ];
12563        let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
12564        assert_eq!(
12565            cols(&result),
12566            vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
12567        );
12568    }
12569
12570    #[gpui::test]
12571    fn test_bg_segments_per_row() {
12572        let base_bg = Hsla::white();
12573
12574        // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
12575        {
12576            let selection_color = Hsla {
12577                h: 200.0,
12578                s: 0.5,
12579                l: 0.5,
12580                a: 0.5,
12581            };
12582            let player_color = PlayerColor {
12583                cursor: selection_color,
12584                background: selection_color,
12585                selection: selection_color,
12586            };
12587
12588            let spanning_selection = SelectionLayout {
12589                head: DisplayPoint::new(DisplayRow(3), 7),
12590                cursor_shape: CursorShape::Bar,
12591                is_newest: true,
12592                is_local: true,
12593                range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
12594                active_rows: DisplayRow(1)..DisplayRow(4),
12595                user_name: None,
12596            };
12597
12598            let selections = vec![(player_color, vec![spanning_selection])];
12599            let result = EditorElement::bg_segments_per_row(
12600                DisplayRow(0)..DisplayRow(5),
12601                &selections,
12602                &[],
12603                base_bg,
12604            );
12605
12606            assert_eq!(result.len(), 5);
12607            assert!(result[0].is_empty());
12608            assert_eq!(result[1].len(), 1);
12609            assert_eq!(result[2].len(), 1);
12610            assert_eq!(result[3].len(), 1);
12611            assert!(result[4].is_empty());
12612
12613            assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
12614            assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
12615            assert_eq!(result[1][0].0.end.column(), u32::MAX);
12616            assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
12617            assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
12618            assert_eq!(result[2][0].0.end.column(), u32::MAX);
12619            assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
12620            assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
12621        }
12622
12623        // Case B: selection ends exactly at the start of row 3, excluding row 3
12624        {
12625            let selection_color = Hsla {
12626                h: 120.0,
12627                s: 0.5,
12628                l: 0.5,
12629                a: 0.5,
12630            };
12631            let player_color = PlayerColor {
12632                cursor: selection_color,
12633                background: selection_color,
12634                selection: selection_color,
12635            };
12636
12637            let selection = SelectionLayout {
12638                head: DisplayPoint::new(DisplayRow(2), 0),
12639                cursor_shape: CursorShape::Bar,
12640                is_newest: true,
12641                is_local: true,
12642                range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
12643                active_rows: DisplayRow(1)..DisplayRow(3),
12644                user_name: None,
12645            };
12646
12647            let selections = vec![(player_color, vec![selection])];
12648            let result = EditorElement::bg_segments_per_row(
12649                DisplayRow(0)..DisplayRow(4),
12650                &selections,
12651                &[],
12652                base_bg,
12653            );
12654
12655            assert_eq!(result.len(), 4);
12656            assert!(result[0].is_empty());
12657            assert_eq!(result[1].len(), 1);
12658            assert_eq!(result[2].len(), 1);
12659            assert!(result[3].is_empty());
12660
12661            assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
12662            assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
12663            assert_eq!(result[1][0].0.end.column(), u32::MAX);
12664            assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
12665            assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
12666            assert_eq!(result[2][0].0.end.column(), u32::MAX);
12667        }
12668    }
12669
12670    #[cfg(test)]
12671    fn generate_test_run(len: usize, color: Hsla) -> TextRun {
12672        TextRun {
12673            len,
12674            color,
12675            ..Default::default()
12676        }
12677    }
12678
12679    #[gpui::test]
12680    fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
12681        init_test(cx, |_| {});
12682
12683        let dx = |start: u32, end: u32| {
12684            DisplayPoint::new(DisplayRow(0), start)..DisplayPoint::new(DisplayRow(0), end)
12685        };
12686
12687        let text_color = Hsla {
12688            h: 210.0,
12689            s: 0.1,
12690            l: 0.4,
12691            a: 1.0,
12692        };
12693        let bg_1 = Hsla {
12694            h: 30.0,
12695            s: 0.6,
12696            l: 0.8,
12697            a: 1.0,
12698        };
12699        let bg_2 = Hsla {
12700            h: 200.0,
12701            s: 0.6,
12702            l: 0.2,
12703            a: 1.0,
12704        };
12705        let min_contrast = 45.0;
12706        let adjusted_bg1 = ensure_minimum_contrast(text_color, bg_1, min_contrast);
12707        let adjusted_bg2 = ensure_minimum_contrast(text_color, bg_2, min_contrast);
12708
12709        // Case A: single run; disjoint segments inside the run
12710        {
12711            let runs = vec![generate_test_run(20, text_color)];
12712            let segs = vec![(dx(5, 10), bg_1), (dx(12, 16), bg_2)];
12713            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
12714            // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
12715            assert_eq!(
12716                out.iter().map(|r| r.len).collect::<Vec<_>>(),
12717                vec![5, 5, 2, 4, 4]
12718            );
12719            assert_eq!(out[0].color, text_color);
12720            assert_eq!(out[1].color, adjusted_bg1);
12721            assert_eq!(out[2].color, text_color);
12722            assert_eq!(out[3].color, adjusted_bg2);
12723            assert_eq!(out[4].color, text_color);
12724        }
12725
12726        // Case B: multiple runs; segment extends to end of line (u32::MAX)
12727        {
12728            let runs = vec![
12729                generate_test_run(8, text_color),
12730                generate_test_run(7, text_color),
12731            ];
12732            let segs = vec![(dx(6, u32::MAX), bg_1)];
12733            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
12734            // Expected slices across runs: [0,6) [6,8) | [0,7)
12735            assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
12736            assert_eq!(out[0].color, text_color);
12737            assert_eq!(out[1].color, adjusted_bg1);
12738            assert_eq!(out[2].color, adjusted_bg1);
12739        }
12740
12741        // Case C: multi-byte characters
12742        {
12743            // for text: "Hello 🌍 δΈ–η•Œ!"
12744            let runs = vec![
12745                generate_test_run(5, text_color), // "Hello"
12746                generate_test_run(6, text_color), // " 🌍 "
12747                generate_test_run(6, text_color), // "δΈ–η•Œ"
12748                generate_test_run(1, text_color), // "!"
12749            ];
12750            // selecting "🌍 δΈ–"
12751            let segs = vec![(dx(6, 14), bg_1)];
12752            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
12753            // "Hello" | " " | "🌍 " | "δΈ–" | "η•Œ" | "!"
12754            assert_eq!(
12755                out.iter().map(|r| r.len).collect::<Vec<_>>(),
12756                vec![5, 1, 5, 3, 3, 1]
12757            );
12758            assert_eq!(out[0].color, text_color); // "Hello"
12759            assert_eq!(out[2].color, adjusted_bg1); // "🌍 "
12760            assert_eq!(out[3].color, adjusted_bg1); // "δΈ–"
12761            assert_eq!(out[4].color, text_color); // "η•Œ"
12762            assert_eq!(out[5].color, text_color); // "!"
12763        }
12764
12765        // Case D: split multiple consecutive text runs with segments
12766        {
12767            let segs = vec![
12768                (dx(2, 4), bg_1),   // selecting "cd"
12769                (dx(4, 8), bg_2),   // selecting "efgh"
12770                (dx(9, 11), bg_1),  // selecting "jk"
12771                (dx(12, 16), bg_2), // selecting "mnop"
12772                (dx(18, 19), bg_1), // selecting "s"
12773            ];
12774
12775            // for text: "abcdef"
12776            let runs = vec![
12777                generate_test_run(2, text_color), // ab
12778                generate_test_run(4, text_color), // cdef
12779            ];
12780            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
12781            // new splits "ab", "cd", "ef"
12782            assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![2, 2, 2]);
12783            assert_eq!(out[0].color, text_color);
12784            assert_eq!(out[1].color, adjusted_bg1);
12785            assert_eq!(out[2].color, adjusted_bg2);
12786
12787            // for text: "ghijklmn"
12788            let runs = vec![
12789                generate_test_run(3, text_color), // ghi
12790                generate_test_run(2, text_color), // jk
12791                generate_test_run(3, text_color), // lmn
12792            ];
12793            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 6); // 2 + 4 from first run
12794            // new splits "gh", "i", "jk", "l", "mn"
12795            assert_eq!(
12796                out.iter().map(|r| r.len).collect::<Vec<_>>(),
12797                vec![2, 1, 2, 1, 2]
12798            );
12799            assert_eq!(out[0].color, adjusted_bg2);
12800            assert_eq!(out[1].color, text_color);
12801            assert_eq!(out[2].color, adjusted_bg1);
12802            assert_eq!(out[3].color, text_color);
12803            assert_eq!(out[4].color, adjusted_bg2);
12804
12805            // for text: "opqrs"
12806            let runs = vec![
12807                generate_test_run(1, text_color), // o
12808                generate_test_run(4, text_color), // pqrs
12809            ];
12810            let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 14); // 6 + 3 + 2 + 3 from first two runs
12811            // new splits "o", "p", "qr", "s"
12812            assert_eq!(
12813                out.iter().map(|r| r.len).collect::<Vec<_>>(),
12814                vec![1, 1, 2, 1]
12815            );
12816            assert_eq!(out[0].color, adjusted_bg2);
12817            assert_eq!(out[1].color, adjusted_bg2);
12818            assert_eq!(out[2].color, text_color);
12819            assert_eq!(out[3].color, adjusted_bg1);
12820        }
12821    }
12822}