element.rs

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