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