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