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