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