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