element.rs

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