element.rs

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