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