element.rs

   1use crate::{
   2    code_context_menus::{CodeActionsMenu, MENU_ASIDE_MAX_WIDTH, MENU_ASIDE_MIN_WIDTH, MENU_GAP},
   3    commit_tooltip::{blame_entry_relative_timestamp, CommitTooltip, ParsedCommitMessage},
   4    display_map::{
   5        Block, BlockContext, BlockStyle, DisplaySnapshot, HighlightedChunk, ToDisplayPoint,
   6    },
   7    editor_settings::{
   8        CurrentLineHighlight, DoubleClickInMultibuffer, MultiCursorModifier, ScrollBeyondLastLine,
   9        ScrollbarDiagnostics, ShowScrollbar,
  10    },
  11    git::blame::GitBlame,
  12    hover_popover::{
  13        self, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
  14    },
  15    inlay_hint_settings,
  16    items::BufferSearchHighlights,
  17    mouse_context_menu::{self, MenuPosition, MouseContextMenu},
  18    scroll::{axis_pair, scroll_amount::ScrollAmount, AxisPair},
  19    BlockId, ChunkReplacement, CursorShape, CustomBlockId, DisplayDiffHunk, DisplayPoint,
  20    DisplayRow, DocumentHighlightRead, DocumentHighlightWrite, EditDisplayMode, Editor, EditorMode,
  21    EditorSettings, EditorSnapshot, EditorStyle, ExpandExcerpts, FocusedBlock, GoToHunk,
  22    GoToPreviousHunk, GutterDimensions, HalfPageDown, HalfPageUp, HandleInput, HoveredCursor,
  23    InlayHintRefreshReason, InlineCompletion, JumpData, LineDown, LineUp, OpenExcerpts, PageDown,
  24    PageUp, Point, RowExt, RowRangeExt, SelectPhase, SelectedTextHighlight, Selection, SoftWrap,
  25    StickyHeaderExcerpt, ToPoint, ToggleFold, COLUMNAR_SELECTION_MODIFIERS, CURSORS_VISIBLE_FOR,
  26    FILE_HEADER_HEIGHT, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED, MAX_LINE_LEN,
  27    MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
  28};
  29use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
  30use client::ParticipantIndex;
  31use collections::{BTreeMap, HashMap, HashSet};
  32use file_icons::FileIcons;
  33use git::{blame::BlameEntry, status::FileStatus, Oid};
  34use gpui::{
  35    anchored, deferred, div, fill, linear_color_stop, linear_gradient, outline, 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::backtab);
 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
2726                            && is_folded
2727                            && focus_handle.contains_focused(window, cx)
2728                        {
2729                            colors.border_focused
2730                        } else {
2731                            colors.border
2732                        };
2733                        div.border_color(border_color)
2734                    })
2735                    .bg(colors.editor_subheader_background)
2736                    .hover(|style| style.bg(colors.element_hover))
2737                    .map(|header| {
2738                        let editor = self.editor.clone();
2739                        let buffer_id = for_excerpt.buffer_id;
2740                        let toggle_chevron_icon =
2741                            FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
2742                        header.child(
2743                            div()
2744                                .hover(|style| style.bg(colors.element_selected))
2745                                .rounded_sm()
2746                                .child(
2747                                    ButtonLike::new("toggle-buffer-fold")
2748                                        .style(ui::ButtonStyle::Transparent)
2749                                        .size(ButtonSize::Large)
2750                                        .width(px(30.).into())
2751                                        .children(toggle_chevron_icon)
2752                                        .tooltip({
2753                                            let focus_handle = focus_handle.clone();
2754                                            move |window, cx| {
2755                                                Tooltip::for_action_in(
2756                                                    "Toggle Excerpt Fold",
2757                                                    &ToggleFold,
2758                                                    &focus_handle,
2759                                                    window,
2760                                                    cx,
2761                                                )
2762                                            }
2763                                        })
2764                                        .on_click(move |_, _, cx| {
2765                                            if is_folded {
2766                                                editor.update(cx, |editor, cx| {
2767                                                    editor.unfold_buffer(buffer_id, cx);
2768                                                });
2769                                            } else {
2770                                                editor.update(cx, |editor, cx| {
2771                                                    editor.fold_buffer(buffer_id, cx);
2772                                                });
2773                                            }
2774                                        }),
2775                                ),
2776                        )
2777                    })
2778                    .children(
2779                        self.editor
2780                            .read(cx)
2781                            .addons
2782                            .values()
2783                            .filter_map(|addon| {
2784                                addon.render_buffer_header_controls(for_excerpt, window, cx)
2785                            })
2786                            .take(1),
2787                    )
2788                    .child(
2789                        h_flex()
2790                            .cursor_pointer()
2791                            .id("path header block")
2792                            .size_full()
2793                            .justify_between()
2794                            .child(
2795                                h_flex()
2796                                    .gap_2()
2797                                    .child(
2798                                        Label::new(
2799                                            filename
2800                                                .map(SharedString::from)
2801                                                .unwrap_or_else(|| "untitled".into()),
2802                                        )
2803                                        .single_line()
2804                                        .when_some(
2805                                            file_status,
2806                                            |el, status| {
2807                                                el.color(if status.is_conflicted() {
2808                                                    Color::Conflict
2809                                                } else if status.is_modified() {
2810                                                    Color::Modified
2811                                                } else if status.is_deleted() {
2812                                                    Color::Disabled
2813                                                } else {
2814                                                    Color::Created
2815                                                })
2816                                                .when(status.is_deleted(), |el| el.strikethrough())
2817                                            },
2818                                        ),
2819                                    )
2820                                    .when_some(parent_path, |then, path| {
2821                                        then.child(div().child(path).text_color(
2822                                            if file_status.is_some_and(FileStatus::is_deleted) {
2823                                                colors.text_disabled
2824                                            } else {
2825                                                colors.text_muted
2826                                            },
2827                                        ))
2828                                    }),
2829                            )
2830                            .when(is_selected, |el| {
2831                                el.child(
2832                                    h_flex()
2833                                        .id("jump-to-file-button")
2834                                        .gap_2p5()
2835                                        .child(Label::new("Jump To File"))
2836                                        .children(
2837                                            KeyBinding::for_action_in(
2838                                                &OpenExcerpts,
2839                                                &focus_handle,
2840                                                window,
2841                                                cx,
2842                                            )
2843                                            .map(|binding| binding.into_any_element()),
2844                                        ),
2845                                )
2846                            })
2847                            .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
2848                            .on_click(window.listener_for(&self.editor, {
2849                                move |editor, e: &ClickEvent, window, cx| {
2850                                    editor.open_excerpts_common(
2851                                        Some(jump_data.clone()),
2852                                        e.down.modifiers.secondary(),
2853                                        window,
2854                                        cx,
2855                                    );
2856                                }
2857                            })),
2858                    ),
2859            )
2860    }
2861
2862    fn render_expand_excerpt_control(
2863        &self,
2864        block_id: BlockId,
2865        direction: ExpandExcerptDirection,
2866        excerpt_id: ExcerptId,
2867        gutter_dimensions: &GutterDimensions,
2868        window: &Window,
2869        cx: &mut App,
2870    ) -> impl IntoElement {
2871        let color = cx.theme().colors().clone();
2872        let hover_color = color.border_variant.opacity(0.5);
2873        let focus_handle = self.editor.focus_handle(cx).clone();
2874
2875        let icon_offset =
2876            gutter_dimensions.width - (gutter_dimensions.left_padding + gutter_dimensions.margin);
2877        let header_height = MULTI_BUFFER_EXCERPT_HEADER_HEIGHT as f32 * window.line_height();
2878        let group_name = if direction == ExpandExcerptDirection::Down {
2879            "expand-down"
2880        } else {
2881            "expand-up"
2882        };
2883
2884        let expand_area = |id: SharedString| {
2885            h_flex()
2886                .id(id)
2887                .w_full()
2888                .cursor_pointer()
2889                .block_mouse_down()
2890                .on_mouse_move(|_, _, cx| cx.stop_propagation())
2891                .hover(|style| style.bg(hover_color))
2892                .tooltip({
2893                    let focus_handle = focus_handle.clone();
2894                    move |window, cx| {
2895                        Tooltip::for_action_in(
2896                            "Expand Excerpt",
2897                            &ExpandExcerpts { lines: 0 },
2898                            &focus_handle,
2899                            window,
2900                            cx,
2901                        )
2902                    }
2903                })
2904        };
2905
2906        expand_area(
2907            format!(
2908                "block-{}-{}",
2909                block_id,
2910                if direction == ExpandExcerptDirection::Down {
2911                    "down"
2912                } else {
2913                    "up"
2914                }
2915            )
2916            .into(),
2917        )
2918        .group(group_name)
2919        .child(
2920            h_flex()
2921                .w(icon_offset)
2922                .h(header_height)
2923                .flex_none()
2924                .justify_end()
2925                .child(
2926                    ButtonLike::new("expand-icon")
2927                        .style(ButtonStyle::Transparent)
2928                        .child(
2929                            svg()
2930                                .path(if direction == ExpandExcerptDirection::Down {
2931                                    IconName::ArrowDownFromLine.path()
2932                                } else {
2933                                    IconName::ArrowUpFromLine.path()
2934                                })
2935                                .size(IconSize::XSmall.rems())
2936                                .text_color(cx.theme().colors().editor_line_number)
2937                                .group_hover(group_name, |style| {
2938                                    style.text_color(cx.theme().colors().editor_active_line_number)
2939                                }),
2940                        ),
2941                ),
2942        )
2943        .on_click(window.listener_for(&self.editor, {
2944            move |editor, _, _, cx| {
2945                editor.expand_excerpt(excerpt_id, direction, cx);
2946                cx.stop_propagation();
2947            }
2948        }))
2949    }
2950
2951    #[allow(clippy::too_many_arguments)]
2952    fn render_blocks(
2953        &self,
2954        rows: Range<DisplayRow>,
2955        snapshot: &EditorSnapshot,
2956        hitbox: &Hitbox,
2957        text_hitbox: &Hitbox,
2958        editor_width: Pixels,
2959        scroll_width: &mut Pixels,
2960        gutter_dimensions: &GutterDimensions,
2961        em_width: Pixels,
2962        text_x: Pixels,
2963        line_height: Pixels,
2964        line_layouts: &[LineWithInvisibles],
2965        selections: &[Selection<Point>],
2966        selected_buffer_ids: &Vec<BufferId>,
2967        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2968        sticky_header_excerpt_id: Option<ExcerptId>,
2969        window: &mut Window,
2970        cx: &mut App,
2971    ) -> Result<Vec<BlockLayout>, HashMap<CustomBlockId, u32>> {
2972        let (fixed_blocks, non_fixed_blocks) = snapshot
2973            .blocks_in_range(rows.clone())
2974            .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
2975
2976        let mut focused_block = self
2977            .editor
2978            .update(cx, |editor, _| editor.take_focused_block());
2979        let mut fixed_block_max_width = Pixels::ZERO;
2980        let mut blocks = Vec::new();
2981        let mut resized_blocks = HashMap::default();
2982
2983        for (row, block) in fixed_blocks {
2984            let block_id = block.id();
2985
2986            if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2987                focused_block = None;
2988            }
2989
2990            let (element, element_size) = self.render_block(
2991                block,
2992                AvailableSpace::MinContent,
2993                block_id,
2994                row,
2995                snapshot,
2996                text_x,
2997                &rows,
2998                line_layouts,
2999                gutter_dimensions,
3000                line_height,
3001                em_width,
3002                text_hitbox,
3003                editor_width,
3004                scroll_width,
3005                &mut resized_blocks,
3006                selections,
3007                selected_buffer_ids,
3008                is_row_soft_wrapped,
3009                sticky_header_excerpt_id,
3010                window,
3011                cx,
3012            );
3013            fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
3014            blocks.push(BlockLayout {
3015                id: block_id,
3016                row: Some(row),
3017                element,
3018                available_space: size(AvailableSpace::MinContent, element_size.height.into()),
3019                style: BlockStyle::Fixed,
3020            });
3021        }
3022
3023        for (row, block) in non_fixed_blocks {
3024            let style = block.style();
3025            let width = match style {
3026                BlockStyle::Sticky => hitbox.size.width,
3027                BlockStyle::Flex => hitbox
3028                    .size
3029                    .width
3030                    .max(fixed_block_max_width)
3031                    .max(gutter_dimensions.width + *scroll_width),
3032                BlockStyle::Fixed => unreachable!(),
3033            };
3034            let block_id = block.id();
3035
3036            if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
3037                focused_block = None;
3038            }
3039
3040            let (element, element_size) = self.render_block(
3041                block,
3042                width.into(),
3043                block_id,
3044                row,
3045                snapshot,
3046                text_x,
3047                &rows,
3048                line_layouts,
3049                gutter_dimensions,
3050                line_height,
3051                em_width,
3052                text_hitbox,
3053                editor_width,
3054                scroll_width,
3055                &mut resized_blocks,
3056                selections,
3057                selected_buffer_ids,
3058                is_row_soft_wrapped,
3059                sticky_header_excerpt_id,
3060                window,
3061                cx,
3062            );
3063
3064            blocks.push(BlockLayout {
3065                id: block_id,
3066                row: Some(row),
3067                element,
3068                available_space: size(width.into(), element_size.height.into()),
3069                style,
3070            });
3071        }
3072
3073        if let Some(focused_block) = focused_block {
3074            if let Some(focus_handle) = focused_block.focus_handle.upgrade() {
3075                if focus_handle.is_focused(window) {
3076                    if let Some(block) = snapshot.block_for_id(focused_block.id) {
3077                        let style = block.style();
3078                        let width = match style {
3079                            BlockStyle::Fixed => AvailableSpace::MinContent,
3080                            BlockStyle::Flex => AvailableSpace::Definite(
3081                                hitbox
3082                                    .size
3083                                    .width
3084                                    .max(fixed_block_max_width)
3085                                    .max(gutter_dimensions.width + *scroll_width),
3086                            ),
3087                            BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
3088                        };
3089
3090                        let (element, element_size) = self.render_block(
3091                            &block,
3092                            width,
3093                            focused_block.id,
3094                            rows.end,
3095                            snapshot,
3096                            text_x,
3097                            &rows,
3098                            line_layouts,
3099                            gutter_dimensions,
3100                            line_height,
3101                            em_width,
3102                            text_hitbox,
3103                            editor_width,
3104                            scroll_width,
3105                            &mut resized_blocks,
3106                            selections,
3107                            selected_buffer_ids,
3108                            is_row_soft_wrapped,
3109                            sticky_header_excerpt_id,
3110                            window,
3111                            cx,
3112                        );
3113
3114                        blocks.push(BlockLayout {
3115                            id: block.id(),
3116                            row: None,
3117                            element,
3118                            available_space: size(width, element_size.height.into()),
3119                            style,
3120                        });
3121                    }
3122                }
3123            }
3124        }
3125
3126        if resized_blocks.is_empty() {
3127            *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
3128            Ok(blocks)
3129        } else {
3130            Err(resized_blocks)
3131        }
3132    }
3133
3134    /// Returns true if any of the blocks changed size since the previous frame. This will trigger
3135    /// a restart of rendering for the editor based on the new sizes.
3136    #[allow(clippy::too_many_arguments)]
3137    fn layout_blocks(
3138        &self,
3139        blocks: &mut Vec<BlockLayout>,
3140        block_starts: &mut HashSet<DisplayRow>,
3141        hitbox: &Hitbox,
3142        line_height: Pixels,
3143        scroll_pixel_position: gpui::Point<Pixels>,
3144        window: &mut Window,
3145        cx: &mut App,
3146    ) {
3147        for block in blocks {
3148            let mut origin = if let Some(row) = block.row {
3149                block_starts.insert(row);
3150                hitbox.origin
3151                    + point(
3152                        Pixels::ZERO,
3153                        row.as_f32() * line_height - scroll_pixel_position.y,
3154                    )
3155            } else {
3156                // Position the block outside the visible area
3157                hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
3158            };
3159
3160            if !matches!(block.style, BlockStyle::Sticky) {
3161                origin += point(-scroll_pixel_position.x, Pixels::ZERO);
3162            }
3163
3164            let focus_handle =
3165                block
3166                    .element
3167                    .prepaint_as_root(origin, block.available_space, window, cx);
3168
3169            if let Some(focus_handle) = focus_handle {
3170                self.editor.update(cx, |editor, _cx| {
3171                    editor.set_focused_block(FocusedBlock {
3172                        id: block.id,
3173                        focus_handle: focus_handle.downgrade(),
3174                    });
3175                });
3176            }
3177        }
3178    }
3179
3180    #[allow(clippy::too_many_arguments)]
3181    fn layout_sticky_buffer_header(
3182        &self,
3183        StickyHeaderExcerpt {
3184            excerpt,
3185            next_excerpt_controls_present,
3186            next_buffer_row,
3187        }: StickyHeaderExcerpt<'_>,
3188        scroll_position: f32,
3189        line_height: Pixels,
3190        snapshot: &EditorSnapshot,
3191        hitbox: &Hitbox,
3192        selected_buffer_ids: &Vec<BufferId>,
3193        window: &mut Window,
3194        cx: &mut App,
3195    ) -> AnyElement {
3196        let jump_data = header_jump_data(
3197            snapshot,
3198            DisplayRow(scroll_position as u32),
3199            FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
3200            excerpt,
3201        );
3202
3203        let editor_bg_color = cx.theme().colors().editor_background;
3204
3205        let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
3206
3207        let mut header = v_flex()
3208            .relative()
3209            .child(
3210                div()
3211                    .w(hitbox.bounds.size.width)
3212                    .h(FILE_HEADER_HEIGHT as f32 * line_height)
3213                    .bg(linear_gradient(
3214                        0.,
3215                        linear_color_stop(editor_bg_color.opacity(0.), 0.),
3216                        linear_color_stop(editor_bg_color, 0.6),
3217                    ))
3218                    .absolute()
3219                    .top_0(),
3220            )
3221            .child(
3222                self.render_buffer_header(excerpt, false, selected, jump_data, window, cx)
3223                    .into_any_element(),
3224            )
3225            .into_any_element();
3226
3227        let mut origin = hitbox.origin;
3228
3229        if let Some(next_buffer_row) = next_buffer_row {
3230            // Push up the sticky header when the excerpt is getting close to the top of the viewport
3231
3232            let mut max_row = next_buffer_row - FILE_HEADER_HEIGHT * 2;
3233
3234            if next_excerpt_controls_present {
3235                max_row -= MULTI_BUFFER_EXCERPT_HEADER_HEIGHT;
3236            }
3237
3238            let offset = scroll_position - max_row as f32;
3239
3240            if offset > 0.0 {
3241                origin.y -= Pixels(offset) * line_height;
3242            }
3243        }
3244
3245        let size = size(
3246            AvailableSpace::Definite(hitbox.size.width),
3247            AvailableSpace::MinContent,
3248        );
3249
3250        header.prepaint_as_root(origin, size, window, cx);
3251
3252        header
3253    }
3254
3255    #[allow(clippy::too_many_arguments)]
3256    fn layout_cursor_popovers(
3257        &self,
3258        line_height: Pixels,
3259        text_hitbox: &Hitbox,
3260        content_origin: gpui::Point<Pixels>,
3261        start_row: DisplayRow,
3262        scroll_pixel_position: gpui::Point<Pixels>,
3263        line_layouts: &[LineWithInvisibles],
3264        cursor: DisplayPoint,
3265        cursor_point: Point,
3266        style: &EditorStyle,
3267        window: &mut Window,
3268        cx: &mut App,
3269    ) {
3270        let mut min_menu_height = Pixels::ZERO;
3271        let mut max_menu_height = Pixels::ZERO;
3272        let mut height_above_menu = Pixels::ZERO;
3273        let height_below_menu = Pixels::ZERO;
3274        let mut edit_prediction_popover_visible = false;
3275        let mut context_menu_visible = false;
3276
3277        {
3278            let editor = self.editor.read(cx);
3279            if editor
3280                .edit_prediction_visible_in_cursor_popover(editor.has_active_inline_completion())
3281            {
3282                height_above_menu +=
3283                    editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
3284                edit_prediction_popover_visible = true;
3285            }
3286
3287            if editor.context_menu_visible() {
3288                if let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin() {
3289                    min_menu_height += line_height * 3. + POPOVER_Y_PADDING;
3290                    max_menu_height += line_height * 12. + POPOVER_Y_PADDING;
3291                    context_menu_visible = true;
3292                }
3293            }
3294        }
3295
3296        let visible = edit_prediction_popover_visible || context_menu_visible;
3297        if !visible {
3298            return;
3299        }
3300
3301        let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
3302        let target_position = content_origin
3303            + gpui::Point {
3304                x: cmp::max(
3305                    px(0.),
3306                    cursor_row_layout.x_for_index(cursor.column() as usize)
3307                        - scroll_pixel_position.x,
3308                ),
3309                y: cmp::max(
3310                    px(0.),
3311                    cursor.row().next_row().as_f32() * line_height - scroll_pixel_position.y,
3312                ),
3313            };
3314
3315        let viewport_bounds =
3316            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3317                right: -Self::SCROLLBAR_WIDTH - MENU_GAP,
3318                ..Default::default()
3319            });
3320
3321        let min_height = height_above_menu + min_menu_height + height_below_menu;
3322        let max_height = height_above_menu + max_menu_height + height_below_menu;
3323        let Some((laid_out_popovers, y_flipped)) = self.layout_popovers_above_or_below_line(
3324            target_position,
3325            line_height,
3326            min_height,
3327            max_height,
3328            text_hitbox,
3329            viewport_bounds,
3330            window,
3331            cx,
3332            |height, max_width_for_stable_x, y_flipped, window, cx| {
3333                // First layout the menu to get its size - others can be at least this wide.
3334                let context_menu = if context_menu_visible {
3335                    let menu_height = if y_flipped {
3336                        height - height_below_menu
3337                    } else {
3338                        height - height_above_menu
3339                    };
3340                    let mut element = self
3341                        .render_context_menu(line_height, menu_height, y_flipped, window, cx)
3342                        .expect("Visible context menu should always render.");
3343                    let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3344                    Some((CursorPopoverType::CodeContextMenu, element, size))
3345                } else {
3346                    None
3347                };
3348                let min_width = context_menu
3349                    .as_ref()
3350                    .map_or(px(0.), |(_, _, size)| size.width);
3351                let max_width = max_width_for_stable_x.max(
3352                    context_menu
3353                        .as_ref()
3354                        .map_or(px(0.), |(_, _, size)| size.width),
3355                );
3356
3357                let edit_prediction = if edit_prediction_popover_visible {
3358                    self.editor.update(cx, move |editor, cx| {
3359                        let accept_binding = editor.accept_edit_prediction_keybind(window, cx);
3360                        let mut element = editor.render_edit_prediction_cursor_popover(
3361                            min_width,
3362                            max_width,
3363                            cursor_point,
3364                            style,
3365                            accept_binding.keystroke(),
3366                            window,
3367                            cx,
3368                        )?;
3369                        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3370                        Some((CursorPopoverType::EditPrediction, element, size))
3371                    })
3372                } else {
3373                    None
3374                };
3375                vec![edit_prediction, context_menu]
3376                    .into_iter()
3377                    .flatten()
3378                    .collect::<Vec<_>>()
3379            },
3380        ) else {
3381            return;
3382        };
3383
3384        let Some((menu_ix, (_, menu_bounds))) = laid_out_popovers
3385            .iter()
3386            .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))
3387        else {
3388            return;
3389        };
3390        let last_ix = laid_out_popovers.len() - 1;
3391        let menu_is_last = menu_ix == last_ix;
3392        let first_popover_bounds = laid_out_popovers[0].1;
3393        let last_popover_bounds = laid_out_popovers[last_ix].1;
3394
3395        // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
3396        // right, and otherwise it goes below or to the right.
3397        let mut target_bounds = Bounds::from_corners(
3398            first_popover_bounds.origin,
3399            last_popover_bounds.bottom_right(),
3400        );
3401        target_bounds.size.width = menu_bounds.size.width;
3402
3403        // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
3404        // based on this is preferred for layout stability.
3405        let mut max_target_bounds = target_bounds;
3406        max_target_bounds.size.height = max_height;
3407        if y_flipped {
3408            max_target_bounds.origin.y -= max_height - target_bounds.size.height;
3409        }
3410
3411        // Add spacing around `target_bounds` and `max_target_bounds`.
3412        let mut extend_amount = Edges::all(MENU_GAP);
3413        if y_flipped {
3414            extend_amount.bottom = line_height;
3415        } else {
3416            extend_amount.top = line_height;
3417        }
3418        let target_bounds = target_bounds.extend(extend_amount);
3419        let max_target_bounds = max_target_bounds.extend(extend_amount);
3420
3421        let must_place_above_or_below =
3422            if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
3423                laid_out_popovers[menu_ix + 1..]
3424                    .iter()
3425                    .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
3426            } else {
3427                false
3428            };
3429
3430        self.layout_context_menu_aside(
3431            y_flipped,
3432            *menu_bounds,
3433            target_bounds,
3434            max_target_bounds,
3435            max_menu_height,
3436            must_place_above_or_below,
3437            text_hitbox,
3438            viewport_bounds,
3439            window,
3440            cx,
3441        );
3442    }
3443
3444    #[allow(clippy::too_many_arguments)]
3445    fn layout_gutter_menu(
3446        &self,
3447        line_height: Pixels,
3448        text_hitbox: &Hitbox,
3449        content_origin: gpui::Point<Pixels>,
3450        scroll_pixel_position: gpui::Point<Pixels>,
3451        gutter_overshoot: Pixels,
3452        window: &mut Window,
3453        cx: &mut App,
3454    ) {
3455        let editor = self.editor.read(cx);
3456        if !editor.context_menu_visible() {
3457            return;
3458        }
3459        let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
3460            editor.context_menu_origin()
3461        else {
3462            return;
3463        };
3464        // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
3465        // indicator than just a plain first column of the text field.
3466        let target_position = content_origin
3467            + gpui::Point {
3468                x: -gutter_overshoot,
3469                y: gutter_row.next_row().as_f32() * line_height - scroll_pixel_position.y,
3470            };
3471        let min_height = line_height * 3. + POPOVER_Y_PADDING;
3472        let max_height = line_height * 12. + POPOVER_Y_PADDING;
3473        let viewport_bounds =
3474            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3475                right: -Self::SCROLLBAR_WIDTH - MENU_GAP,
3476                ..Default::default()
3477            });
3478        self.layout_popovers_above_or_below_line(
3479            target_position,
3480            line_height,
3481            min_height,
3482            max_height,
3483            text_hitbox,
3484            viewport_bounds,
3485            window,
3486            cx,
3487            move |height, _max_width_for_stable_x, y_flipped, window, cx| {
3488                let mut element = self
3489                    .render_context_menu(line_height, height, y_flipped, window, cx)
3490                    .expect("Visible context menu should always render.");
3491                let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3492                vec![(CursorPopoverType::CodeContextMenu, element, size)]
3493            },
3494        );
3495    }
3496
3497    #[allow(clippy::too_many_arguments)]
3498    fn layout_popovers_above_or_below_line(
3499        &self,
3500        target_position: gpui::Point<Pixels>,
3501        line_height: Pixels,
3502        min_height: Pixels,
3503        max_height: Pixels,
3504        text_hitbox: &Hitbox,
3505        viewport_bounds: Bounds<Pixels>,
3506        window: &mut Window,
3507        cx: &mut App,
3508        make_sized_popovers: impl FnOnce(
3509            Pixels,
3510            Pixels,
3511            bool,
3512            &mut Window,
3513            &mut App,
3514        ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
3515    ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
3516        let text_style = TextStyleRefinement {
3517            line_height: Some(DefiniteLength::Fraction(
3518                BufferLineHeight::Comfortable.value(),
3519            )),
3520            ..Default::default()
3521        };
3522        window.with_text_style(Some(text_style), |window| {
3523            // If the max height won't fit below and there is more space above, put it above the line.
3524            let bottom_y_when_flipped = target_position.y - line_height;
3525            let available_above = bottom_y_when_flipped - text_hitbox.top();
3526            let available_below = text_hitbox.bottom() - target_position.y;
3527            let y_overflows_below = max_height > available_below;
3528            let mut y_flipped = y_overflows_below && available_above > available_below;
3529            let mut height = cmp::min(
3530                max_height,
3531                if y_flipped {
3532                    available_above
3533                } else {
3534                    available_below
3535                },
3536            );
3537
3538            // If the min height doesn't fit within text bounds, instead fit within the window.
3539            if height < min_height {
3540                let available_above = bottom_y_when_flipped;
3541                let available_below = viewport_bounds.bottom() - target_position.y;
3542                if available_below > min_height {
3543                    y_flipped = false;
3544                    height = min_height;
3545                } else if available_above > min_height {
3546                    y_flipped = true;
3547                    height = min_height;
3548                } else if available_above > available_below {
3549                    y_flipped = true;
3550                    height = available_above;
3551                } else {
3552                    y_flipped = false;
3553                    height = available_below;
3554                }
3555            }
3556
3557            let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
3558
3559            // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
3560            // for very narrow windows.
3561            let popovers =
3562                make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
3563            if popovers.is_empty() {
3564                return None;
3565            }
3566
3567            let max_width = popovers
3568                .iter()
3569                .map(|(_, _, size)| size.width)
3570                .max()
3571                .unwrap_or_default();
3572
3573            let mut current_position = gpui::Point {
3574                // Snap the right edge of the list to the right edge of the window if its horizontal bounds
3575                // overflow. Include space for the scrollbar.
3576                x: target_position
3577                    .x
3578                    .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
3579                y: if y_flipped {
3580                    bottom_y_when_flipped
3581                } else {
3582                    target_position.y
3583                },
3584            };
3585
3586            let mut laid_out_popovers = popovers
3587                .into_iter()
3588                .map(|(popover_type, element, size)| {
3589                    if y_flipped {
3590                        current_position.y -= size.height;
3591                    }
3592                    let position = current_position;
3593                    window.defer_draw(element, current_position, 1);
3594                    if !y_flipped {
3595                        current_position.y += size.height + MENU_GAP;
3596                    } else {
3597                        current_position.y -= MENU_GAP;
3598                    }
3599                    (popover_type, Bounds::new(position, size))
3600                })
3601                .collect::<Vec<_>>();
3602
3603            if y_flipped {
3604                laid_out_popovers.reverse();
3605            }
3606
3607            Some((laid_out_popovers, y_flipped))
3608        })
3609    }
3610
3611    #[allow(clippy::too_many_arguments)]
3612    fn layout_context_menu_aside(
3613        &self,
3614        y_flipped: bool,
3615        menu_bounds: Bounds<Pixels>,
3616        target_bounds: Bounds<Pixels>,
3617        max_target_bounds: Bounds<Pixels>,
3618        max_height: Pixels,
3619        must_place_above_or_below: bool,
3620        text_hitbox: &Hitbox,
3621        viewport_bounds: Bounds<Pixels>,
3622        window: &mut Window,
3623        cx: &mut App,
3624    ) {
3625        let available_within_viewport = target_bounds.space_within(&viewport_bounds);
3626        let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
3627            && !must_place_above_or_below
3628        {
3629            let max_width = cmp::min(
3630                available_within_viewport.right - px(1.),
3631                MENU_ASIDE_MAX_WIDTH,
3632            );
3633            let Some(mut aside) = self.render_context_menu_aside(
3634                size(max_width, max_height - POPOVER_Y_PADDING),
3635                window,
3636                cx,
3637            ) else {
3638                return;
3639            };
3640            aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3641            let right_position = point(target_bounds.right(), menu_bounds.origin.y);
3642            Some((aside, right_position))
3643        } else {
3644            let max_size = size(
3645                // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
3646                // won't be needed here.
3647                cmp::min(
3648                    cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
3649                    viewport_bounds.right(),
3650                ),
3651                cmp::min(
3652                    max_height,
3653                    cmp::max(
3654                        available_within_viewport.top,
3655                        available_within_viewport.bottom,
3656                    ),
3657                ) - POPOVER_Y_PADDING,
3658            );
3659            let Some(mut aside) = self.render_context_menu_aside(max_size, window, cx) else {
3660                return;
3661            };
3662            let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3663
3664            let top_position = point(
3665                menu_bounds.origin.x,
3666                target_bounds.top() - actual_size.height,
3667            );
3668            let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
3669
3670            let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
3671                // Prefer to fit on the same side of the line as the menu, then on the other side of
3672                // the line.
3673                if !y_flipped && wanted.height < available.bottom {
3674                    Some(bottom_position)
3675                } else if !y_flipped && wanted.height < available.top {
3676                    Some(top_position)
3677                } else if y_flipped && wanted.height < available.top {
3678                    Some(top_position)
3679                } else if y_flipped && wanted.height < available.bottom {
3680                    Some(bottom_position)
3681                } else {
3682                    None
3683                }
3684            };
3685
3686            // Prefer choosing a direction using max sizes rather than actual size for stability.
3687            let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
3688            let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
3689            let aside_position = fit_within(available_within_text, wanted)
3690                // Fallback: fit max size in window.
3691                .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
3692                // Fallback: fit actual size in window.
3693                .or_else(|| fit_within(available_within_viewport, actual_size));
3694
3695            aside_position.map(|position| (aside, position))
3696        };
3697
3698        // Skip drawing if it doesn't fit anywhere.
3699        if let Some((aside, position)) = positioned_aside {
3700            window.defer_draw(aside, position, 2);
3701        }
3702    }
3703
3704    fn render_context_menu(
3705        &self,
3706        line_height: Pixels,
3707        height: Pixels,
3708        y_flipped: bool,
3709        window: &mut Window,
3710        cx: &mut App,
3711    ) -> Option<AnyElement> {
3712        let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
3713        self.editor.update(cx, |editor, cx| {
3714            editor.render_context_menu(&self.style, max_height_in_lines, y_flipped, window, cx)
3715        })
3716    }
3717
3718    fn render_context_menu_aside(
3719        &self,
3720        max_size: Size<Pixels>,
3721        window: &mut Window,
3722        cx: &mut App,
3723    ) -> Option<AnyElement> {
3724        if max_size.width < px(100.) || max_size.height < px(12.) {
3725            None
3726        } else {
3727            self.editor.update(cx, |editor, cx| {
3728                editor.render_context_menu_aside(max_size, window, cx)
3729            })
3730        }
3731    }
3732
3733    fn layout_mouse_context_menu(
3734        &self,
3735        editor_snapshot: &EditorSnapshot,
3736        visible_range: Range<DisplayRow>,
3737        content_origin: gpui::Point<Pixels>,
3738        window: &mut Window,
3739        cx: &mut App,
3740    ) -> Option<AnyElement> {
3741        let position = self.editor.update(cx, |editor, _cx| {
3742            let visible_start_point = editor.display_to_pixel_point(
3743                DisplayPoint::new(visible_range.start, 0),
3744                editor_snapshot,
3745                window,
3746            )?;
3747            let visible_end_point = editor.display_to_pixel_point(
3748                DisplayPoint::new(visible_range.end, 0),
3749                editor_snapshot,
3750                window,
3751            )?;
3752
3753            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3754            let (source_display_point, position) = match mouse_context_menu.position {
3755                MenuPosition::PinnedToScreen(point) => (None, point),
3756                MenuPosition::PinnedToEditor { source, offset } => {
3757                    let source_display_point = source.to_display_point(editor_snapshot);
3758                    let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
3759                    let position = content_origin + source_point + offset;
3760                    (Some(source_display_point), position)
3761                }
3762            };
3763
3764            let source_included = source_display_point.map_or(true, |source_display_point| {
3765                visible_range
3766                    .to_inclusive()
3767                    .contains(&source_display_point.row())
3768            });
3769            let position_included =
3770                visible_start_point.y <= position.y && position.y <= visible_end_point.y;
3771            if !source_included && !position_included {
3772                None
3773            } else {
3774                Some(position)
3775            }
3776        })?;
3777
3778        let text_style = TextStyleRefinement {
3779            line_height: Some(DefiniteLength::Fraction(
3780                BufferLineHeight::Comfortable.value(),
3781            )),
3782            ..Default::default()
3783        };
3784        window.with_text_style(Some(text_style), |window| {
3785            let mut element = self.editor.update(cx, |editor, _| {
3786                let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3787                let context_menu = mouse_context_menu.context_menu.clone();
3788
3789                Some(
3790                    deferred(
3791                        anchored()
3792                            .position(position)
3793                            .child(context_menu)
3794                            .anchor(Corner::TopLeft)
3795                            .snap_to_window_with_margin(px(8.)),
3796                    )
3797                    .with_priority(1)
3798                    .into_any(),
3799                )
3800            })?;
3801
3802            element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
3803            Some(element)
3804        })
3805    }
3806
3807    #[allow(clippy::too_many_arguments)]
3808    fn layout_hover_popovers(
3809        &self,
3810        snapshot: &EditorSnapshot,
3811        hitbox: &Hitbox,
3812        text_hitbox: &Hitbox,
3813        visible_display_row_range: Range<DisplayRow>,
3814        content_origin: gpui::Point<Pixels>,
3815        scroll_pixel_position: gpui::Point<Pixels>,
3816        line_layouts: &[LineWithInvisibles],
3817        line_height: Pixels,
3818        em_width: Pixels,
3819        window: &mut Window,
3820        cx: &mut App,
3821    ) {
3822        struct MeasuredHoverPopover {
3823            element: AnyElement,
3824            size: Size<Pixels>,
3825            horizontal_offset: Pixels,
3826        }
3827
3828        let max_size = size(
3829            (120. * em_width) // Default size
3830                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
3831                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3832            (16. * line_height) // Default size
3833                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
3834                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3835        );
3836
3837        let hover_popovers = self.editor.update(cx, |editor, cx| {
3838            editor
3839                .hover_state
3840                .render(snapshot, visible_display_row_range.clone(), max_size, cx)
3841        });
3842        let Some((position, hover_popovers)) = hover_popovers else {
3843            return;
3844        };
3845
3846        // This is safe because we check on layout whether the required row is available
3847        let hovered_row_layout =
3848            &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
3849
3850        // Compute Hovered Point
3851        let x =
3852            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
3853        let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
3854        let hovered_point = content_origin + point(x, y);
3855
3856        let mut overall_height = Pixels::ZERO;
3857        let mut measured_hover_popovers = Vec::new();
3858        for mut hover_popover in hover_popovers {
3859            let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
3860            let horizontal_offset =
3861                (text_hitbox.top_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
3862
3863            overall_height += HOVER_POPOVER_GAP + size.height;
3864
3865            measured_hover_popovers.push(MeasuredHoverPopover {
3866                element: hover_popover,
3867                size,
3868                horizontal_offset,
3869            });
3870        }
3871        overall_height += HOVER_POPOVER_GAP;
3872
3873        fn draw_occluder(
3874            width: Pixels,
3875            origin: gpui::Point<Pixels>,
3876            window: &mut Window,
3877            cx: &mut App,
3878        ) {
3879            let mut occlusion = div()
3880                .size_full()
3881                .occlude()
3882                .on_mouse_move(|_, _, cx| cx.stop_propagation())
3883                .into_any_element();
3884            occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
3885            window.defer_draw(occlusion, origin, 2);
3886        }
3887
3888        if hovered_point.y > overall_height {
3889            // There is enough space above. Render popovers above the hovered point
3890            let mut current_y = hovered_point.y;
3891            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3892                let size = popover.size;
3893                let popover_origin = point(
3894                    hovered_point.x + popover.horizontal_offset,
3895                    current_y - size.height,
3896                );
3897
3898                window.defer_draw(popover.element, popover_origin, 2);
3899                if position != itertools::Position::Last {
3900                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
3901                    draw_occluder(size.width, origin, window, cx);
3902                }
3903
3904                current_y = popover_origin.y - HOVER_POPOVER_GAP;
3905            }
3906        } else {
3907            // There is not enough space above. Render popovers below the hovered point
3908            let mut current_y = hovered_point.y + line_height;
3909            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3910                let size = popover.size;
3911                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
3912
3913                window.defer_draw(popover.element, popover_origin, 2);
3914                if position != itertools::Position::Last {
3915                    let origin = point(popover_origin.x, popover_origin.y + size.height);
3916                    draw_occluder(size.width, origin, window, cx);
3917                }
3918
3919                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
3920            }
3921        }
3922    }
3923
3924    #[allow(clippy::too_many_arguments)]
3925    fn layout_diff_hunk_controls(
3926        &self,
3927        row_range: Range<DisplayRow>,
3928        row_infos: &[RowInfo],
3929        text_hitbox: &Hitbox,
3930        position_map: &PositionMap,
3931        newest_cursor_position: Option<DisplayPoint>,
3932        line_height: Pixels,
3933        scroll_pixel_position: gpui::Point<Pixels>,
3934        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
3935        editor: Entity<Editor>,
3936        window: &mut Window,
3937        cx: &mut App,
3938    ) -> Vec<AnyElement> {
3939        let point_for_position = position_map.point_for_position(window.mouse_position());
3940
3941        let mut controls = vec![];
3942
3943        let active_positions = [
3944            Some(point_for_position.previous_valid),
3945            newest_cursor_position,
3946        ];
3947
3948        for (hunk, _) in display_hunks {
3949            if let DisplayDiffHunk::Unfolded {
3950                display_row_range,
3951                multi_buffer_range,
3952                status,
3953                ..
3954            } = &hunk
3955            {
3956                if display_row_range.start < row_range.start
3957                    || display_row_range.start >= row_range.end
3958                {
3959                    continue;
3960                }
3961                let row_ix = (display_row_range.start - row_range.start).0 as usize;
3962                if row_infos[row_ix].diff_status.is_none() {
3963                    continue;
3964                }
3965                if row_infos[row_ix]
3966                    .diff_status
3967                    .is_some_and(|status| status.is_added())
3968                    && !status.is_added()
3969                {
3970                    continue;
3971                }
3972                if active_positions
3973                    .iter()
3974                    .any(|p| p.map_or(false, |p| display_row_range.contains(&p.row())))
3975                {
3976                    let y = display_row_range.start.as_f32() * line_height
3977                        + text_hitbox.bounds.top()
3978                        - scroll_pixel_position.y;
3979
3980                    let mut element = diff_hunk_controls(
3981                        display_row_range.start.0,
3982                        status,
3983                        multi_buffer_range.clone(),
3984                        line_height,
3985                        &editor,
3986                        cx,
3987                    );
3988                    let size =
3989                        element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
3990
3991                    let x = text_hitbox.bounds.right()
3992                        - self.style.scrollbar_width
3993                        - px(10.)
3994                        - size.width;
3995
3996                    window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
3997                        element.prepaint(window, cx)
3998                    });
3999                    controls.push(element);
4000                }
4001            }
4002        }
4003
4004        controls
4005    }
4006
4007    #[allow(clippy::too_many_arguments)]
4008    fn layout_signature_help(
4009        &self,
4010        hitbox: &Hitbox,
4011        content_origin: gpui::Point<Pixels>,
4012        scroll_pixel_position: gpui::Point<Pixels>,
4013        newest_selection_head: Option<DisplayPoint>,
4014        start_row: DisplayRow,
4015        line_layouts: &[LineWithInvisibles],
4016        line_height: Pixels,
4017        em_width: Pixels,
4018        window: &mut Window,
4019        cx: &mut App,
4020    ) {
4021        if !self.editor.focus_handle(cx).is_focused(window) {
4022            return;
4023        }
4024        let Some(newest_selection_head) = newest_selection_head else {
4025            return;
4026        };
4027        let selection_row = newest_selection_head.row();
4028        if selection_row < start_row {
4029            return;
4030        }
4031        let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
4032        else {
4033            return;
4034        };
4035
4036        let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
4037            - scroll_pixel_position.x
4038            + content_origin.x;
4039        let start_y =
4040            selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
4041
4042        let max_size = size(
4043            (120. * em_width) // Default size
4044                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4045                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4046            (16. * line_height) // Default size
4047                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4048                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4049        );
4050
4051        let maybe_element = self.editor.update(cx, |editor, cx| {
4052            if let Some(popover) = editor.signature_help_state.popover_mut() {
4053                let element = popover.render(max_size, cx);
4054                Some(element)
4055            } else {
4056                None
4057            }
4058        });
4059        if let Some(mut element) = maybe_element {
4060            let window_size = window.viewport_size();
4061            let size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
4062            let mut point = point(start_x, start_y - size.height);
4063
4064            // Adjusting to ensure the popover does not overflow in the X-axis direction.
4065            if point.x + size.width >= window_size.width {
4066                point.x = window_size.width - size.width;
4067            }
4068
4069            window.defer_draw(element, point, 1)
4070        }
4071    }
4072
4073    fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
4074        window.paint_layer(layout.hitbox.bounds, |window| {
4075            let scroll_top = layout.position_map.snapshot.scroll_position().y;
4076            let gutter_bg = cx.theme().colors().editor_gutter_background;
4077            window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
4078            window.paint_quad(fill(
4079                layout.position_map.text_hitbox.bounds,
4080                self.style.background,
4081            ));
4082
4083            if let EditorMode::Full = layout.mode {
4084                let mut active_rows = layout.active_rows.iter().peekable();
4085                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
4086                    let mut end_row = start_row.0;
4087                    while active_rows
4088                        .peek()
4089                        .map_or(false, |(active_row, has_selection)| {
4090                            active_row.0 == end_row + 1
4091                                && *has_selection == contains_non_empty_selection
4092                        })
4093                    {
4094                        active_rows.next().unwrap();
4095                        end_row += 1;
4096                    }
4097
4098                    if !contains_non_empty_selection {
4099                        let highlight_h_range =
4100                            match layout.position_map.snapshot.current_line_highlight {
4101                                CurrentLineHighlight::Gutter => Some(Range {
4102                                    start: layout.hitbox.left(),
4103                                    end: layout.gutter_hitbox.right(),
4104                                }),
4105                                CurrentLineHighlight::Line => Some(Range {
4106                                    start: layout.position_map.text_hitbox.bounds.left(),
4107                                    end: layout.position_map.text_hitbox.bounds.right(),
4108                                }),
4109                                CurrentLineHighlight::All => Some(Range {
4110                                    start: layout.hitbox.left(),
4111                                    end: layout.hitbox.right(),
4112                                }),
4113                                CurrentLineHighlight::None => None,
4114                            };
4115                        if let Some(range) = highlight_h_range {
4116                            let active_line_bg = cx.theme().colors().editor_active_line_background;
4117                            let bounds = Bounds {
4118                                origin: point(
4119                                    range.start,
4120                                    layout.hitbox.origin.y
4121                                        + (start_row.as_f32() - scroll_top)
4122                                            * layout.position_map.line_height,
4123                                ),
4124                                size: size(
4125                                    range.end - range.start,
4126                                    layout.position_map.line_height
4127                                        * (end_row - start_row.0 + 1) as f32,
4128                                ),
4129                            };
4130                            window.paint_quad(fill(bounds, active_line_bg));
4131                        }
4132                    }
4133                }
4134
4135                let mut paint_highlight =
4136                    |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
4137                        let origin = point(
4138                            layout.hitbox.origin.x,
4139                            layout.hitbox.origin.y
4140                                + (highlight_row_start.as_f32() - scroll_top)
4141                                    * layout.position_map.line_height,
4142                        );
4143                        let size = size(
4144                            layout.hitbox.size.width,
4145                            layout.position_map.line_height
4146                                * highlight_row_end.next_row().minus(highlight_row_start) as f32,
4147                        );
4148                        window.paint_quad(fill(Bounds { origin, size }, color));
4149                    };
4150
4151                let mut current_paint: Option<(gpui::Background, Range<DisplayRow>)> = None;
4152                for (&new_row, &new_background) in &layout.highlighted_rows {
4153                    match &mut current_paint {
4154                        Some((current_background, current_range)) => {
4155                            let current_background = *current_background;
4156                            let new_range_started = current_background != new_background
4157                                || current_range.end.next_row() != new_row;
4158                            if new_range_started {
4159                                paint_highlight(
4160                                    current_range.start,
4161                                    current_range.end,
4162                                    current_background,
4163                                );
4164                                current_paint = Some((new_background, new_row..new_row));
4165                                continue;
4166                            } else {
4167                                current_range.end = current_range.end.next_row();
4168                            }
4169                        }
4170                        None => current_paint = Some((new_background, new_row..new_row)),
4171                    };
4172                }
4173                if let Some((color, range)) = current_paint {
4174                    paint_highlight(range.start, range.end, color);
4175                }
4176
4177                let scroll_left =
4178                    layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
4179
4180                for (wrap_position, active) in layout.wrap_guides.iter() {
4181                    let x = (layout.position_map.text_hitbox.origin.x
4182                        + *wrap_position
4183                        + layout.position_map.em_width / 2.)
4184                        - scroll_left;
4185
4186                    let show_scrollbars = {
4187                        let (scrollbar_x, scrollbar_y) = &layout.scrollbars_layout.as_xy();
4188
4189                        scrollbar_x.as_ref().map_or(false, |sx| sx.visible)
4190                            || scrollbar_y.as_ref().map_or(false, |sy| sy.visible)
4191                    };
4192
4193                    if x < layout.position_map.text_hitbox.origin.x
4194                        || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
4195                    {
4196                        continue;
4197                    }
4198
4199                    let color = if *active {
4200                        cx.theme().colors().editor_active_wrap_guide
4201                    } else {
4202                        cx.theme().colors().editor_wrap_guide
4203                    };
4204                    window.paint_quad(fill(
4205                        Bounds {
4206                            origin: point(x, layout.position_map.text_hitbox.origin.y),
4207                            size: size(px(1.), layout.position_map.text_hitbox.size.height),
4208                        },
4209                        color,
4210                    ));
4211                }
4212            }
4213        })
4214    }
4215
4216    fn paint_indent_guides(
4217        &mut self,
4218        layout: &mut EditorLayout,
4219        window: &mut Window,
4220        cx: &mut App,
4221    ) {
4222        let Some(indent_guides) = &layout.indent_guides else {
4223            return;
4224        };
4225
4226        let faded_color = |color: Hsla, alpha: f32| {
4227            let mut faded = color;
4228            faded.a = alpha;
4229            faded
4230        };
4231
4232        for indent_guide in indent_guides {
4233            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
4234            let settings = indent_guide.settings;
4235
4236            // TODO fixed for now, expose them through themes later
4237            const INDENT_AWARE_ALPHA: f32 = 0.2;
4238            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
4239            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
4240            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
4241
4242            let line_color = match (settings.coloring, indent_guide.active) {
4243                (IndentGuideColoring::Disabled, _) => None,
4244                (IndentGuideColoring::Fixed, false) => {
4245                    Some(cx.theme().colors().editor_indent_guide)
4246                }
4247                (IndentGuideColoring::Fixed, true) => {
4248                    Some(cx.theme().colors().editor_indent_guide_active)
4249                }
4250                (IndentGuideColoring::IndentAware, false) => {
4251                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
4252                }
4253                (IndentGuideColoring::IndentAware, true) => {
4254                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
4255                }
4256            };
4257
4258            let background_color = match (settings.background_coloring, indent_guide.active) {
4259                (IndentGuideBackgroundColoring::Disabled, _) => None,
4260                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
4261                    indent_accent_colors,
4262                    INDENT_AWARE_BACKGROUND_ALPHA,
4263                )),
4264                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
4265                    indent_accent_colors,
4266                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
4267                )),
4268            };
4269
4270            let requested_line_width = if indent_guide.active {
4271                settings.active_line_width
4272            } else {
4273                settings.line_width
4274            }
4275            .clamp(1, 10);
4276            let mut line_indicator_width = 0.;
4277            if let Some(color) = line_color {
4278                window.paint_quad(fill(
4279                    Bounds {
4280                        origin: indent_guide.origin,
4281                        size: size(px(requested_line_width as f32), indent_guide.length),
4282                    },
4283                    color,
4284                ));
4285                line_indicator_width = requested_line_width as f32;
4286            }
4287
4288            if let Some(color) = background_color {
4289                let width = indent_guide.single_indent_width - px(line_indicator_width);
4290                window.paint_quad(fill(
4291                    Bounds {
4292                        origin: point(
4293                            indent_guide.origin.x + px(line_indicator_width),
4294                            indent_guide.origin.y,
4295                        ),
4296                        size: size(width, indent_guide.length),
4297                    },
4298                    color,
4299                ));
4300            }
4301        }
4302    }
4303
4304    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4305        let is_singleton = self.editor.read(cx).is_singleton(cx);
4306
4307        let line_height = layout.position_map.line_height;
4308        window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
4309
4310        for LineNumberLayout {
4311            shaped_line,
4312            hitbox,
4313            display_row,
4314        } in layout.line_numbers.values()
4315        {
4316            let Some(hitbox) = hitbox else {
4317                continue;
4318            };
4319
4320            let is_active = layout.active_rows.contains_key(&display_row);
4321
4322            let color = if is_active {
4323                cx.theme().colors().editor_active_line_number
4324            } else if !is_singleton && hitbox.is_hovered(window) {
4325                cx.theme().colors().editor_hover_line_number
4326            } else {
4327                cx.theme().colors().editor_line_number
4328            };
4329
4330            let Some(line) = self
4331                .shape_line_number(shaped_line.text.clone(), color, window)
4332                .log_err()
4333            else {
4334                continue;
4335            };
4336            let Some(()) = line.paint(hitbox.origin, line_height, window, cx).log_err() else {
4337                continue;
4338            };
4339            // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
4340            // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
4341            if is_singleton {
4342                window.set_cursor_style(CursorStyle::IBeam, &hitbox);
4343            } else {
4344                window.set_cursor_style(CursorStyle::PointingHand, &hitbox);
4345            }
4346        }
4347    }
4348
4349    fn paint_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4350        let is_light = cx.theme().appearance().is_light();
4351
4352        if layout.display_hunks.is_empty() {
4353            return;
4354        }
4355
4356        let line_height = layout.position_map.line_height;
4357        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4358            for (hunk, hitbox) in &layout.display_hunks {
4359                let hunk_to_paint = match hunk {
4360                    DisplayDiffHunk::Folded { .. } => {
4361                        let hunk_bounds = Self::diff_hunk_bounds(
4362                            &layout.position_map.snapshot,
4363                            line_height,
4364                            layout.gutter_hitbox.bounds,
4365                            hunk,
4366                        );
4367                        Some((
4368                            hunk_bounds,
4369                            cx.theme().colors().version_control_modified,
4370                            Corners::all(px(0.)),
4371                            DiffHunkStatus::modified_none(),
4372                        ))
4373                    }
4374                    DisplayDiffHunk::Unfolded {
4375                        status,
4376                        display_row_range,
4377                        ..
4378                    } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
4379                        DiffHunkStatusKind::Added => (
4380                            hunk_hitbox.bounds,
4381                            cx.theme().colors().version_control_added,
4382                            Corners::all(px(0.)),
4383                            *status,
4384                        ),
4385                        DiffHunkStatusKind::Modified => (
4386                            hunk_hitbox.bounds,
4387                            cx.theme().colors().version_control_modified,
4388                            Corners::all(px(0.)),
4389                            *status,
4390                        ),
4391                        DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
4392                            hunk_hitbox.bounds,
4393                            cx.theme().colors().version_control_deleted,
4394                            Corners::all(px(0.)),
4395                            *status,
4396                        ),
4397                        DiffHunkStatusKind::Deleted => (
4398                            Bounds::new(
4399                                point(
4400                                    hunk_hitbox.origin.x - hunk_hitbox.size.width,
4401                                    hunk_hitbox.origin.y,
4402                                ),
4403                                size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
4404                            ),
4405                            cx.theme().colors().version_control_deleted,
4406                            Corners::all(1. * line_height),
4407                            *status,
4408                        ),
4409                    }),
4410                };
4411
4412                if let Some((hunk_bounds, mut background_color, corner_radii, secondary_status)) =
4413                    hunk_to_paint
4414                {
4415                    if secondary_status.has_secondary_hunk() {
4416                        background_color =
4417                            background_color.opacity(if is_light { 0.2 } else { 0.32 });
4418                    }
4419                    window.paint_quad(quad(
4420                        hunk_bounds,
4421                        corner_radii,
4422                        background_color,
4423                        Edges::default(),
4424                        transparent_black(),
4425                    ));
4426                }
4427            }
4428        });
4429    }
4430
4431    fn diff_hunk_bounds(
4432        snapshot: &EditorSnapshot,
4433        line_height: Pixels,
4434        gutter_bounds: Bounds<Pixels>,
4435        hunk: &DisplayDiffHunk,
4436    ) -> Bounds<Pixels> {
4437        let scroll_position = snapshot.scroll_position();
4438        let scroll_top = scroll_position.y * line_height;
4439        let gutter_strip_width = (0.275 * line_height).floor();
4440
4441        match hunk {
4442            DisplayDiffHunk::Folded { display_row, .. } => {
4443                let start_y = display_row.as_f32() * line_height - scroll_top;
4444                let end_y = start_y + line_height;
4445                let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4446                let highlight_size = size(gutter_strip_width, end_y - start_y);
4447                Bounds::new(highlight_origin, highlight_size)
4448            }
4449            DisplayDiffHunk::Unfolded {
4450                display_row_range,
4451                status,
4452                ..
4453            } => {
4454                if status.is_deleted() && display_row_range.is_empty() {
4455                    let row = display_row_range.start;
4456
4457                    let offset = line_height / 2.;
4458                    let start_y = row.as_f32() * line_height - offset - scroll_top;
4459                    let end_y = start_y + line_height;
4460
4461                    let width = (0.35 * line_height).floor();
4462                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4463                    let highlight_size = size(width, end_y - start_y);
4464                    Bounds::new(highlight_origin, highlight_size)
4465                } else {
4466                    let start_row = display_row_range.start;
4467                    let end_row = display_row_range.end;
4468                    // If we're in a multibuffer, row range span might include an
4469                    // excerpt header, so if we were to draw the marker straight away,
4470                    // the hunk might include the rows of that header.
4471                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
4472                    // Instead, we simply check whether the range we're dealing with includes
4473                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
4474                    let end_row_in_current_excerpt = snapshot
4475                        .blocks_in_range(start_row..end_row)
4476                        .find_map(|(start_row, block)| {
4477                            if matches!(block, Block::ExcerptBoundary { .. }) {
4478                                Some(start_row)
4479                            } else {
4480                                None
4481                            }
4482                        })
4483                        .unwrap_or(end_row);
4484
4485                    let start_y = start_row.as_f32() * line_height - scroll_top;
4486                    let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
4487
4488                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4489                    let highlight_size = size(gutter_strip_width, end_y - start_y);
4490                    Bounds::new(highlight_origin, highlight_size)
4491                }
4492            }
4493        }
4494    }
4495
4496    fn paint_gutter_indicators(
4497        &self,
4498        layout: &mut EditorLayout,
4499        window: &mut Window,
4500        cx: &mut App,
4501    ) {
4502        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4503            window.with_element_namespace("crease_toggles", |window| {
4504                for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
4505                    crease_toggle.paint(window, cx);
4506                }
4507            });
4508
4509            for test_indicator in layout.test_indicators.iter_mut() {
4510                test_indicator.paint(window, cx);
4511            }
4512
4513            if let Some(indicator) = layout.code_actions_indicator.as_mut() {
4514                indicator.paint(window, cx);
4515            }
4516        });
4517    }
4518
4519    fn paint_gutter_highlights(
4520        &self,
4521        layout: &mut EditorLayout,
4522        window: &mut Window,
4523        cx: &mut App,
4524    ) {
4525        for (_, hunk_hitbox) in &layout.display_hunks {
4526            if let Some(hunk_hitbox) = hunk_hitbox {
4527                if !self
4528                    .editor
4529                    .read(cx)
4530                    .buffer()
4531                    .read(cx)
4532                    .all_diff_hunks_expanded()
4533                {
4534                    window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
4535                }
4536            }
4537        }
4538
4539        let show_git_gutter = layout
4540            .position_map
4541            .snapshot
4542            .show_git_diff_gutter
4543            .unwrap_or_else(|| {
4544                matches!(
4545                    ProjectSettings::get_global(cx).git.git_gutter,
4546                    Some(GitGutterSetting::TrackedFiles)
4547                )
4548            });
4549        if show_git_gutter {
4550            Self::paint_diff_hunks(layout, window, cx)
4551        }
4552
4553        let highlight_width = 0.275 * layout.position_map.line_height;
4554        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
4555        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4556            for (range, color) in &layout.highlighted_gutter_ranges {
4557                let start_row = if range.start.row() < layout.visible_display_row_range.start {
4558                    layout.visible_display_row_range.start - DisplayRow(1)
4559                } else {
4560                    range.start.row()
4561                };
4562                let end_row = if range.end.row() > layout.visible_display_row_range.end {
4563                    layout.visible_display_row_range.end + DisplayRow(1)
4564                } else {
4565                    range.end.row()
4566                };
4567
4568                let start_y = layout.gutter_hitbox.top()
4569                    + start_row.0 as f32 * layout.position_map.line_height
4570                    - layout.position_map.scroll_pixel_position.y;
4571                let end_y = layout.gutter_hitbox.top()
4572                    + (end_row.0 + 1) as f32 * layout.position_map.line_height
4573                    - layout.position_map.scroll_pixel_position.y;
4574                let bounds = Bounds::from_corners(
4575                    point(layout.gutter_hitbox.left(), start_y),
4576                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
4577                );
4578                window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
4579            }
4580        });
4581    }
4582
4583    fn paint_blamed_display_rows(
4584        &self,
4585        layout: &mut EditorLayout,
4586        window: &mut Window,
4587        cx: &mut App,
4588    ) {
4589        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
4590            return;
4591        };
4592
4593        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4594            for mut blame_element in blamed_display_rows.into_iter() {
4595                blame_element.paint(window, cx);
4596            }
4597        })
4598    }
4599
4600    fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4601        window.with_content_mask(
4602            Some(ContentMask {
4603                bounds: layout.position_map.text_hitbox.bounds,
4604            }),
4605            |window| {
4606                let cursor_style = if self
4607                    .editor
4608                    .read(cx)
4609                    .hovered_link_state
4610                    .as_ref()
4611                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
4612                {
4613                    CursorStyle::PointingHand
4614                } else {
4615                    CursorStyle::IBeam
4616                };
4617                window.set_cursor_style(cursor_style, &layout.position_map.text_hitbox);
4618
4619                let invisible_display_ranges = self.paint_highlights(layout, window);
4620                self.paint_lines(&invisible_display_ranges, layout, window, cx);
4621                self.paint_redactions(layout, window);
4622                self.paint_cursors(layout, window, cx);
4623                self.paint_inline_diagnostics(layout, window, cx);
4624                self.paint_inline_blame(layout, window, cx);
4625                self.paint_diff_hunk_controls(layout, window, cx);
4626                window.with_element_namespace("crease_trailers", |window| {
4627                    for trailer in layout.crease_trailers.iter_mut().flatten() {
4628                        trailer.element.paint(window, cx);
4629                    }
4630                });
4631            },
4632        )
4633    }
4634
4635    fn paint_highlights(
4636        &mut self,
4637        layout: &mut EditorLayout,
4638        window: &mut Window,
4639    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
4640        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4641            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
4642            let line_end_overshoot = 0.15 * layout.position_map.line_height;
4643            for (range, color) in &layout.highlighted_ranges {
4644                self.paint_highlighted_range(
4645                    range.clone(),
4646                    *color,
4647                    Pixels::ZERO,
4648                    line_end_overshoot,
4649                    layout,
4650                    window,
4651                );
4652            }
4653
4654            let corner_radius = 0.15 * layout.position_map.line_height;
4655
4656            for (player_color, selections) in &layout.selections {
4657                for selection in selections.iter() {
4658                    self.paint_highlighted_range(
4659                        selection.range.clone(),
4660                        player_color.selection,
4661                        corner_radius,
4662                        corner_radius * 2.,
4663                        layout,
4664                        window,
4665                    );
4666
4667                    if selection.is_local && !selection.range.is_empty() {
4668                        invisible_display_ranges.push(selection.range.clone());
4669                    }
4670                }
4671            }
4672            invisible_display_ranges
4673        })
4674    }
4675
4676    fn paint_lines(
4677        &mut self,
4678        invisible_display_ranges: &[Range<DisplayPoint>],
4679        layout: &mut EditorLayout,
4680        window: &mut Window,
4681        cx: &mut App,
4682    ) {
4683        let whitespace_setting = self
4684            .editor
4685            .read(cx)
4686            .buffer
4687            .read(cx)
4688            .settings_at(0, cx)
4689            .show_whitespaces;
4690
4691        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
4692            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
4693            line_with_invisibles.draw(
4694                layout,
4695                row,
4696                layout.content_origin,
4697                whitespace_setting,
4698                invisible_display_ranges,
4699                window,
4700                cx,
4701            )
4702        }
4703
4704        for line_element in &mut layout.line_elements {
4705            line_element.paint(window, cx);
4706        }
4707    }
4708
4709    fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
4710        if layout.redacted_ranges.is_empty() {
4711            return;
4712        }
4713
4714        let line_end_overshoot = layout.line_end_overshoot();
4715
4716        // A softer than perfect black
4717        let redaction_color = gpui::rgb(0x0e1111);
4718
4719        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4720            for range in layout.redacted_ranges.iter() {
4721                self.paint_highlighted_range(
4722                    range.clone(),
4723                    redaction_color.into(),
4724                    Pixels::ZERO,
4725                    line_end_overshoot,
4726                    layout,
4727                    window,
4728                );
4729            }
4730        });
4731    }
4732
4733    fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4734        for cursor in &mut layout.visible_cursors {
4735            cursor.paint(layout.content_origin, window, cx);
4736        }
4737    }
4738
4739    fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4740        let (scrollbar_x, scrollbar_y) = layout.scrollbars_layout.as_xy();
4741
4742        if let Some(scrollbar_layout) = scrollbar_x {
4743            let hitbox = scrollbar_layout.hitbox.clone();
4744            let text_unit_size = scrollbar_layout.text_unit_size;
4745            let visible_range = scrollbar_layout.visible_range.clone();
4746            let thumb_bounds = scrollbar_layout.thumb_bounds();
4747
4748            if scrollbar_layout.visible {
4749                window.paint_layer(hitbox.bounds, |window| {
4750                    window.paint_quad(quad(
4751                        hitbox.bounds,
4752                        Corners::default(),
4753                        cx.theme().colors().scrollbar_track_background,
4754                        Edges {
4755                            top: Pixels::ZERO,
4756                            right: Pixels::ZERO,
4757                            bottom: Pixels::ZERO,
4758                            left: Pixels::ZERO,
4759                        },
4760                        cx.theme().colors().scrollbar_track_border,
4761                    ));
4762
4763                    window.paint_quad(quad(
4764                        thumb_bounds,
4765                        Corners::default(),
4766                        cx.theme().colors().scrollbar_thumb_background,
4767                        Edges {
4768                            top: Pixels::ZERO,
4769                            right: Pixels::ZERO,
4770                            bottom: Pixels::ZERO,
4771                            left: ScrollbarLayout::BORDER_WIDTH,
4772                        },
4773                        cx.theme().colors().scrollbar_thumb_border,
4774                    ));
4775                })
4776            }
4777
4778            window.set_cursor_style(CursorStyle::Arrow, &hitbox);
4779
4780            window.on_mouse_event({
4781                let editor = self.editor.clone();
4782
4783                // there may be a way to avoid this clone
4784                let hitbox = hitbox.clone();
4785
4786                let mut mouse_position = window.mouse_position();
4787                move |event: &MouseMoveEvent, phase, window, cx| {
4788                    if phase == DispatchPhase::Capture {
4789                        return;
4790                    }
4791
4792                    editor.update(cx, |editor, cx| {
4793                        if event.pressed_button == Some(MouseButton::Left)
4794                            && editor
4795                                .scroll_manager
4796                                .is_dragging_scrollbar(Axis::Horizontal)
4797                        {
4798                            let x = mouse_position.x;
4799                            let new_x = event.position.x;
4800                            if (hitbox.left()..hitbox.right()).contains(&x) {
4801                                let mut position = editor.scroll_position(cx);
4802
4803                                position.x += (new_x - x) / text_unit_size;
4804                                if position.x < 0.0 {
4805                                    position.x = 0.0;
4806                                }
4807                                editor.set_scroll_position(position, window, cx);
4808                            }
4809
4810                            cx.stop_propagation();
4811                        } else {
4812                            editor.scroll_manager.set_is_dragging_scrollbar(
4813                                Axis::Horizontal,
4814                                false,
4815                                cx,
4816                            );
4817
4818                            if hitbox.is_hovered(window) {
4819                                editor.scroll_manager.show_scrollbar(window, cx);
4820                            }
4821                        }
4822                        mouse_position = event.position;
4823                    })
4824                }
4825            });
4826
4827            if self
4828                .editor
4829                .read(cx)
4830                .scroll_manager
4831                .is_dragging_scrollbar(Axis::Horizontal)
4832            {
4833                window.on_mouse_event({
4834                    let editor = self.editor.clone();
4835                    move |_: &MouseUpEvent, phase, _, cx| {
4836                        if phase == DispatchPhase::Capture {
4837                            return;
4838                        }
4839
4840                        editor.update(cx, |editor, cx| {
4841                            editor.scroll_manager.set_is_dragging_scrollbar(
4842                                Axis::Horizontal,
4843                                false,
4844                                cx,
4845                            );
4846                            cx.stop_propagation();
4847                        });
4848                    }
4849                });
4850            } else {
4851                window.on_mouse_event({
4852                    let editor = self.editor.clone();
4853
4854                    move |event: &MouseDownEvent, phase, window, cx| {
4855                        if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
4856                            return;
4857                        }
4858
4859                        editor.update(cx, |editor, cx| {
4860                            editor.scroll_manager.set_is_dragging_scrollbar(
4861                                Axis::Horizontal,
4862                                true,
4863                                cx,
4864                            );
4865
4866                            let x = event.position.x;
4867
4868                            if x < thumb_bounds.left() || thumb_bounds.right() < x {
4869                                let center_row =
4870                                    ((x - hitbox.left()) / text_unit_size).round() as u32;
4871                                let top_row = center_row.saturating_sub(
4872                                    (visible_range.end - visible_range.start) as u32 / 2,
4873                                );
4874
4875                                let mut position = editor.scroll_position(cx);
4876                                position.x = top_row as f32;
4877
4878                                editor.set_scroll_position(position, window, cx);
4879                            } else {
4880                                editor.scroll_manager.show_scrollbar(window, cx);
4881                            }
4882
4883                            cx.stop_propagation();
4884                        });
4885                    }
4886                });
4887            }
4888        }
4889
4890        if let Some(scrollbar_layout) = scrollbar_y {
4891            let hitbox = scrollbar_layout.hitbox.clone();
4892            let text_unit_size = scrollbar_layout.text_unit_size;
4893            let visible_range = scrollbar_layout.visible_range.clone();
4894            let thumb_bounds = scrollbar_layout.thumb_bounds();
4895
4896            if scrollbar_layout.visible {
4897                window.paint_layer(hitbox.bounds, |window| {
4898                    window.paint_quad(quad(
4899                        hitbox.bounds,
4900                        Corners::default(),
4901                        cx.theme().colors().scrollbar_track_background,
4902                        Edges {
4903                            top: Pixels::ZERO,
4904                            right: Pixels::ZERO,
4905                            bottom: Pixels::ZERO,
4906                            left: ScrollbarLayout::BORDER_WIDTH,
4907                        },
4908                        cx.theme().colors().scrollbar_track_border,
4909                    ));
4910
4911                    let fast_markers =
4912                        self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
4913                    // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
4914                    self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx);
4915
4916                    let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
4917                    for marker in markers.iter().chain(&fast_markers) {
4918                        let mut marker = marker.clone();
4919                        marker.bounds.origin += hitbox.origin;
4920                        window.paint_quad(marker);
4921                    }
4922
4923                    window.paint_quad(quad(
4924                        thumb_bounds,
4925                        Corners::default(),
4926                        cx.theme().colors().scrollbar_thumb_background,
4927                        Edges {
4928                            top: Pixels::ZERO,
4929                            right: Pixels::ZERO,
4930                            bottom: Pixels::ZERO,
4931                            left: ScrollbarLayout::BORDER_WIDTH,
4932                        },
4933                        cx.theme().colors().scrollbar_thumb_border,
4934                    ));
4935                });
4936            }
4937
4938            window.set_cursor_style(CursorStyle::Arrow, &hitbox);
4939
4940            window.on_mouse_event({
4941                let editor = self.editor.clone();
4942
4943                let hitbox = hitbox.clone();
4944
4945                let mut mouse_position = window.mouse_position();
4946                move |event: &MouseMoveEvent, phase, window, cx| {
4947                    if phase == DispatchPhase::Capture {
4948                        return;
4949                    }
4950
4951                    editor.update(cx, |editor, cx| {
4952                        if event.pressed_button == Some(MouseButton::Left)
4953                            && editor.scroll_manager.is_dragging_scrollbar(Axis::Vertical)
4954                        {
4955                            let y = mouse_position.y;
4956                            let new_y = event.position.y;
4957                            if (hitbox.top()..hitbox.bottom()).contains(&y) {
4958                                let mut position = editor.scroll_position(cx);
4959                                position.y += (new_y - y) / text_unit_size;
4960                                if position.y < 0.0 {
4961                                    position.y = 0.0;
4962                                }
4963                                editor.set_scroll_position(position, window, cx);
4964                            }
4965                        } else {
4966                            editor.scroll_manager.set_is_dragging_scrollbar(
4967                                Axis::Vertical,
4968                                false,
4969                                cx,
4970                            );
4971
4972                            if hitbox.is_hovered(window) {
4973                                editor.scroll_manager.show_scrollbar(window, cx);
4974                            }
4975                        }
4976                        mouse_position = event.position;
4977                    })
4978                }
4979            });
4980
4981            if self
4982                .editor
4983                .read(cx)
4984                .scroll_manager
4985                .is_dragging_scrollbar(Axis::Vertical)
4986            {
4987                window.on_mouse_event({
4988                    let editor = self.editor.clone();
4989                    move |_: &MouseUpEvent, phase, _, cx| {
4990                        if phase == DispatchPhase::Capture {
4991                            return;
4992                        }
4993
4994                        editor.update(cx, |editor, cx| {
4995                            editor.scroll_manager.set_is_dragging_scrollbar(
4996                                Axis::Vertical,
4997                                false,
4998                                cx,
4999                            );
5000                            cx.stop_propagation();
5001                        });
5002                    }
5003                });
5004            } else {
5005                window.on_mouse_event({
5006                    let editor = self.editor.clone();
5007
5008                    move |event: &MouseDownEvent, phase, window, cx| {
5009                        if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
5010                            return;
5011                        }
5012
5013                        editor.update(cx, |editor, cx| {
5014                            editor.scroll_manager.set_is_dragging_scrollbar(
5015                                Axis::Vertical,
5016                                true,
5017                                cx,
5018                            );
5019
5020                            let y = event.position.y;
5021                            if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
5022                                let center_row =
5023                                    ((y - hitbox.top()) / text_unit_size).round() as u32;
5024                                let top_row = center_row.saturating_sub(
5025                                    (visible_range.end - visible_range.start) as u32 / 2,
5026                                );
5027                                let mut position = editor.scroll_position(cx);
5028                                position.y = top_row as f32;
5029                                editor.set_scroll_position(position, window, cx);
5030                            } else {
5031                                editor.scroll_manager.show_scrollbar(window, cx);
5032                            }
5033
5034                            cx.stop_propagation();
5035                        });
5036                    }
5037                });
5038            }
5039        }
5040    }
5041
5042    fn collect_fast_scrollbar_markers(
5043        &self,
5044        layout: &EditorLayout,
5045        scrollbar_layout: &ScrollbarLayout,
5046        cx: &mut App,
5047    ) -> Vec<PaintQuad> {
5048        const LIMIT: usize = 100;
5049        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
5050            return vec![];
5051        }
5052        let cursor_ranges = layout
5053            .cursors
5054            .iter()
5055            .map(|(point, color)| ColoredRange {
5056                start: point.row(),
5057                end: point.row(),
5058                color: *color,
5059            })
5060            .collect_vec();
5061        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
5062    }
5063
5064    fn refresh_slow_scrollbar_markers(
5065        &self,
5066        layout: &EditorLayout,
5067        scrollbar_layout: &ScrollbarLayout,
5068        window: &mut Window,
5069        cx: &mut App,
5070    ) {
5071        self.editor.update(cx, |editor, cx| {
5072            if !editor.is_singleton(cx)
5073                || !editor
5074                    .scrollbar_marker_state
5075                    .should_refresh(scrollbar_layout.hitbox.size)
5076            {
5077                return;
5078            }
5079
5080            let scrollbar_layout = scrollbar_layout.clone();
5081            let background_highlights = editor.background_highlights.clone();
5082            let snapshot = layout.position_map.snapshot.clone();
5083            let theme = cx.theme().clone();
5084            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
5085
5086            editor.scrollbar_marker_state.dirty = false;
5087            editor.scrollbar_marker_state.pending_refresh =
5088                Some(cx.spawn_in(window, |editor, mut cx| async move {
5089                    let scrollbar_size = scrollbar_layout.hitbox.size;
5090                    let scrollbar_markers = cx
5091                        .background_spawn(async move {
5092                            let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
5093                            let mut marker_quads = Vec::new();
5094                            if scrollbar_settings.git_diff {
5095                                let marker_row_ranges =
5096                                    snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
5097                                        let start_display_row =
5098                                            MultiBufferPoint::new(hunk.row_range.start.0, 0)
5099                                                .to_display_point(&snapshot.display_snapshot)
5100                                                .row();
5101                                        let mut end_display_row =
5102                                            MultiBufferPoint::new(hunk.row_range.end.0, 0)
5103                                                .to_display_point(&snapshot.display_snapshot)
5104                                                .row();
5105                                        if end_display_row != start_display_row {
5106                                            end_display_row.0 -= 1;
5107                                        }
5108                                        let color = match &hunk.status().kind {
5109                                            DiffHunkStatusKind::Added => {
5110                                                theme.colors().version_control_added
5111                                            }
5112                                            DiffHunkStatusKind::Modified => {
5113                                                theme.colors().version_control_modified
5114                                            }
5115                                            DiffHunkStatusKind::Deleted => {
5116                                                theme.colors().version_control_deleted
5117                                            }
5118                                        };
5119                                        ColoredRange {
5120                                            start: start_display_row,
5121                                            end: end_display_row,
5122                                            color,
5123                                        }
5124                                    });
5125
5126                                marker_quads.extend(
5127                                    scrollbar_layout
5128                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
5129                                );
5130                            }
5131
5132                            for (background_highlight_id, (_, background_ranges)) in
5133                                background_highlights.iter()
5134                            {
5135                                let is_search_highlights = *background_highlight_id
5136                                    == TypeId::of::<BufferSearchHighlights>();
5137                                let is_text_highlights = *background_highlight_id
5138                                    == TypeId::of::<SelectedTextHighlight>();
5139                                let is_symbol_occurrences = *background_highlight_id
5140                                    == TypeId::of::<DocumentHighlightRead>()
5141                                    || *background_highlight_id
5142                                        == TypeId::of::<DocumentHighlightWrite>();
5143                                if (is_search_highlights && scrollbar_settings.search_results)
5144                                    || (is_text_highlights && scrollbar_settings.selected_text)
5145                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
5146                                {
5147                                    let mut color = theme.status().info;
5148                                    if is_symbol_occurrences {
5149                                        color.fade_out(0.5);
5150                                    }
5151                                    let marker_row_ranges = background_ranges.iter().map(|range| {
5152                                        let display_start = range
5153                                            .start
5154                                            .to_display_point(&snapshot.display_snapshot);
5155                                        let display_end =
5156                                            range.end.to_display_point(&snapshot.display_snapshot);
5157                                        ColoredRange {
5158                                            start: display_start.row(),
5159                                            end: display_end.row(),
5160                                            color,
5161                                        }
5162                                    });
5163                                    marker_quads.extend(
5164                                        scrollbar_layout
5165                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
5166                                    );
5167                                }
5168                            }
5169
5170                            if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
5171                                let diagnostics = snapshot
5172                                    .buffer_snapshot
5173                                    .diagnostics_in_range::<Point>(Point::zero()..max_point)
5174                                    // Don't show diagnostics the user doesn't care about
5175                                    .filter(|diagnostic| {
5176                                        match (
5177                                            scrollbar_settings.diagnostics,
5178                                            diagnostic.diagnostic.severity,
5179                                        ) {
5180                                            (ScrollbarDiagnostics::All, _) => true,
5181                                            (
5182                                                ScrollbarDiagnostics::Error,
5183                                                DiagnosticSeverity::ERROR,
5184                                            ) => true,
5185                                            (
5186                                                ScrollbarDiagnostics::Warning,
5187                                                DiagnosticSeverity::ERROR
5188                                                | DiagnosticSeverity::WARNING,
5189                                            ) => true,
5190                                            (
5191                                                ScrollbarDiagnostics::Information,
5192                                                DiagnosticSeverity::ERROR
5193                                                | DiagnosticSeverity::WARNING
5194                                                | DiagnosticSeverity::INFORMATION,
5195                                            ) => true,
5196                                            (_, _) => false,
5197                                        }
5198                                    })
5199                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
5200                                    .sorted_by_key(|diagnostic| {
5201                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
5202                                    });
5203
5204                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
5205                                    let start_display = diagnostic
5206                                        .range
5207                                        .start
5208                                        .to_display_point(&snapshot.display_snapshot);
5209                                    let end_display = diagnostic
5210                                        .range
5211                                        .end
5212                                        .to_display_point(&snapshot.display_snapshot);
5213                                    let color = match diagnostic.diagnostic.severity {
5214                                        DiagnosticSeverity::ERROR => theme.status().error,
5215                                        DiagnosticSeverity::WARNING => theme.status().warning,
5216                                        DiagnosticSeverity::INFORMATION => theme.status().info,
5217                                        _ => theme.status().hint,
5218                                    };
5219                                    ColoredRange {
5220                                        start: start_display.row(),
5221                                        end: end_display.row(),
5222                                        color,
5223                                    }
5224                                });
5225                                marker_quads.extend(
5226                                    scrollbar_layout
5227                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
5228                                );
5229                            }
5230
5231                            Arc::from(marker_quads)
5232                        })
5233                        .await;
5234
5235                    editor.update(&mut cx, |editor, cx| {
5236                        editor.scrollbar_marker_state.markers = scrollbar_markers;
5237                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
5238                        editor.scrollbar_marker_state.pending_refresh = None;
5239                        cx.notify();
5240                    })?;
5241
5242                    Ok(())
5243                }));
5244        });
5245    }
5246
5247    #[allow(clippy::too_many_arguments)]
5248    fn paint_highlighted_range(
5249        &self,
5250        range: Range<DisplayPoint>,
5251        color: Hsla,
5252        corner_radius: Pixels,
5253        line_end_overshoot: Pixels,
5254        layout: &EditorLayout,
5255        window: &mut Window,
5256    ) {
5257        let start_row = layout.visible_display_row_range.start;
5258        let end_row = layout.visible_display_row_range.end;
5259        if range.start != range.end {
5260            let row_range = if range.end.column() == 0 {
5261                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
5262            } else {
5263                cmp::max(range.start.row(), start_row)
5264                    ..cmp::min(range.end.row().next_row(), end_row)
5265            };
5266
5267            let highlighted_range = HighlightedRange {
5268                color,
5269                line_height: layout.position_map.line_height,
5270                corner_radius,
5271                start_y: layout.content_origin.y
5272                    + row_range.start.as_f32() * layout.position_map.line_height
5273                    - layout.position_map.scroll_pixel_position.y,
5274                lines: row_range
5275                    .iter_rows()
5276                    .map(|row| {
5277                        let line_layout =
5278                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
5279                        HighlightedRangeLine {
5280                            start_x: if row == range.start.row() {
5281                                layout.content_origin.x
5282                                    + line_layout.x_for_index(range.start.column() as usize)
5283                                    - layout.position_map.scroll_pixel_position.x
5284                            } else {
5285                                layout.content_origin.x
5286                                    - layout.position_map.scroll_pixel_position.x
5287                            },
5288                            end_x: if row == range.end.row() {
5289                                layout.content_origin.x
5290                                    + line_layout.x_for_index(range.end.column() as usize)
5291                                    - layout.position_map.scroll_pixel_position.x
5292                            } else {
5293                                layout.content_origin.x + line_layout.width + line_end_overshoot
5294                                    - layout.position_map.scroll_pixel_position.x
5295                            },
5296                        }
5297                    })
5298                    .collect(),
5299            };
5300
5301            highlighted_range.paint(layout.position_map.text_hitbox.bounds, window);
5302        }
5303    }
5304
5305    fn paint_inline_diagnostics(
5306        &mut self,
5307        layout: &mut EditorLayout,
5308        window: &mut Window,
5309        cx: &mut App,
5310    ) {
5311        for mut inline_diagnostic in layout.inline_diagnostics.drain() {
5312            inline_diagnostic.1.paint(window, cx);
5313        }
5314    }
5315
5316    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5317        if let Some(mut inline_blame) = layout.inline_blame.take() {
5318            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5319                inline_blame.paint(window, cx);
5320            })
5321        }
5322    }
5323
5324    fn paint_diff_hunk_controls(
5325        &mut self,
5326        layout: &mut EditorLayout,
5327        window: &mut Window,
5328        cx: &mut App,
5329    ) {
5330        for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
5331            diff_hunk_control.paint(window, cx);
5332        }
5333    }
5334
5335    fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5336        for mut block in layout.blocks.drain(..) {
5337            block.element.paint(window, cx);
5338        }
5339    }
5340
5341    fn paint_inline_completion_popover(
5342        &mut self,
5343        layout: &mut EditorLayout,
5344        window: &mut Window,
5345        cx: &mut App,
5346    ) {
5347        if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
5348            inline_completion_popover.paint(window, cx);
5349        }
5350    }
5351
5352    fn paint_mouse_context_menu(
5353        &mut self,
5354        layout: &mut EditorLayout,
5355        window: &mut Window,
5356        cx: &mut App,
5357    ) {
5358        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
5359            mouse_context_menu.paint(window, cx);
5360        }
5361    }
5362
5363    fn paint_scroll_wheel_listener(
5364        &mut self,
5365        layout: &EditorLayout,
5366        window: &mut Window,
5367        cx: &mut App,
5368    ) {
5369        window.on_mouse_event({
5370            let position_map = layout.position_map.clone();
5371            let editor = self.editor.clone();
5372            let hitbox = layout.hitbox.clone();
5373            let mut delta = ScrollDelta::default();
5374
5375            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
5376            // accidentally turn off their scrolling.
5377            let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
5378
5379            move |event: &ScrollWheelEvent, phase, window, cx| {
5380                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
5381                    delta = delta.coalesce(event.delta);
5382                    editor.update(cx, |editor, cx| {
5383                        let position_map: &PositionMap = &position_map;
5384
5385                        let line_height = position_map.line_height;
5386                        let max_glyph_width = position_map.em_width;
5387                        let (delta, axis) = match delta {
5388                            gpui::ScrollDelta::Pixels(mut pixels) => {
5389                                //Trackpad
5390                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
5391                                (pixels, axis)
5392                            }
5393
5394                            gpui::ScrollDelta::Lines(lines) => {
5395                                //Not trackpad
5396                                let pixels =
5397                                    point(lines.x * max_glyph_width, lines.y * line_height);
5398                                (pixels, None)
5399                            }
5400                        };
5401
5402                        let current_scroll_position = position_map.snapshot.scroll_position();
5403                        let x = (current_scroll_position.x * max_glyph_width
5404                            - (delta.x * scroll_sensitivity))
5405                            / max_glyph_width;
5406                        let y = (current_scroll_position.y * line_height
5407                            - (delta.y * scroll_sensitivity))
5408                            / line_height;
5409                        let mut scroll_position =
5410                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
5411                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
5412                        if forbid_vertical_scroll {
5413                            scroll_position.y = current_scroll_position.y;
5414                        }
5415
5416                        if scroll_position != current_scroll_position {
5417                            editor.scroll(scroll_position, axis, window, cx);
5418                            cx.stop_propagation();
5419                        } else if y < 0. {
5420                            // Due to clamping, we may fail to detect cases of overscroll to the top;
5421                            // We want the scroll manager to get an update in such cases and detect the change of direction
5422                            // on the next frame.
5423                            cx.notify();
5424                        }
5425                    });
5426                }
5427            }
5428        });
5429    }
5430
5431    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5432        self.paint_scroll_wheel_listener(layout, window, cx);
5433
5434        window.on_mouse_event({
5435            let position_map = layout.position_map.clone();
5436            let editor = self.editor.clone();
5437            let diff_hunk_range =
5438                layout
5439                    .display_hunks
5440                    .iter()
5441                    .find_map(|(hunk, hunk_hitbox)| match hunk {
5442                        DisplayDiffHunk::Folded { .. } => None,
5443                        DisplayDiffHunk::Unfolded {
5444                            multi_buffer_range, ..
5445                        } => {
5446                            if hunk_hitbox
5447                                .as_ref()
5448                                .map(|hitbox| hitbox.is_hovered(window))
5449                                .unwrap_or(false)
5450                            {
5451                                Some(multi_buffer_range.clone())
5452                            } else {
5453                                None
5454                            }
5455                        }
5456                    });
5457            let line_numbers = layout.line_numbers.clone();
5458
5459            move |event: &MouseDownEvent, phase, window, cx| {
5460                if phase == DispatchPhase::Bubble {
5461                    match event.button {
5462                        MouseButton::Left => editor.update(cx, |editor, cx| {
5463                            let pending_mouse_down = editor
5464                                .pending_mouse_down
5465                                .get_or_insert_with(Default::default)
5466                                .clone();
5467
5468                            *pending_mouse_down.borrow_mut() = Some(event.clone());
5469
5470                            Self::mouse_left_down(
5471                                editor,
5472                                event,
5473                                diff_hunk_range.clone(),
5474                                &position_map,
5475                                line_numbers.as_ref(),
5476                                window,
5477                                cx,
5478                            );
5479                        }),
5480                        MouseButton::Right => editor.update(cx, |editor, cx| {
5481                            Self::mouse_right_down(editor, event, &position_map, window, cx);
5482                        }),
5483                        MouseButton::Middle => editor.update(cx, |editor, cx| {
5484                            Self::mouse_middle_down(editor, event, &position_map, window, cx);
5485                        }),
5486                        _ => {}
5487                    };
5488                }
5489            }
5490        });
5491
5492        window.on_mouse_event({
5493            let editor = self.editor.clone();
5494            let position_map = layout.position_map.clone();
5495
5496            move |event: &MouseUpEvent, phase, window, cx| {
5497                if phase == DispatchPhase::Bubble {
5498                    editor.update(cx, |editor, cx| {
5499                        Self::mouse_up(editor, event, &position_map, window, cx)
5500                    });
5501                }
5502            }
5503        });
5504
5505        window.on_mouse_event({
5506            let editor = self.editor.clone();
5507            let position_map = layout.position_map.clone();
5508            let mut captured_mouse_down = None;
5509
5510            move |event: &MouseUpEvent, phase, window, cx| match phase {
5511                // Clear the pending mouse down during the capture phase,
5512                // so that it happens even if another event handler stops
5513                // propagation.
5514                DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
5515                    let pending_mouse_down = editor
5516                        .pending_mouse_down
5517                        .get_or_insert_with(Default::default)
5518                        .clone();
5519
5520                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
5521                    if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
5522                        captured_mouse_down = pending_mouse_down.take();
5523                        window.refresh();
5524                    }
5525                }),
5526                // Fire click handlers during the bubble phase.
5527                DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
5528                    if let Some(mouse_down) = captured_mouse_down.take() {
5529                        let event = ClickEvent {
5530                            down: mouse_down,
5531                            up: event.clone(),
5532                        };
5533                        Self::click(editor, &event, &position_map, window, cx);
5534                    }
5535                }),
5536            }
5537        });
5538
5539        window.on_mouse_event({
5540            let position_map = layout.position_map.clone();
5541            let editor = self.editor.clone();
5542
5543            move |event: &MouseMoveEvent, phase, window, cx| {
5544                if phase == DispatchPhase::Bubble {
5545                    editor.update(cx, |editor, cx| {
5546                        if editor.hover_state.focused(window, cx) {
5547                            return;
5548                        }
5549                        if event.pressed_button == Some(MouseButton::Left)
5550                            || event.pressed_button == Some(MouseButton::Middle)
5551                        {
5552                            Self::mouse_dragged(editor, event, &position_map, window, cx)
5553                        }
5554
5555                        Self::mouse_moved(editor, event, &position_map, window, cx)
5556                    });
5557                }
5558            }
5559        });
5560    }
5561
5562    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
5563        bounds.top_right().x - self.style.scrollbar_width
5564    }
5565
5566    fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
5567        let style = &self.style;
5568        let font_size = style.text.font_size.to_pixels(window.rem_size());
5569        let layout = window
5570            .text_system()
5571            .shape_line(
5572                SharedString::from(" ".repeat(column)),
5573                font_size,
5574                &[TextRun {
5575                    len: column,
5576                    font: style.text.font(),
5577                    color: Hsla::default(),
5578                    background_color: None,
5579                    underline: None,
5580                    strikethrough: None,
5581                }],
5582            )
5583            .unwrap();
5584
5585        layout.width
5586    }
5587
5588    fn max_line_number_width(
5589        &self,
5590        snapshot: &EditorSnapshot,
5591        window: &mut Window,
5592        cx: &mut App,
5593    ) -> Pixels {
5594        let digit_count = (snapshot.widest_line_number() as f32).log10().floor() as usize + 1;
5595        self.column_pixels(digit_count, window, cx)
5596    }
5597
5598    fn shape_line_number(
5599        &self,
5600        text: SharedString,
5601        color: Hsla,
5602        window: &mut Window,
5603    ) -> anyhow::Result<ShapedLine> {
5604        let run = TextRun {
5605            len: text.len(),
5606            font: self.style.text.font(),
5607            color,
5608            background_color: None,
5609            underline: None,
5610            strikethrough: None,
5611        };
5612        window.text_system().shape_line(
5613            text,
5614            self.style.text.font_size.to_pixels(window.rem_size()),
5615            &[run],
5616        )
5617    }
5618}
5619
5620fn header_jump_data(
5621    snapshot: &EditorSnapshot,
5622    block_row_start: DisplayRow,
5623    height: u32,
5624    for_excerpt: &ExcerptInfo,
5625) -> JumpData {
5626    let range = &for_excerpt.range;
5627    let buffer = &for_excerpt.buffer;
5628    let jump_anchor = range
5629        .primary
5630        .as_ref()
5631        .map_or(range.context.start, |primary| primary.start);
5632
5633    let excerpt_start = range.context.start;
5634    let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
5635    let rows_from_excerpt_start = if jump_anchor == excerpt_start {
5636        0
5637    } else {
5638        let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
5639        jump_position.row.saturating_sub(excerpt_start_point.row)
5640    };
5641
5642    let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
5643        .saturating_sub(
5644            snapshot
5645                .scroll_anchor
5646                .scroll_position(&snapshot.display_snapshot)
5647                .y as u32,
5648        );
5649
5650    JumpData::MultiBufferPoint {
5651        excerpt_id: for_excerpt.id,
5652        anchor: jump_anchor,
5653        position: jump_position,
5654        line_offset_from_top,
5655    }
5656}
5657
5658pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
5659
5660impl AcceptEditPredictionBinding {
5661    pub fn keystroke(&self) -> Option<&Keystroke> {
5662        if let Some(binding) = self.0.as_ref() {
5663            match &binding.keystrokes() {
5664                [keystroke] => Some(keystroke),
5665                _ => None,
5666            }
5667        } else {
5668            None
5669        }
5670    }
5671}
5672
5673#[allow(clippy::too_many_arguments)]
5674fn prepaint_gutter_button(
5675    button: IconButton,
5676    row: DisplayRow,
5677    line_height: Pixels,
5678    gutter_dimensions: &GutterDimensions,
5679    scroll_pixel_position: gpui::Point<Pixels>,
5680    gutter_hitbox: &Hitbox,
5681    rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
5682    window: &mut Window,
5683    cx: &mut App,
5684) -> AnyElement {
5685    let mut button = button.into_any_element();
5686    let available_space = size(
5687        AvailableSpace::MinContent,
5688        AvailableSpace::Definite(line_height),
5689    );
5690    let indicator_size = button.layout_as_root(available_space, window, cx);
5691
5692    let blame_width = gutter_dimensions.git_blame_entries_width;
5693    let gutter_width = rows_with_hunk_bounds
5694        .get(&row)
5695        .map(|bounds| bounds.size.width);
5696    let left_offset = blame_width.max(gutter_width).unwrap_or_default();
5697
5698    let mut x = left_offset;
5699    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
5700        - indicator_size.width
5701        - left_offset;
5702    x += available_width / 2.;
5703
5704    let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
5705    y += (line_height - indicator_size.height) / 2.;
5706
5707    button.prepaint_as_root(
5708        gutter_hitbox.origin + point(x, y),
5709        available_space,
5710        window,
5711        cx,
5712    );
5713    button
5714}
5715
5716fn render_inline_blame_entry(
5717    editor: Entity<Editor>,
5718    blame: &gpui::Entity<GitBlame>,
5719    blame_entry: BlameEntry,
5720    style: &EditorStyle,
5721    cx: &mut App,
5722) -> AnyElement {
5723    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5724
5725    let author = blame_entry.author.as_deref().unwrap_or_default();
5726    let summary_enabled = ProjectSettings::get_global(cx)
5727        .git
5728        .show_inline_commit_summary();
5729
5730    let text = match blame_entry.summary.as_ref() {
5731        Some(summary) if summary_enabled => {
5732            format!("{}, {} - {}", author, relative_timestamp, summary)
5733        }
5734        _ => format!("{}, {}", author, relative_timestamp),
5735    };
5736    let blame = blame.clone();
5737    let blame_entry = blame_entry.clone();
5738
5739    h_flex()
5740        .id("inline-blame")
5741        .w_full()
5742        .font_family(style.text.font().family)
5743        .text_color(cx.theme().status().hint)
5744        .line_height(style.text.line_height)
5745        .child(Icon::new(IconName::FileGit).color(Color::Hint))
5746        .child(text)
5747        .gap_2()
5748        .hoverable_tooltip(move |window, cx| {
5749            let details = blame.read(cx).details_for_entry(&blame_entry);
5750            let tooltip =
5751                cx.new(|cx| CommitTooltip::blame_entry(&blame_entry, details, window, cx));
5752            editor.update(cx, |editor, _| {
5753                editor.git_blame_inline_tooltip = Some(tooltip.downgrade())
5754            });
5755            tooltip.into()
5756        })
5757        .into_any()
5758}
5759
5760fn render_blame_entry(
5761    ix: usize,
5762    blame: &gpui::Entity<GitBlame>,
5763    blame_entry: BlameEntry,
5764    style: &EditorStyle,
5765    last_used_color: &mut Option<(PlayerColor, Oid)>,
5766    editor: Entity<Editor>,
5767    cx: &mut App,
5768) -> AnyElement {
5769    let mut sha_color = cx
5770        .theme()
5771        .players()
5772        .color_for_participant(blame_entry.sha.into());
5773    // If the last color we used is the same as the one we get for this line, but
5774    // the commit SHAs are different, then we try again to get a different color.
5775    match *last_used_color {
5776        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
5777            let index: u32 = blame_entry.sha.into();
5778            sha_color = cx.theme().players().color_for_participant(index + 1);
5779        }
5780        _ => {}
5781    };
5782    last_used_color.replace((sha_color, blame_entry.sha));
5783
5784    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5785
5786    let short_commit_id = blame_entry.sha.display_short();
5787
5788    let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
5789    let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
5790    let details = blame.read(cx).details_for_entry(&blame_entry);
5791
5792    h_flex()
5793        .w_full()
5794        .justify_between()
5795        .font_family(style.text.font().family)
5796        .line_height(style.text.line_height)
5797        .id(("blame", ix))
5798        .text_color(cx.theme().status().hint)
5799        .pr_2()
5800        .gap_2()
5801        .child(
5802            h_flex()
5803                .items_center()
5804                .gap_2()
5805                .child(div().text_color(sha_color.cursor).child(short_commit_id))
5806                .child(name),
5807        )
5808        .child(relative_timestamp)
5809        .on_mouse_down(MouseButton::Right, {
5810            let blame_entry = blame_entry.clone();
5811            let details = details.clone();
5812            move |event, window, cx| {
5813                deploy_blame_entry_context_menu(
5814                    &blame_entry,
5815                    details.as_ref(),
5816                    editor.clone(),
5817                    event.position,
5818                    window,
5819                    cx,
5820                );
5821            }
5822        })
5823        .hover(|style| style.bg(cx.theme().colors().element_hover))
5824        .when_some(
5825            details
5826                .as_ref()
5827                .and_then(|details| details.permalink.clone()),
5828            |this, url| {
5829                this.cursor_pointer().on_click(move |_, _, cx| {
5830                    cx.stop_propagation();
5831                    cx.open_url(url.as_str())
5832                })
5833            },
5834        )
5835        .hoverable_tooltip(move |window, cx| {
5836            cx.new(|cx| CommitTooltip::blame_entry(&blame_entry, details.clone(), window, cx))
5837                .into()
5838        })
5839        .into_any()
5840}
5841
5842fn deploy_blame_entry_context_menu(
5843    blame_entry: &BlameEntry,
5844    details: Option<&ParsedCommitMessage>,
5845    editor: Entity<Editor>,
5846    position: gpui::Point<Pixels>,
5847    window: &mut Window,
5848    cx: &mut App,
5849) {
5850    let context_menu = ContextMenu::build(window, cx, move |menu, _, _| {
5851        let sha = format!("{}", blame_entry.sha);
5852        menu.on_blur_subscription(Subscription::new(|| {}))
5853            .entry("Copy commit SHA", None, move |_, cx| {
5854                cx.write_to_clipboard(ClipboardItem::new_string(sha.clone()));
5855            })
5856            .when_some(
5857                details.and_then(|details| details.permalink.clone()),
5858                |this, url| {
5859                    this.entry("Open permalink", None, move |_, cx| {
5860                        cx.open_url(url.as_str())
5861                    })
5862                },
5863            )
5864    });
5865
5866    editor.update(cx, move |editor, cx| {
5867        editor.mouse_context_menu = Some(MouseContextMenu::new(
5868            MenuPosition::PinnedToScreen(position),
5869            context_menu,
5870            window,
5871            cx,
5872        ));
5873        cx.notify();
5874    });
5875}
5876
5877#[derive(Debug)]
5878pub(crate) struct LineWithInvisibles {
5879    fragments: SmallVec<[LineFragment; 1]>,
5880    invisibles: Vec<Invisible>,
5881    len: usize,
5882    pub(crate) width: Pixels,
5883    font_size: Pixels,
5884}
5885
5886#[allow(clippy::large_enum_variant)]
5887enum LineFragment {
5888    Text(ShapedLine),
5889    Element {
5890        element: Option<AnyElement>,
5891        size: Size<Pixels>,
5892        len: usize,
5893    },
5894}
5895
5896impl fmt::Debug for LineFragment {
5897    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5898        match self {
5899            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
5900            LineFragment::Element { size, len, .. } => f
5901                .debug_struct("Element")
5902                .field("size", size)
5903                .field("len", len)
5904                .finish(),
5905        }
5906    }
5907}
5908
5909impl LineWithInvisibles {
5910    #[allow(clippy::too_many_arguments)]
5911    fn from_chunks<'a>(
5912        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
5913        editor_style: &EditorStyle,
5914        max_line_len: usize,
5915        max_line_count: usize,
5916        editor_mode: EditorMode,
5917        text_width: Pixels,
5918        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
5919        window: &mut Window,
5920        cx: &mut App,
5921    ) -> Vec<Self> {
5922        let text_style = &editor_style.text;
5923        let mut layouts = Vec::with_capacity(max_line_count);
5924        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
5925        let mut line = String::new();
5926        let mut invisibles = Vec::new();
5927        let mut width = Pixels::ZERO;
5928        let mut len = 0;
5929        let mut styles = Vec::new();
5930        let mut non_whitespace_added = false;
5931        let mut row = 0;
5932        let mut line_exceeded_max_len = false;
5933        let font_size = text_style.font_size.to_pixels(window.rem_size());
5934
5935        let ellipsis = SharedString::from("");
5936
5937        for highlighted_chunk in chunks.chain([HighlightedChunk {
5938            text: "\n",
5939            style: None,
5940            is_tab: false,
5941            replacement: None,
5942        }]) {
5943            if let Some(replacement) = highlighted_chunk.replacement {
5944                if !line.is_empty() {
5945                    let shaped_line = window
5946                        .text_system()
5947                        .shape_line(line.clone().into(), font_size, &styles)
5948                        .unwrap();
5949                    width += shaped_line.width;
5950                    len += shaped_line.len;
5951                    fragments.push(LineFragment::Text(shaped_line));
5952                    line.clear();
5953                    styles.clear();
5954                }
5955
5956                match replacement {
5957                    ChunkReplacement::Renderer(renderer) => {
5958                        let available_width = if renderer.constrain_width {
5959                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
5960                                ellipsis.clone()
5961                            } else {
5962                                SharedString::from(Arc::from(highlighted_chunk.text))
5963                            };
5964                            let shaped_line = window
5965                                .text_system()
5966                                .shape_line(
5967                                    chunk,
5968                                    font_size,
5969                                    &[text_style.to_run(highlighted_chunk.text.len())],
5970                                )
5971                                .unwrap();
5972                            AvailableSpace::Definite(shaped_line.width)
5973                        } else {
5974                            AvailableSpace::MinContent
5975                        };
5976
5977                        let mut element = (renderer.render)(&mut ChunkRendererContext {
5978                            context: cx,
5979                            window,
5980                            max_width: text_width,
5981                        });
5982                        let line_height = text_style.line_height_in_pixels(window.rem_size());
5983                        let size = element.layout_as_root(
5984                            size(available_width, AvailableSpace::Definite(line_height)),
5985                            window,
5986                            cx,
5987                        );
5988
5989                        width += size.width;
5990                        len += highlighted_chunk.text.len();
5991                        fragments.push(LineFragment::Element {
5992                            element: Some(element),
5993                            size,
5994                            len: highlighted_chunk.text.len(),
5995                        });
5996                    }
5997                    ChunkReplacement::Str(x) => {
5998                        let text_style = if let Some(style) = highlighted_chunk.style {
5999                            Cow::Owned(text_style.clone().highlight(style))
6000                        } else {
6001                            Cow::Borrowed(text_style)
6002                        };
6003
6004                        let run = TextRun {
6005                            len: x.len(),
6006                            font: text_style.font(),
6007                            color: text_style.color,
6008                            background_color: text_style.background_color,
6009                            underline: text_style.underline,
6010                            strikethrough: text_style.strikethrough,
6011                        };
6012                        let line_layout = window
6013                            .text_system()
6014                            .shape_line(x, font_size, &[run])
6015                            .unwrap()
6016                            .with_len(highlighted_chunk.text.len());
6017
6018                        width += line_layout.width;
6019                        len += highlighted_chunk.text.len();
6020                        fragments.push(LineFragment::Text(line_layout))
6021                    }
6022                }
6023            } else {
6024                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
6025                    if ix > 0 {
6026                        let shaped_line = window
6027                            .text_system()
6028                            .shape_line(line.clone().into(), font_size, &styles)
6029                            .unwrap();
6030                        width += shaped_line.width;
6031                        len += shaped_line.len;
6032                        fragments.push(LineFragment::Text(shaped_line));
6033                        layouts.push(Self {
6034                            width: mem::take(&mut width),
6035                            len: mem::take(&mut len),
6036                            fragments: mem::take(&mut fragments),
6037                            invisibles: std::mem::take(&mut invisibles),
6038                            font_size,
6039                        });
6040
6041                        line.clear();
6042                        styles.clear();
6043                        row += 1;
6044                        line_exceeded_max_len = false;
6045                        non_whitespace_added = false;
6046                        if row == max_line_count {
6047                            return layouts;
6048                        }
6049                    }
6050
6051                    if !line_chunk.is_empty() && !line_exceeded_max_len {
6052                        let text_style = if let Some(style) = highlighted_chunk.style {
6053                            Cow::Owned(text_style.clone().highlight(style))
6054                        } else {
6055                            Cow::Borrowed(text_style)
6056                        };
6057
6058                        if line.len() + line_chunk.len() > max_line_len {
6059                            let mut chunk_len = max_line_len - line.len();
6060                            while !line_chunk.is_char_boundary(chunk_len) {
6061                                chunk_len -= 1;
6062                            }
6063                            line_chunk = &line_chunk[..chunk_len];
6064                            line_exceeded_max_len = true;
6065                        }
6066
6067                        styles.push(TextRun {
6068                            len: line_chunk.len(),
6069                            font: text_style.font(),
6070                            color: text_style.color,
6071                            background_color: text_style.background_color,
6072                            underline: text_style.underline,
6073                            strikethrough: text_style.strikethrough,
6074                        });
6075
6076                        if editor_mode == EditorMode::Full {
6077                            // Line wrap pads its contents with fake whitespaces,
6078                            // avoid printing them
6079                            let is_soft_wrapped = is_row_soft_wrapped(row);
6080                            if highlighted_chunk.is_tab {
6081                                if non_whitespace_added || !is_soft_wrapped {
6082                                    invisibles.push(Invisible::Tab {
6083                                        line_start_offset: line.len(),
6084                                        line_end_offset: line.len() + line_chunk.len(),
6085                                    });
6086                                }
6087                            } else {
6088                                invisibles.extend(line_chunk.char_indices().filter_map(
6089                                    |(index, c)| {
6090                                        let is_whitespace = c.is_whitespace();
6091                                        non_whitespace_added |= !is_whitespace;
6092                                        if is_whitespace
6093                                            && (non_whitespace_added || !is_soft_wrapped)
6094                                        {
6095                                            Some(Invisible::Whitespace {
6096                                                line_offset: line.len() + index,
6097                                            })
6098                                        } else {
6099                                            None
6100                                        }
6101                                    },
6102                                ))
6103                            }
6104                        }
6105
6106                        line.push_str(line_chunk);
6107                    }
6108                }
6109            }
6110        }
6111
6112        layouts
6113    }
6114
6115    #[allow(clippy::too_many_arguments)]
6116    fn prepaint(
6117        &mut self,
6118        line_height: Pixels,
6119        scroll_pixel_position: gpui::Point<Pixels>,
6120        row: DisplayRow,
6121        content_origin: gpui::Point<Pixels>,
6122        line_elements: &mut SmallVec<[AnyElement; 1]>,
6123        window: &mut Window,
6124        cx: &mut App,
6125    ) {
6126        let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
6127        let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
6128        for fragment in &mut self.fragments {
6129            match fragment {
6130                LineFragment::Text(line) => {
6131                    fragment_origin.x += line.width;
6132                }
6133                LineFragment::Element { element, size, .. } => {
6134                    let mut element = element
6135                        .take()
6136                        .expect("you can't prepaint LineWithInvisibles twice");
6137
6138                    // Center the element vertically within the line.
6139                    let mut element_origin = fragment_origin;
6140                    element_origin.y += (line_height - size.height) / 2.;
6141                    element.prepaint_at(element_origin, window, cx);
6142                    line_elements.push(element);
6143
6144                    fragment_origin.x += size.width;
6145                }
6146            }
6147        }
6148    }
6149
6150    #[allow(clippy::too_many_arguments)]
6151    fn draw(
6152        &self,
6153        layout: &EditorLayout,
6154        row: DisplayRow,
6155        content_origin: gpui::Point<Pixels>,
6156        whitespace_setting: ShowWhitespaceSetting,
6157        selection_ranges: &[Range<DisplayPoint>],
6158        window: &mut Window,
6159        cx: &mut App,
6160    ) {
6161        let line_height = layout.position_map.line_height;
6162        let line_y = line_height
6163            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6164
6165        let mut fragment_origin =
6166            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6167
6168        for fragment in &self.fragments {
6169            match fragment {
6170                LineFragment::Text(line) => {
6171                    line.paint(fragment_origin, line_height, window, cx)
6172                        .log_err();
6173                    fragment_origin.x += line.width;
6174                }
6175                LineFragment::Element { size, .. } => {
6176                    fragment_origin.x += size.width;
6177                }
6178            }
6179        }
6180
6181        self.draw_invisibles(
6182            selection_ranges,
6183            layout,
6184            content_origin,
6185            line_y,
6186            row,
6187            line_height,
6188            whitespace_setting,
6189            window,
6190            cx,
6191        );
6192    }
6193
6194    #[allow(clippy::too_many_arguments)]
6195    fn draw_invisibles(
6196        &self,
6197        selection_ranges: &[Range<DisplayPoint>],
6198        layout: &EditorLayout,
6199        content_origin: gpui::Point<Pixels>,
6200        line_y: Pixels,
6201        row: DisplayRow,
6202        line_height: Pixels,
6203        whitespace_setting: ShowWhitespaceSetting,
6204        window: &mut Window,
6205        cx: &mut App,
6206    ) {
6207        let extract_whitespace_info = |invisible: &Invisible| {
6208            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
6209                Invisible::Tab {
6210                    line_start_offset,
6211                    line_end_offset,
6212                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
6213                Invisible::Whitespace { line_offset } => {
6214                    (*line_offset, line_offset + 1, &layout.space_invisible)
6215                }
6216            };
6217
6218            let x_offset = self.x_for_index(token_offset);
6219            let invisible_offset =
6220                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
6221            let origin = content_origin
6222                + gpui::point(
6223                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
6224                    line_y,
6225                );
6226
6227            (
6228                [token_offset, token_end_offset],
6229                Box::new(move |window: &mut Window, cx: &mut App| {
6230                    invisible_symbol
6231                        .paint(origin, line_height, window, cx)
6232                        .log_err();
6233                }),
6234            )
6235        };
6236
6237        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
6238        match whitespace_setting {
6239            ShowWhitespaceSetting::None => (),
6240            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
6241            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
6242                let invisible_point = DisplayPoint::new(row, start as u32);
6243                if !selection_ranges
6244                    .iter()
6245                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
6246                {
6247                    return;
6248                }
6249
6250                paint(window, cx);
6251            }),
6252
6253            // For a whitespace to be on a boundary, any of the following conditions need to be met:
6254            // - It is a tab
6255            // - It is adjacent to an edge (start or end)
6256            // - It is adjacent to a whitespace (left or right)
6257            ShowWhitespaceSetting::Boundary => {
6258                // 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
6259                // the above cases.
6260                // Note: We zip in the original `invisibles` to check for tab equality
6261                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
6262                for (([start, end], paint), invisible) in
6263                    invisible_iter.zip_eq(self.invisibles.iter())
6264                {
6265                    let should_render = match (&last_seen, invisible) {
6266                        (_, Invisible::Tab { .. }) => true,
6267                        (Some((_, last_end, _)), _) => *last_end == start,
6268                        _ => false,
6269                    };
6270
6271                    if should_render || start == 0 || end == self.len {
6272                        paint(window, cx);
6273
6274                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
6275                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
6276                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
6277                            // Note that we need to make sure that the last one is actually adjacent
6278                            if !should_render_last && last_end == start {
6279                                paint_last(window, cx);
6280                            }
6281                        }
6282                    }
6283
6284                    // Manually render anything within a selection
6285                    let invisible_point = DisplayPoint::new(row, start as u32);
6286                    if selection_ranges.iter().any(|region| {
6287                        region.start <= invisible_point && invisible_point < region.end
6288                    }) {
6289                        paint(window, cx);
6290                    }
6291
6292                    last_seen = Some((should_render, end, paint));
6293                }
6294            }
6295        }
6296    }
6297
6298    pub fn x_for_index(&self, index: usize) -> Pixels {
6299        let mut fragment_start_x = Pixels::ZERO;
6300        let mut fragment_start_index = 0;
6301
6302        for fragment in &self.fragments {
6303            match fragment {
6304                LineFragment::Text(shaped_line) => {
6305                    let fragment_end_index = fragment_start_index + shaped_line.len;
6306                    if index < fragment_end_index {
6307                        return fragment_start_x
6308                            + shaped_line.x_for_index(index - fragment_start_index);
6309                    }
6310                    fragment_start_x += shaped_line.width;
6311                    fragment_start_index = fragment_end_index;
6312                }
6313                LineFragment::Element { len, size, .. } => {
6314                    let fragment_end_index = fragment_start_index + len;
6315                    if index < fragment_end_index {
6316                        return fragment_start_x;
6317                    }
6318                    fragment_start_x += size.width;
6319                    fragment_start_index = fragment_end_index;
6320                }
6321            }
6322        }
6323
6324        fragment_start_x
6325    }
6326
6327    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
6328        let mut fragment_start_x = Pixels::ZERO;
6329        let mut fragment_start_index = 0;
6330
6331        for fragment in &self.fragments {
6332            match fragment {
6333                LineFragment::Text(shaped_line) => {
6334                    let fragment_end_x = fragment_start_x + shaped_line.width;
6335                    if x < fragment_end_x {
6336                        return Some(
6337                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
6338                        );
6339                    }
6340                    fragment_start_x = fragment_end_x;
6341                    fragment_start_index += shaped_line.len;
6342                }
6343                LineFragment::Element { len, size, .. } => {
6344                    let fragment_end_x = fragment_start_x + size.width;
6345                    if x < fragment_end_x {
6346                        return Some(fragment_start_index);
6347                    }
6348                    fragment_start_index += len;
6349                    fragment_start_x = fragment_end_x;
6350                }
6351            }
6352        }
6353
6354        None
6355    }
6356
6357    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
6358        let mut fragment_start_index = 0;
6359
6360        for fragment in &self.fragments {
6361            match fragment {
6362                LineFragment::Text(shaped_line) => {
6363                    let fragment_end_index = fragment_start_index + shaped_line.len;
6364                    if index < fragment_end_index {
6365                        return shaped_line.font_id_for_index(index - fragment_start_index);
6366                    }
6367                    fragment_start_index = fragment_end_index;
6368                }
6369                LineFragment::Element { len, .. } => {
6370                    let fragment_end_index = fragment_start_index + len;
6371                    if index < fragment_end_index {
6372                        return None;
6373                    }
6374                    fragment_start_index = fragment_end_index;
6375                }
6376            }
6377        }
6378
6379        None
6380    }
6381}
6382
6383#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6384enum Invisible {
6385    /// A tab character
6386    ///
6387    /// A tab character is internally represented by spaces (configured by the user's tab width)
6388    /// aligned to the nearest column, so it's necessary to store the start and end offset for
6389    /// adjacency checks.
6390    Tab {
6391        line_start_offset: usize,
6392        line_end_offset: usize,
6393    },
6394    Whitespace {
6395        line_offset: usize,
6396    },
6397}
6398
6399impl EditorElement {
6400    /// Returns the rem size to use when rendering the [`EditorElement`].
6401    ///
6402    /// This allows UI elements to scale based on the `buffer_font_size`.
6403    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
6404        match self.editor.read(cx).mode {
6405            EditorMode::Full => {
6406                let buffer_font_size = self.style.text.font_size;
6407                match buffer_font_size {
6408                    AbsoluteLength::Pixels(pixels) => {
6409                        let rem_size_scale = {
6410                            // Our default UI font size is 14px on a 16px base scale.
6411                            // This means the default UI font size is 0.875rems.
6412                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
6413
6414                            // We then determine the delta between a single rem and the default font
6415                            // size scale.
6416                            let default_font_size_delta = 1. - default_font_size_scale;
6417
6418                            // Finally, we add this delta to 1rem to get the scale factor that
6419                            // should be used to scale up the UI.
6420                            1. + default_font_size_delta
6421                        };
6422
6423                        Some(pixels * rem_size_scale)
6424                    }
6425                    AbsoluteLength::Rems(rems) => {
6426                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
6427                    }
6428                }
6429            }
6430            // We currently use single-line and auto-height editors in UI contexts,
6431            // so we don't want to scale everything with the buffer font size, as it
6432            // ends up looking off.
6433            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
6434        }
6435    }
6436}
6437
6438impl Element for EditorElement {
6439    type RequestLayoutState = ();
6440    type PrepaintState = EditorLayout;
6441
6442    fn id(&self) -> Option<ElementId> {
6443        None
6444    }
6445
6446    fn request_layout(
6447        &mut self,
6448        _: Option<&GlobalElementId>,
6449        window: &mut Window,
6450        cx: &mut App,
6451    ) -> (gpui::LayoutId, ()) {
6452        let rem_size = self.rem_size(cx);
6453        window.with_rem_size(rem_size, |window| {
6454            self.editor.update(cx, |editor, cx| {
6455                editor.set_style(self.style.clone(), window, cx);
6456
6457                let layout_id = match editor.mode {
6458                    EditorMode::SingleLine { auto_width } => {
6459                        let rem_size = window.rem_size();
6460
6461                        let height = self.style.text.line_height_in_pixels(rem_size);
6462                        if auto_width {
6463                            let editor_handle = cx.entity().clone();
6464                            let style = self.style.clone();
6465                            window.request_measured_layout(
6466                                Style::default(),
6467                                move |_, _, window, cx| {
6468                                    let editor_snapshot = editor_handle
6469                                        .update(cx, |editor, cx| editor.snapshot(window, cx));
6470                                    let line = Self::layout_lines(
6471                                        DisplayRow(0)..DisplayRow(1),
6472                                        &editor_snapshot,
6473                                        &style,
6474                                        px(f32::MAX),
6475                                        |_| false, // Single lines never soft wrap
6476                                        window,
6477                                        cx,
6478                                    )
6479                                    .pop()
6480                                    .unwrap();
6481
6482                                    let font_id =
6483                                        window.text_system().resolve_font(&style.text.font());
6484                                    let font_size =
6485                                        style.text.font_size.to_pixels(window.rem_size());
6486                                    let em_width =
6487                                        window.text_system().em_width(font_id, font_size).unwrap();
6488
6489                                    size(line.width + em_width, height)
6490                                },
6491                            )
6492                        } else {
6493                            let mut style = Style::default();
6494                            style.size.height = height.into();
6495                            style.size.width = relative(1.).into();
6496                            window.request_layout(style, None, cx)
6497                        }
6498                    }
6499                    EditorMode::AutoHeight { max_lines } => {
6500                        let editor_handle = cx.entity().clone();
6501                        let max_line_number_width =
6502                            self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
6503                        window.request_measured_layout(
6504                            Style::default(),
6505                            move |known_dimensions, available_space, window, cx| {
6506                                editor_handle
6507                                    .update(cx, |editor, cx| {
6508                                        compute_auto_height_layout(
6509                                            editor,
6510                                            max_lines,
6511                                            max_line_number_width,
6512                                            known_dimensions,
6513                                            available_space.width,
6514                                            window,
6515                                            cx,
6516                                        )
6517                                    })
6518                                    .unwrap_or_default()
6519                            },
6520                        )
6521                    }
6522                    EditorMode::Full => {
6523                        let mut style = Style::default();
6524                        style.size.width = relative(1.).into();
6525                        style.size.height = relative(1.).into();
6526                        window.request_layout(style, None, cx)
6527                    }
6528                };
6529
6530                (layout_id, ())
6531            })
6532        })
6533    }
6534
6535    fn prepaint(
6536        &mut self,
6537        _: Option<&GlobalElementId>,
6538        bounds: Bounds<Pixels>,
6539        _: &mut Self::RequestLayoutState,
6540        window: &mut Window,
6541        cx: &mut App,
6542    ) -> Self::PrepaintState {
6543        let text_style = TextStyleRefinement {
6544            font_size: Some(self.style.text.font_size),
6545            line_height: Some(self.style.text.line_height),
6546            ..Default::default()
6547        };
6548        let focus_handle = self.editor.focus_handle(cx);
6549        window.set_view_id(self.editor.entity_id());
6550        window.set_focus_handle(&focus_handle, cx);
6551
6552        let rem_size = self.rem_size(cx);
6553        window.with_rem_size(rem_size, |window| {
6554            window.with_text_style(Some(text_style), |window| {
6555                window.with_content_mask(Some(ContentMask { bounds }), |window| {
6556                    let mut snapshot = self
6557                        .editor
6558                        .update(cx, |editor, cx| editor.snapshot(window, cx));
6559                    let style = self.style.clone();
6560
6561                    let font_id = window.text_system().resolve_font(&style.text.font());
6562                    let font_size = style.text.font_size.to_pixels(window.rem_size());
6563                    let line_height = style.text.line_height_in_pixels(window.rem_size());
6564                    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
6565                    let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
6566
6567                    let letter_size = size(em_width, line_height);
6568
6569                    let gutter_dimensions = snapshot
6570                        .gutter_dimensions(
6571                            font_id,
6572                            font_size,
6573                            self.max_line_number_width(&snapshot, window, cx),
6574                            cx,
6575                        )
6576                        .unwrap_or_default();
6577                    let text_width = bounds.size.width - gutter_dimensions.width;
6578
6579                    let editor_width =
6580                        text_width - gutter_dimensions.margin - em_width - style.scrollbar_width;
6581
6582                    snapshot = self.editor.update(cx, |editor, cx| {
6583                        editor.last_bounds = Some(bounds);
6584                        editor.gutter_dimensions = gutter_dimensions;
6585                        editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
6586
6587                        if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
6588                            snapshot
6589                        } else {
6590                            let wrap_width = match editor.soft_wrap_mode(cx) {
6591                                SoftWrap::GitDiff => None,
6592                                SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
6593                                SoftWrap::EditorWidth => Some(editor_width),
6594                                SoftWrap::Column(column) => Some(column as f32 * em_advance),
6595                                SoftWrap::Bounded(column) => {
6596                                    Some(editor_width.min(column as f32 * em_advance))
6597                                }
6598                            };
6599
6600                            if editor.set_wrap_width(wrap_width, cx) {
6601                                editor.snapshot(window, cx)
6602                            } else {
6603                                snapshot
6604                            }
6605                        }
6606                    });
6607
6608                    let wrap_guides = self
6609                        .editor
6610                        .read(cx)
6611                        .wrap_guides(cx)
6612                        .iter()
6613                        .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
6614                        .collect::<SmallVec<[_; 2]>>();
6615
6616                    let hitbox = window.insert_hitbox(bounds, false);
6617                    let gutter_hitbox =
6618                        window.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
6619                    let text_hitbox = window.insert_hitbox(
6620                        Bounds {
6621                            origin: gutter_hitbox.top_right(),
6622                            size: size(text_width, bounds.size.height),
6623                        },
6624                        false,
6625                    );
6626                    // Offset the content_bounds from the text_bounds by the gutter margin (which
6627                    // is roughly half a character wide) to make hit testing work more like how we want.
6628                    let content_origin =
6629                        text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
6630
6631                    let scrollbar_bounds =
6632                        Bounds::from_corners(content_origin, bounds.bottom_right());
6633
6634                    let height_in_lines = scrollbar_bounds.size.height / line_height;
6635
6636                    // NOTE: The max row number in the current file, minus one
6637                    let max_row = snapshot.max_point().row().as_f32();
6638
6639                    // NOTE: The max scroll position for the top of the window
6640                    let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
6641                        (max_row - height_in_lines + 1.).max(0.)
6642                    } else {
6643                        let settings = EditorSettings::get_global(cx);
6644                        match settings.scroll_beyond_last_line {
6645                            ScrollBeyondLastLine::OnePage => max_row,
6646                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
6647                            ScrollBeyondLastLine::VerticalScrollMargin => {
6648                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
6649                                    .max(0.)
6650                            }
6651                        }
6652                    };
6653
6654                    // TODO: Autoscrolling for both axes
6655                    let mut autoscroll_request = None;
6656                    let mut autoscroll_containing_element = false;
6657                    let mut autoscroll_horizontally = false;
6658                    self.editor.update(cx, |editor, cx| {
6659                        autoscroll_request = editor.autoscroll_request();
6660                        autoscroll_containing_element =
6661                            autoscroll_request.is_some() || editor.has_pending_selection();
6662                        // TODO: Is this horizontal or vertical?!
6663                        autoscroll_horizontally = editor.autoscroll_vertically(
6664                            bounds,
6665                            line_height,
6666                            max_scroll_top,
6667                            window,
6668                            cx,
6669                        );
6670                        snapshot = editor.snapshot(window, cx);
6671                    });
6672
6673                    let mut scroll_position = snapshot.scroll_position();
6674                    // The scroll position is a fractional point, the whole number of which represents
6675                    // the top of the window in terms of display rows.
6676                    let start_row = DisplayRow(scroll_position.y as u32);
6677                    let max_row = snapshot.max_point().row();
6678                    let end_row = cmp::min(
6679                        (scroll_position.y + height_in_lines).ceil() as u32,
6680                        max_row.next_row().0,
6681                    );
6682                    let end_row = DisplayRow(end_row);
6683
6684                    let row_infos = snapshot
6685                        .row_infos(start_row)
6686                        .take((start_row..end_row).len())
6687                        .collect::<Vec<RowInfo>>();
6688                    let is_row_soft_wrapped = |row: usize| {
6689                        row_infos
6690                            .get(row)
6691                            .map_or(true, |info| info.buffer_row.is_none())
6692                    };
6693
6694                    let start_anchor = if start_row == Default::default() {
6695                        Anchor::min()
6696                    } else {
6697                        snapshot.buffer_snapshot.anchor_before(
6698                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
6699                        )
6700                    };
6701                    let end_anchor = if end_row > max_row {
6702                        Anchor::max()
6703                    } else {
6704                        snapshot.buffer_snapshot.anchor_before(
6705                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
6706                        )
6707                    };
6708
6709                    let mut highlighted_rows = self
6710                        .editor
6711                        .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
6712
6713                    let is_light = cx.theme().appearance().is_light();
6714
6715                    for (ix, row_info) in row_infos.iter().enumerate() {
6716                        let Some(diff_status) = row_info.diff_status else {
6717                            continue;
6718                        };
6719
6720                        let staged_opacity = if is_light { 0.14 } else { 0.10 };
6721                        let unstaged_opacity = 0.04;
6722
6723                        let background_color = match diff_status.kind {
6724                            DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
6725                            DiffHunkStatusKind::Deleted => {
6726                                cx.theme().colors().version_control_deleted
6727                            }
6728                            DiffHunkStatusKind::Modified => {
6729                                debug_panic!("modified diff status for row info");
6730                                continue;
6731                            }
6732                        };
6733                        let background_color = if diff_status.has_secondary_hunk() {
6734                            background_color.opacity(unstaged_opacity)
6735                        } else {
6736                            background_color.opacity(staged_opacity)
6737                        };
6738
6739                        highlighted_rows
6740                            .entry(start_row + DisplayRow(ix as u32))
6741                            .or_insert(background_color.into());
6742                    }
6743
6744                    let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
6745                        start_anchor..end_anchor,
6746                        &snapshot.display_snapshot,
6747                        cx.theme().colors(),
6748                    );
6749                    let highlighted_gutter_ranges =
6750                        self.editor.read(cx).gutter_highlights_in_range(
6751                            start_anchor..end_anchor,
6752                            &snapshot.display_snapshot,
6753                            cx,
6754                        );
6755
6756                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
6757                        start_anchor..end_anchor,
6758                        &snapshot.display_snapshot,
6759                        cx,
6760                    );
6761
6762                    let (local_selections, selected_buffer_ids): (
6763                        Vec<Selection<Point>>,
6764                        Vec<BufferId>,
6765                    ) = self.editor.update(cx, |editor, cx| {
6766                        let all_selections = editor.selections.all::<Point>(cx);
6767                        let selected_buffer_ids = if editor.is_singleton(cx) {
6768                            Vec::new()
6769                        } else {
6770                            let mut selected_buffer_ids = Vec::with_capacity(all_selections.len());
6771
6772                            for selection in all_selections {
6773                                for buffer_id in snapshot
6774                                    .buffer_snapshot
6775                                    .buffer_ids_for_range(selection.range())
6776                                {
6777                                    if selected_buffer_ids.last() != Some(&buffer_id) {
6778                                        selected_buffer_ids.push(buffer_id);
6779                                    }
6780                                }
6781                            }
6782
6783                            selected_buffer_ids
6784                        };
6785
6786                        let mut selections = editor
6787                            .selections
6788                            .disjoint_in_range(start_anchor..end_anchor, cx);
6789                        selections.extend(editor.selections.pending(cx));
6790
6791                        (selections, selected_buffer_ids)
6792                    });
6793
6794                    let (selections, active_rows, newest_selection_head) = self.layout_selections(
6795                        start_anchor,
6796                        end_anchor,
6797                        &local_selections,
6798                        &snapshot,
6799                        start_row,
6800                        end_row,
6801                        window,
6802                        cx,
6803                    );
6804
6805                    let line_numbers = self.layout_line_numbers(
6806                        Some(&gutter_hitbox),
6807                        gutter_dimensions,
6808                        line_height,
6809                        scroll_position,
6810                        start_row..end_row,
6811                        &row_infos,
6812                        newest_selection_head,
6813                        &snapshot,
6814                        window,
6815                        cx,
6816                    );
6817
6818                    let mut crease_toggles =
6819                        window.with_element_namespace("crease_toggles", |window| {
6820                            self.layout_crease_toggles(
6821                                start_row..end_row,
6822                                &row_infos,
6823                                &active_rows,
6824                                &snapshot,
6825                                window,
6826                                cx,
6827                            )
6828                        });
6829                    let crease_trailers =
6830                        window.with_element_namespace("crease_trailers", |window| {
6831                            self.layout_crease_trailers(
6832                                row_infos.iter().copied(),
6833                                &snapshot,
6834                                window,
6835                                cx,
6836                            )
6837                        });
6838
6839                    let display_hunks = self.layout_gutter_diff_hunks(
6840                        line_height,
6841                        &gutter_hitbox,
6842                        start_row..end_row,
6843                        &snapshot,
6844                        window,
6845                        cx,
6846                    );
6847
6848                    let mut line_layouts = Self::layout_lines(
6849                        start_row..end_row,
6850                        &snapshot,
6851                        &self.style,
6852                        editor_width,
6853                        is_row_soft_wrapped,
6854                        window,
6855                        cx,
6856                    );
6857
6858                    let longest_line_blame_width = self
6859                        .editor
6860                        .update(cx, |editor, cx| {
6861                            if !editor.show_git_blame_inline {
6862                                return None;
6863                            }
6864                            let blame = editor.blame.as_ref()?;
6865                            let blame_entry = blame
6866                                .update(cx, |blame, cx| {
6867                                    let row_infos =
6868                                        snapshot.row_infos(snapshot.longest_row()).next()?;
6869                                    blame.blame_for_rows(&[row_infos], cx).next()
6870                                })
6871                                .flatten()?;
6872                            let mut element = render_inline_blame_entry(
6873                                self.editor.clone(),
6874                                blame,
6875                                blame_entry,
6876                                &style,
6877                                cx,
6878                            );
6879                            let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
6880                            Some(
6881                                element
6882                                    .layout_as_root(AvailableSpace::min_size(), window, cx)
6883                                    .width
6884                                    + inline_blame_padding,
6885                            )
6886                        })
6887                        .unwrap_or(Pixels::ZERO);
6888
6889                    let longest_line_width = layout_line(
6890                        snapshot.longest_row(),
6891                        &snapshot,
6892                        &style,
6893                        editor_width,
6894                        is_row_soft_wrapped,
6895                        window,
6896                        cx,
6897                    )
6898                    .width;
6899
6900                    let scrollbar_range_data = ScrollbarRangeData::new(
6901                        scrollbar_bounds,
6902                        letter_size,
6903                        &snapshot,
6904                        longest_line_width,
6905                        longest_line_blame_width,
6906                        &style,
6907                        editor_width,
6908                        cx,
6909                    );
6910
6911                    let scroll_range_bounds = scrollbar_range_data.scroll_range;
6912                    let mut scroll_width = scroll_range_bounds.size.width;
6913
6914                    let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
6915                        snapshot.sticky_header_excerpt(start_row)
6916                    } else {
6917                        None
6918                    };
6919                    let sticky_header_excerpt_id =
6920                        sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
6921
6922                    let blocks = window.with_element_namespace("blocks", |window| {
6923                        self.render_blocks(
6924                            start_row..end_row,
6925                            &snapshot,
6926                            &hitbox,
6927                            &text_hitbox,
6928                            editor_width,
6929                            &mut scroll_width,
6930                            &gutter_dimensions,
6931                            em_width,
6932                            gutter_dimensions.full_width(),
6933                            line_height,
6934                            &line_layouts,
6935                            &local_selections,
6936                            &selected_buffer_ids,
6937                            is_row_soft_wrapped,
6938                            sticky_header_excerpt_id,
6939                            window,
6940                            cx,
6941                        )
6942                    });
6943                    let mut blocks = match blocks {
6944                        Ok(blocks) => blocks,
6945                        Err(resized_blocks) => {
6946                            self.editor.update(cx, |editor, cx| {
6947                                editor.resize_blocks(resized_blocks, autoscroll_request, cx)
6948                            });
6949                            return self.prepaint(None, bounds, &mut (), window, cx);
6950                        }
6951                    };
6952
6953                    let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
6954                        window.with_element_namespace("blocks", |window| {
6955                            self.layout_sticky_buffer_header(
6956                                sticky_header_excerpt,
6957                                scroll_position.y,
6958                                line_height,
6959                                &snapshot,
6960                                &hitbox,
6961                                &selected_buffer_ids,
6962                                window,
6963                                cx,
6964                            )
6965                        })
6966                    });
6967
6968                    let start_buffer_row =
6969                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
6970                    let end_buffer_row =
6971                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
6972
6973                    let scroll_max = point(
6974                        ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
6975                        max_row.as_f32(),
6976                    );
6977
6978                    self.editor.update(cx, |editor, cx| {
6979                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
6980
6981                        let autoscrolled = if autoscroll_horizontally {
6982                            editor.autoscroll_horizontally(
6983                                start_row,
6984                                editor_width - (letter_size.width / 2.0) + style.scrollbar_width,
6985                                scroll_width,
6986                                em_width,
6987                                &line_layouts,
6988                                cx,
6989                            )
6990                        } else {
6991                            false
6992                        };
6993
6994                        if clamped || autoscrolled {
6995                            snapshot = editor.snapshot(window, cx);
6996                            scroll_position = snapshot.scroll_position();
6997                        }
6998                    });
6999
7000                    let scroll_pixel_position = point(
7001                        scroll_position.x * em_width,
7002                        scroll_position.y * line_height,
7003                    );
7004
7005                    let indent_guides = self.layout_indent_guides(
7006                        content_origin,
7007                        text_hitbox.origin,
7008                        start_buffer_row..end_buffer_row,
7009                        scroll_pixel_position,
7010                        line_height,
7011                        &snapshot,
7012                        window,
7013                        cx,
7014                    );
7015
7016                    let crease_trailers =
7017                        window.with_element_namespace("crease_trailers", |window| {
7018                            self.prepaint_crease_trailers(
7019                                crease_trailers,
7020                                &line_layouts,
7021                                line_height,
7022                                content_origin,
7023                                scroll_pixel_position,
7024                                em_width,
7025                                window,
7026                                cx,
7027                            )
7028                        });
7029
7030                    let (inline_completion_popover, inline_completion_popover_origin) = self
7031                        .editor
7032                        .update(cx, |editor, cx| {
7033                            editor.render_edit_prediction_popover(
7034                                &text_hitbox.bounds,
7035                                content_origin,
7036                                &snapshot,
7037                                start_row..end_row,
7038                                scroll_position.y,
7039                                scroll_position.y + height_in_lines,
7040                                &line_layouts,
7041                                line_height,
7042                                scroll_pixel_position,
7043                                newest_selection_head,
7044                                editor_width,
7045                                &style,
7046                                window,
7047                                cx,
7048                            )
7049                        })
7050                        .unzip();
7051
7052                    let mut inline_diagnostics = self.layout_inline_diagnostics(
7053                        &line_layouts,
7054                        &crease_trailers,
7055                        content_origin,
7056                        scroll_pixel_position,
7057                        inline_completion_popover_origin,
7058                        start_row,
7059                        end_row,
7060                        line_height,
7061                        em_width,
7062                        &style,
7063                        window,
7064                        cx,
7065                    );
7066
7067                    let mut inline_blame = None;
7068                    if let Some(newest_selection_head) = newest_selection_head {
7069                        let display_row = newest_selection_head.row();
7070                        if (start_row..end_row).contains(&display_row) {
7071                            let line_ix = display_row.minus(start_row) as usize;
7072                            let row_info = &row_infos[line_ix];
7073                            let line_layout = &line_layouts[line_ix];
7074                            let crease_trailer_layout = crease_trailers[line_ix].as_ref();
7075                            inline_blame = self.layout_inline_blame(
7076                                display_row,
7077                                row_info,
7078                                line_layout,
7079                                crease_trailer_layout,
7080                                em_width,
7081                                content_origin,
7082                                scroll_pixel_position,
7083                                line_height,
7084                                window,
7085                                cx,
7086                            );
7087                            if inline_blame.is_some() {
7088                                // Blame overrides inline diagnostics
7089                                inline_diagnostics.remove(&display_row);
7090                            }
7091                        }
7092                    }
7093
7094                    let blamed_display_rows = self.layout_blame_entries(
7095                        &row_infos,
7096                        em_width,
7097                        scroll_position,
7098                        line_height,
7099                        &gutter_hitbox,
7100                        gutter_dimensions.git_blame_entries_width,
7101                        window,
7102                        cx,
7103                    );
7104
7105                    let scroll_max = point(
7106                        ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7107                        max_scroll_top,
7108                    );
7109
7110                    self.editor.update(cx, |editor, cx| {
7111                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7112
7113                        let autoscrolled = if autoscroll_horizontally {
7114                            editor.autoscroll_horizontally(
7115                                start_row,
7116                                editor_width - (letter_size.width / 2.0) + style.scrollbar_width,
7117                                scroll_width,
7118                                em_width,
7119                                &line_layouts,
7120                                cx,
7121                            )
7122                        } else {
7123                            false
7124                        };
7125
7126                        if clamped || autoscrolled {
7127                            snapshot = editor.snapshot(window, cx);
7128                            scroll_position = snapshot.scroll_position();
7129                        }
7130                    });
7131
7132                    let line_elements = self.prepaint_lines(
7133                        start_row,
7134                        &mut line_layouts,
7135                        line_height,
7136                        scroll_pixel_position,
7137                        content_origin,
7138                        window,
7139                        cx,
7140                    );
7141
7142                    let mut block_start_rows = HashSet::default();
7143
7144                    window.with_element_namespace("blocks", |window| {
7145                        self.layout_blocks(
7146                            &mut blocks,
7147                            &mut block_start_rows,
7148                            &hitbox,
7149                            line_height,
7150                            scroll_pixel_position,
7151                            window,
7152                            cx,
7153                        );
7154                    });
7155
7156                    let cursors = self.collect_cursors(&snapshot, cx);
7157                    let visible_row_range = start_row..end_row;
7158                    let non_visible_cursors = cursors
7159                        .iter()
7160                        .any(|c| !visible_row_range.contains(&c.0.row()));
7161
7162                    let visible_cursors = self.layout_visible_cursors(
7163                        &snapshot,
7164                        &selections,
7165                        &block_start_rows,
7166                        start_row..end_row,
7167                        &line_layouts,
7168                        &text_hitbox,
7169                        content_origin,
7170                        scroll_position,
7171                        scroll_pixel_position,
7172                        line_height,
7173                        em_width,
7174                        em_advance,
7175                        autoscroll_containing_element,
7176                        window,
7177                        cx,
7178                    );
7179
7180                    let scrollbars_layout = self.layout_scrollbars(
7181                        &snapshot,
7182                        scrollbar_range_data,
7183                        scroll_position,
7184                        non_visible_cursors,
7185                        window,
7186                        cx,
7187                    );
7188
7189                    let gutter_settings = EditorSettings::get_global(cx).gutter;
7190
7191                    let rows_with_hunk_bounds = display_hunks
7192                        .iter()
7193                        .filter_map(|(hunk, hitbox)| Some((hunk, hitbox.as_ref()?.bounds)))
7194                        .fold(
7195                            HashMap::default(),
7196                            |mut rows_with_hunk_bounds, (hunk, bounds)| {
7197                                match hunk {
7198                                    DisplayDiffHunk::Folded { display_row } => {
7199                                        rows_with_hunk_bounds.insert(*display_row, bounds);
7200                                    }
7201                                    DisplayDiffHunk::Unfolded {
7202                                        display_row_range, ..
7203                                    } => {
7204                                        for display_row in display_row_range.iter_rows() {
7205                                            rows_with_hunk_bounds.insert(display_row, bounds);
7206                                        }
7207                                    }
7208                                }
7209                                rows_with_hunk_bounds
7210                            },
7211                        );
7212                    let mut code_actions_indicator = None;
7213                    if let Some(newest_selection_head) = newest_selection_head {
7214                        let newest_selection_point =
7215                            newest_selection_head.to_point(&snapshot.display_snapshot);
7216
7217                        if (start_row..end_row).contains(&newest_selection_head.row()) {
7218                            self.layout_cursor_popovers(
7219                                line_height,
7220                                &text_hitbox,
7221                                content_origin,
7222                                start_row,
7223                                scroll_pixel_position,
7224                                &line_layouts,
7225                                newest_selection_head,
7226                                newest_selection_point,
7227                                &style,
7228                                window,
7229                                cx,
7230                            );
7231
7232                            let show_code_actions = snapshot
7233                                .show_code_actions
7234                                .unwrap_or(gutter_settings.code_actions);
7235                            if show_code_actions {
7236                                let newest_selection_point =
7237                                    newest_selection_head.to_point(&snapshot.display_snapshot);
7238                                if !snapshot
7239                                    .is_line_folded(MultiBufferRow(newest_selection_point.row))
7240                                {
7241                                    let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
7242                                        MultiBufferRow(newest_selection_point.row),
7243                                    );
7244                                    if let Some((buffer, range)) = buffer {
7245                                        let buffer_id = buffer.remote_id();
7246                                        let row = range.start.row;
7247                                        let has_test_indicator = self
7248                                            .editor
7249                                            .read(cx)
7250                                            .tasks
7251                                            .contains_key(&(buffer_id, row));
7252
7253                                        if !has_test_indicator {
7254                                            code_actions_indicator = self
7255                                                .layout_code_actions_indicator(
7256                                                    line_height,
7257                                                    newest_selection_head,
7258                                                    scroll_pixel_position,
7259                                                    &gutter_dimensions,
7260                                                    &gutter_hitbox,
7261                                                    &rows_with_hunk_bounds,
7262                                                    window,
7263                                                    cx,
7264                                                );
7265                                        }
7266                                    }
7267                                }
7268                            }
7269                        }
7270                    }
7271
7272                    self.layout_gutter_menu(
7273                        line_height,
7274                        &text_hitbox,
7275                        content_origin,
7276                        scroll_pixel_position,
7277                        gutter_dimensions.width - gutter_dimensions.left_padding,
7278                        window,
7279                        cx,
7280                    );
7281
7282                    let test_indicators = if gutter_settings.runnables {
7283                        self.layout_run_indicators(
7284                            line_height,
7285                            start_row..end_row,
7286                            scroll_pixel_position,
7287                            &gutter_dimensions,
7288                            &gutter_hitbox,
7289                            &rows_with_hunk_bounds,
7290                            &snapshot,
7291                            window,
7292                            cx,
7293                        )
7294                    } else {
7295                        Vec::new()
7296                    };
7297
7298                    self.layout_signature_help(
7299                        &hitbox,
7300                        content_origin,
7301                        scroll_pixel_position,
7302                        newest_selection_head,
7303                        start_row,
7304                        &line_layouts,
7305                        line_height,
7306                        em_width,
7307                        window,
7308                        cx,
7309                    );
7310
7311                    if !cx.has_active_drag() {
7312                        self.layout_hover_popovers(
7313                            &snapshot,
7314                            &hitbox,
7315                            &text_hitbox,
7316                            start_row..end_row,
7317                            content_origin,
7318                            scroll_pixel_position,
7319                            &line_layouts,
7320                            line_height,
7321                            em_width,
7322                            window,
7323                            cx,
7324                        );
7325                    }
7326
7327                    let mouse_context_menu = self.layout_mouse_context_menu(
7328                        &snapshot,
7329                        start_row..end_row,
7330                        content_origin,
7331                        window,
7332                        cx,
7333                    );
7334
7335                    window.with_element_namespace("crease_toggles", |window| {
7336                        self.prepaint_crease_toggles(
7337                            &mut crease_toggles,
7338                            line_height,
7339                            &gutter_dimensions,
7340                            gutter_settings,
7341                            scroll_pixel_position,
7342                            &gutter_hitbox,
7343                            window,
7344                            cx,
7345                        )
7346                    });
7347
7348                    let invisible_symbol_font_size = font_size / 2.;
7349                    let tab_invisible = window
7350                        .text_system()
7351                        .shape_line(
7352                            "".into(),
7353                            invisible_symbol_font_size,
7354                            &[TextRun {
7355                                len: "".len(),
7356                                font: self.style.text.font(),
7357                                color: cx.theme().colors().editor_invisible,
7358                                background_color: None,
7359                                underline: None,
7360                                strikethrough: None,
7361                            }],
7362                        )
7363                        .unwrap();
7364                    let space_invisible = window
7365                        .text_system()
7366                        .shape_line(
7367                            "".into(),
7368                            invisible_symbol_font_size,
7369                            &[TextRun {
7370                                len: "".len(),
7371                                font: self.style.text.font(),
7372                                color: cx.theme().colors().editor_invisible,
7373                                background_color: None,
7374                                underline: None,
7375                                strikethrough: None,
7376                            }],
7377                        )
7378                        .unwrap();
7379
7380                    let mode = snapshot.mode;
7381
7382                    let position_map = Rc::new(PositionMap {
7383                        size: bounds.size,
7384                        visible_row_range,
7385                        scroll_pixel_position,
7386                        scroll_max,
7387                        line_layouts,
7388                        line_height,
7389                        em_width,
7390                        em_advance,
7391                        snapshot,
7392                        gutter_hitbox: gutter_hitbox.clone(),
7393                        text_hitbox: text_hitbox.clone(),
7394                    });
7395
7396                    self.editor.update(cx, |editor, _| {
7397                        editor.last_position_map = Some(position_map.clone())
7398                    });
7399
7400                    let diff_hunk_controls = self.layout_diff_hunk_controls(
7401                        start_row..end_row,
7402                        &row_infos,
7403                        &text_hitbox,
7404                        &position_map,
7405                        newest_selection_head,
7406                        line_height,
7407                        scroll_pixel_position,
7408                        &display_hunks,
7409                        self.editor.clone(),
7410                        window,
7411                        cx,
7412                    );
7413
7414                    EditorLayout {
7415                        mode,
7416                        position_map,
7417                        visible_display_row_range: start_row..end_row,
7418                        wrap_guides,
7419                        indent_guides,
7420                        hitbox,
7421                        gutter_hitbox,
7422                        display_hunks,
7423                        content_origin,
7424                        scrollbars_layout,
7425                        active_rows,
7426                        highlighted_rows,
7427                        highlighted_ranges,
7428                        highlighted_gutter_ranges,
7429                        redacted_ranges,
7430                        line_elements,
7431                        line_numbers,
7432                        blamed_display_rows,
7433                        inline_diagnostics,
7434                        inline_blame,
7435                        blocks,
7436                        cursors,
7437                        visible_cursors,
7438                        selections,
7439                        inline_completion_popover,
7440                        diff_hunk_controls,
7441                        mouse_context_menu,
7442                        test_indicators,
7443                        code_actions_indicator,
7444                        crease_toggles,
7445                        crease_trailers,
7446                        tab_invisible,
7447                        space_invisible,
7448                        sticky_buffer_header,
7449                    }
7450                })
7451            })
7452        })
7453    }
7454
7455    fn paint(
7456        &mut self,
7457        _: Option<&GlobalElementId>,
7458        bounds: Bounds<gpui::Pixels>,
7459        _: &mut Self::RequestLayoutState,
7460        layout: &mut Self::PrepaintState,
7461        window: &mut Window,
7462        cx: &mut App,
7463    ) {
7464        let focus_handle = self.editor.focus_handle(cx);
7465        let key_context = self
7466            .editor
7467            .update(cx, |editor, cx| editor.key_context(window, cx));
7468
7469        window.set_key_context(key_context);
7470        window.handle_input(
7471            &focus_handle,
7472            ElementInputHandler::new(bounds, self.editor.clone()),
7473            cx,
7474        );
7475        self.register_actions(window, cx);
7476        self.register_key_listeners(window, cx, layout);
7477
7478        let text_style = TextStyleRefinement {
7479            font_size: Some(self.style.text.font_size),
7480            line_height: Some(self.style.text.line_height),
7481            ..Default::default()
7482        };
7483        let rem_size = self.rem_size(cx);
7484        window.with_rem_size(rem_size, |window| {
7485            window.with_text_style(Some(text_style), |window| {
7486                window.with_content_mask(Some(ContentMask { bounds }), |window| {
7487                    self.paint_mouse_listeners(layout, window, cx);
7488                    self.paint_background(layout, window, cx);
7489                    self.paint_indent_guides(layout, window, cx);
7490
7491                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
7492                        self.paint_blamed_display_rows(layout, window, cx);
7493                        self.paint_line_numbers(layout, window, cx);
7494                    }
7495
7496                    self.paint_text(layout, window, cx);
7497
7498                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
7499                        self.paint_gutter_highlights(layout, window, cx);
7500                        self.paint_gutter_indicators(layout, window, cx);
7501                    }
7502
7503                    if !layout.blocks.is_empty() {
7504                        window.with_element_namespace("blocks", |window| {
7505                            self.paint_blocks(layout, window, cx);
7506                        });
7507                    }
7508
7509                    window.with_element_namespace("blocks", |window| {
7510                        if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
7511                            sticky_header.paint(window, cx)
7512                        }
7513                    });
7514
7515                    self.paint_scrollbars(layout, window, cx);
7516                    self.paint_inline_completion_popover(layout, window, cx);
7517                    self.paint_mouse_context_menu(layout, window, cx);
7518                });
7519            })
7520        })
7521    }
7522}
7523
7524pub(super) fn gutter_bounds(
7525    editor_bounds: Bounds<Pixels>,
7526    gutter_dimensions: GutterDimensions,
7527) -> Bounds<Pixels> {
7528    Bounds {
7529        origin: editor_bounds.origin,
7530        size: size(gutter_dimensions.width, editor_bounds.size.height),
7531    }
7532}
7533
7534struct ScrollbarRangeData {
7535    scrollbar_bounds: Bounds<Pixels>,
7536    scroll_range: Bounds<Pixels>,
7537    letter_size: Size<Pixels>,
7538}
7539
7540impl ScrollbarRangeData {
7541    #[allow(clippy::too_many_arguments)]
7542    pub fn new(
7543        scrollbar_bounds: Bounds<Pixels>,
7544        letter_size: Size<Pixels>,
7545        snapshot: &EditorSnapshot,
7546        longest_line_width: Pixels,
7547        longest_line_blame_width: Pixels,
7548        style: &EditorStyle,
7549        editor_width: Pixels,
7550        cx: &mut App,
7551    ) -> ScrollbarRangeData {
7552        // TODO: Simplify this function down, it requires a lot of parameters
7553        let max_row = snapshot.max_point().row();
7554        let text_bounds_size = size(longest_line_width, max_row.0 as f32 * letter_size.height);
7555
7556        let settings = EditorSettings::get_global(cx);
7557        let scroll_beyond_last_line: Pixels = match settings.scroll_beyond_last_line {
7558            ScrollBeyondLastLine::OnePage => px(scrollbar_bounds.size.height / letter_size.height),
7559            ScrollBeyondLastLine::Off => px(1.),
7560            ScrollBeyondLastLine::VerticalScrollMargin => px(1.0 + settings.vertical_scroll_margin),
7561        };
7562
7563        let right_margin = if longest_line_width + longest_line_blame_width >= editor_width {
7564            letter_size.width + style.scrollbar_width
7565        } else {
7566            px(0.0)
7567        };
7568
7569        let overscroll = size(
7570            right_margin + longest_line_blame_width,
7571            letter_size.height * scroll_beyond_last_line,
7572        );
7573
7574        let scroll_range = Bounds {
7575            origin: scrollbar_bounds.origin,
7576            size: text_bounds_size + overscroll,
7577        };
7578
7579        ScrollbarRangeData {
7580            scrollbar_bounds,
7581            scroll_range,
7582            letter_size,
7583        }
7584    }
7585}
7586
7587impl IntoElement for EditorElement {
7588    type Element = Self;
7589
7590    fn into_element(self) -> Self::Element {
7591        self
7592    }
7593}
7594
7595pub struct EditorLayout {
7596    position_map: Rc<PositionMap>,
7597    hitbox: Hitbox,
7598    gutter_hitbox: Hitbox,
7599    content_origin: gpui::Point<Pixels>,
7600    scrollbars_layout: AxisPair<Option<ScrollbarLayout>>,
7601    mode: EditorMode,
7602    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
7603    indent_guides: Option<Vec<IndentGuideLayout>>,
7604    visible_display_row_range: Range<DisplayRow>,
7605    active_rows: BTreeMap<DisplayRow, bool>,
7606    highlighted_rows: BTreeMap<DisplayRow, gpui::Background>,
7607    line_elements: SmallVec<[AnyElement; 1]>,
7608    line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
7609    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
7610    blamed_display_rows: Option<Vec<AnyElement>>,
7611    inline_diagnostics: HashMap<DisplayRow, AnyElement>,
7612    inline_blame: Option<AnyElement>,
7613    blocks: Vec<BlockLayout>,
7614    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7615    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7616    redacted_ranges: Vec<Range<DisplayPoint>>,
7617    cursors: Vec<(DisplayPoint, Hsla)>,
7618    visible_cursors: Vec<CursorLayout>,
7619    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
7620    code_actions_indicator: Option<AnyElement>,
7621    test_indicators: Vec<AnyElement>,
7622    crease_toggles: Vec<Option<AnyElement>>,
7623    diff_hunk_controls: Vec<AnyElement>,
7624    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
7625    inline_completion_popover: Option<AnyElement>,
7626    mouse_context_menu: Option<AnyElement>,
7627    tab_invisible: ShapedLine,
7628    space_invisible: ShapedLine,
7629    sticky_buffer_header: Option<AnyElement>,
7630}
7631
7632impl EditorLayout {
7633    fn line_end_overshoot(&self) -> Pixels {
7634        0.15 * self.position_map.line_height
7635    }
7636}
7637
7638struct LineNumberLayout {
7639    shaped_line: ShapedLine,
7640    hitbox: Option<Hitbox>,
7641    display_row: DisplayRow,
7642}
7643
7644struct ColoredRange<T> {
7645    start: T,
7646    end: T,
7647    color: Hsla,
7648}
7649
7650#[derive(Clone)]
7651struct ScrollbarLayout {
7652    hitbox: Hitbox,
7653    visible_range: Range<f32>,
7654    visible: bool,
7655    text_unit_size: Pixels,
7656    thumb_size: Pixels,
7657    axis: Axis,
7658}
7659
7660impl ScrollbarLayout {
7661    const BORDER_WIDTH: Pixels = px(1.0);
7662    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
7663    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
7664    // const MIN_THUMB_HEIGHT: Pixels = px(20.0);
7665
7666    fn thumb_bounds(&self) -> Bounds<Pixels> {
7667        match self.axis {
7668            Axis::Vertical => {
7669                let thumb_top = self.y_for_row(self.visible_range.start);
7670                let thumb_bottom = thumb_top + self.thumb_size;
7671                Bounds::from_corners(
7672                    point(self.hitbox.left(), thumb_top),
7673                    point(self.hitbox.right(), thumb_bottom),
7674                )
7675            }
7676            Axis::Horizontal => {
7677                let thumb_left =
7678                    self.hitbox.left() + self.visible_range.start * self.text_unit_size;
7679                let thumb_right = thumb_left + self.thumb_size;
7680                Bounds::from_corners(
7681                    point(thumb_left, self.hitbox.top()),
7682                    point(thumb_right, self.hitbox.bottom()),
7683                )
7684            }
7685        }
7686    }
7687
7688    fn y_for_row(&self, row: f32) -> Pixels {
7689        self.hitbox.top() + row * self.text_unit_size
7690    }
7691
7692    fn marker_quads_for_ranges(
7693        &self,
7694        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
7695        column: Option<usize>,
7696    ) -> Vec<PaintQuad> {
7697        struct MinMax {
7698            min: Pixels,
7699            max: Pixels,
7700        }
7701        let (x_range, height_limit) = if let Some(column) = column {
7702            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
7703            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
7704            let end = start + column_width;
7705            (
7706                Range { start, end },
7707                MinMax {
7708                    min: Self::MIN_MARKER_HEIGHT,
7709                    max: px(f32::MAX),
7710                },
7711            )
7712        } else {
7713            (
7714                Range {
7715                    start: Self::BORDER_WIDTH,
7716                    end: self.hitbox.size.width,
7717                },
7718                MinMax {
7719                    min: Self::LINE_MARKER_HEIGHT,
7720                    max: Self::LINE_MARKER_HEIGHT,
7721                },
7722            )
7723        };
7724
7725        let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
7726        let mut pixel_ranges = row_ranges
7727            .into_iter()
7728            .map(|range| {
7729                let start_y = row_to_y(range.start);
7730                let end_y = row_to_y(range.end)
7731                    + self
7732                        .text_unit_size
7733                        .max(height_limit.min)
7734                        .min(height_limit.max);
7735                ColoredRange {
7736                    start: start_y,
7737                    end: end_y,
7738                    color: range.color,
7739                }
7740            })
7741            .peekable();
7742
7743        let mut quads = Vec::new();
7744        while let Some(mut pixel_range) = pixel_ranges.next() {
7745            while let Some(next_pixel_range) = pixel_ranges.peek() {
7746                if pixel_range.end >= next_pixel_range.start - px(1.0)
7747                    && pixel_range.color == next_pixel_range.color
7748                {
7749                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
7750                    pixel_ranges.next();
7751                } else {
7752                    break;
7753                }
7754            }
7755
7756            let bounds = Bounds::from_corners(
7757                point(x_range.start, pixel_range.start),
7758                point(x_range.end, pixel_range.end),
7759            );
7760            quads.push(quad(
7761                bounds,
7762                Corners::default(),
7763                pixel_range.color,
7764                Edges::default(),
7765                Hsla::transparent_black(),
7766            ));
7767        }
7768
7769        quads
7770    }
7771}
7772
7773struct CreaseTrailerLayout {
7774    element: AnyElement,
7775    bounds: Bounds<Pixels>,
7776}
7777
7778pub(crate) struct PositionMap {
7779    pub size: Size<Pixels>,
7780    pub line_height: Pixels,
7781    pub scroll_pixel_position: gpui::Point<Pixels>,
7782    pub scroll_max: gpui::Point<f32>,
7783    pub em_width: Pixels,
7784    pub em_advance: Pixels,
7785    pub visible_row_range: Range<DisplayRow>,
7786    pub line_layouts: Vec<LineWithInvisibles>,
7787    pub snapshot: EditorSnapshot,
7788    pub text_hitbox: Hitbox,
7789    pub gutter_hitbox: Hitbox,
7790}
7791
7792#[derive(Debug, Copy, Clone)]
7793pub struct PointForPosition {
7794    pub previous_valid: DisplayPoint,
7795    pub next_valid: DisplayPoint,
7796    pub exact_unclipped: DisplayPoint,
7797    pub column_overshoot_after_line_end: u32,
7798}
7799
7800impl PointForPosition {
7801    pub fn as_valid(&self) -> Option<DisplayPoint> {
7802        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
7803            Some(self.previous_valid)
7804        } else {
7805            None
7806        }
7807    }
7808}
7809
7810impl PositionMap {
7811    pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
7812        let text_bounds = self.text_hitbox.bounds;
7813        let scroll_position = self.snapshot.scroll_position();
7814        let position = position - text_bounds.origin;
7815        let y = position.y.max(px(0.)).min(self.size.height);
7816        let x = position.x + (scroll_position.x * self.em_width);
7817        let row = ((y / self.line_height) + scroll_position.y) as u32;
7818
7819        let (column, x_overshoot_after_line_end) = if let Some(line) = self
7820            .line_layouts
7821            .get(row as usize - scroll_position.y as usize)
7822        {
7823            if let Some(ix) = line.index_for_x(x) {
7824                (ix as u32, px(0.))
7825            } else {
7826                (line.len as u32, px(0.).max(x - line.width))
7827            }
7828        } else {
7829            (0, x)
7830        };
7831
7832        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
7833        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
7834        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
7835
7836        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
7837        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
7838        PointForPosition {
7839            previous_valid,
7840            next_valid,
7841            exact_unclipped,
7842            column_overshoot_after_line_end,
7843        }
7844    }
7845}
7846
7847struct BlockLayout {
7848    id: BlockId,
7849    row: Option<DisplayRow>,
7850    element: AnyElement,
7851    available_space: Size<AvailableSpace>,
7852    style: BlockStyle,
7853}
7854
7855pub fn layout_line(
7856    row: DisplayRow,
7857    snapshot: &EditorSnapshot,
7858    style: &EditorStyle,
7859    text_width: Pixels,
7860    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
7861    window: &mut Window,
7862    cx: &mut App,
7863) -> LineWithInvisibles {
7864    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
7865    LineWithInvisibles::from_chunks(
7866        chunks,
7867        &style,
7868        MAX_LINE_LEN,
7869        1,
7870        snapshot.mode,
7871        text_width,
7872        is_row_soft_wrapped,
7873        window,
7874        cx,
7875    )
7876    .pop()
7877    .unwrap()
7878}
7879
7880#[derive(Debug)]
7881pub struct IndentGuideLayout {
7882    origin: gpui::Point<Pixels>,
7883    length: Pixels,
7884    single_indent_width: Pixels,
7885    depth: u32,
7886    active: bool,
7887    settings: IndentGuideSettings,
7888}
7889
7890pub struct CursorLayout {
7891    origin: gpui::Point<Pixels>,
7892    block_width: Pixels,
7893    line_height: Pixels,
7894    color: Hsla,
7895    shape: CursorShape,
7896    block_text: Option<ShapedLine>,
7897    cursor_name: Option<AnyElement>,
7898}
7899
7900#[derive(Debug)]
7901pub struct CursorName {
7902    string: SharedString,
7903    color: Hsla,
7904    is_top_row: bool,
7905}
7906
7907impl CursorLayout {
7908    pub fn new(
7909        origin: gpui::Point<Pixels>,
7910        block_width: Pixels,
7911        line_height: Pixels,
7912        color: Hsla,
7913        shape: CursorShape,
7914        block_text: Option<ShapedLine>,
7915    ) -> CursorLayout {
7916        CursorLayout {
7917            origin,
7918            block_width,
7919            line_height,
7920            color,
7921            shape,
7922            block_text,
7923            cursor_name: None,
7924        }
7925    }
7926
7927    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
7928        Bounds {
7929            origin: self.origin + origin,
7930            size: size(self.block_width, self.line_height),
7931        }
7932    }
7933
7934    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
7935        match self.shape {
7936            CursorShape::Bar => Bounds {
7937                origin: self.origin + origin,
7938                size: size(px(2.0), self.line_height),
7939            },
7940            CursorShape::Block | CursorShape::Hollow => Bounds {
7941                origin: self.origin + origin,
7942                size: size(self.block_width, self.line_height),
7943            },
7944            CursorShape::Underline => Bounds {
7945                origin: self.origin
7946                    + origin
7947                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
7948                size: size(self.block_width, px(2.0)),
7949            },
7950        }
7951    }
7952
7953    pub fn layout(
7954        &mut self,
7955        origin: gpui::Point<Pixels>,
7956        cursor_name: Option<CursorName>,
7957        window: &mut Window,
7958        cx: &mut App,
7959    ) {
7960        if let Some(cursor_name) = cursor_name {
7961            let bounds = self.bounds(origin);
7962            let text_size = self.line_height / 1.5;
7963
7964            let name_origin = if cursor_name.is_top_row {
7965                point(bounds.right() - px(1.), bounds.top())
7966            } else {
7967                match self.shape {
7968                    CursorShape::Bar => point(
7969                        bounds.right() - px(2.),
7970                        bounds.top() - text_size / 2. - px(1.),
7971                    ),
7972                    _ => point(
7973                        bounds.right() - px(1.),
7974                        bounds.top() - text_size / 2. - px(1.),
7975                    ),
7976                }
7977            };
7978            let mut name_element = div()
7979                .bg(self.color)
7980                .text_size(text_size)
7981                .px_0p5()
7982                .line_height(text_size + px(2.))
7983                .text_color(cursor_name.color)
7984                .child(cursor_name.string.clone())
7985                .into_any_element();
7986
7987            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
7988
7989            self.cursor_name = Some(name_element);
7990        }
7991    }
7992
7993    pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
7994        let bounds = self.bounds(origin);
7995
7996        //Draw background or border quad
7997        let cursor = if matches!(self.shape, CursorShape::Hollow) {
7998            outline(bounds, self.color)
7999        } else {
8000            fill(bounds, self.color)
8001        };
8002
8003        if let Some(name) = &mut self.cursor_name {
8004            name.paint(window, cx);
8005        }
8006
8007        window.paint_quad(cursor);
8008
8009        if let Some(block_text) = &self.block_text {
8010            block_text
8011                .paint(self.origin + origin, self.line_height, window, cx)
8012                .log_err();
8013        }
8014    }
8015
8016    pub fn shape(&self) -> CursorShape {
8017        self.shape
8018    }
8019}
8020
8021#[derive(Debug)]
8022pub struct HighlightedRange {
8023    pub start_y: Pixels,
8024    pub line_height: Pixels,
8025    pub lines: Vec<HighlightedRangeLine>,
8026    pub color: Hsla,
8027    pub corner_radius: Pixels,
8028}
8029
8030#[derive(Debug)]
8031pub struct HighlightedRangeLine {
8032    pub start_x: Pixels,
8033    pub end_x: Pixels,
8034}
8035
8036impl HighlightedRange {
8037    pub fn paint(&self, bounds: Bounds<Pixels>, window: &mut Window) {
8038        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
8039            self.paint_lines(self.start_y, &self.lines[0..1], bounds, window);
8040            self.paint_lines(
8041                self.start_y + self.line_height,
8042                &self.lines[1..],
8043                bounds,
8044                window,
8045            );
8046        } else {
8047            self.paint_lines(self.start_y, &self.lines, bounds, window);
8048        }
8049    }
8050
8051    fn paint_lines(
8052        &self,
8053        start_y: Pixels,
8054        lines: &[HighlightedRangeLine],
8055        _bounds: Bounds<Pixels>,
8056        window: &mut Window,
8057    ) {
8058        if lines.is_empty() {
8059            return;
8060        }
8061
8062        let first_line = lines.first().unwrap();
8063        let last_line = lines.last().unwrap();
8064
8065        let first_top_left = point(first_line.start_x, start_y);
8066        let first_top_right = point(first_line.end_x, start_y);
8067
8068        let curve_height = point(Pixels::ZERO, self.corner_radius);
8069        let curve_width = |start_x: Pixels, end_x: Pixels| {
8070            let max = (end_x - start_x) / 2.;
8071            let width = if max < self.corner_radius {
8072                max
8073            } else {
8074                self.corner_radius
8075            };
8076
8077            point(width, Pixels::ZERO)
8078        };
8079
8080        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
8081        let mut builder = gpui::PathBuilder::fill();
8082        builder.move_to(first_top_right - top_curve_width);
8083        builder.curve_to(first_top_right + curve_height, first_top_right);
8084
8085        let mut iter = lines.iter().enumerate().peekable();
8086        while let Some((ix, line)) = iter.next() {
8087            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
8088
8089            if let Some((_, next_line)) = iter.peek() {
8090                let next_top_right = point(next_line.end_x, bottom_right.y);
8091
8092                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
8093                    Ordering::Equal => {
8094                        builder.line_to(bottom_right);
8095                    }
8096                    Ordering::Less => {
8097                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
8098                        builder.line_to(bottom_right - curve_height);
8099                        if self.corner_radius > Pixels::ZERO {
8100                            builder.curve_to(bottom_right - curve_width, bottom_right);
8101                        }
8102                        builder.line_to(next_top_right + curve_width);
8103                        if self.corner_radius > Pixels::ZERO {
8104                            builder.curve_to(next_top_right + curve_height, next_top_right);
8105                        }
8106                    }
8107                    Ordering::Greater => {
8108                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
8109                        builder.line_to(bottom_right - curve_height);
8110                        if self.corner_radius > Pixels::ZERO {
8111                            builder.curve_to(bottom_right + curve_width, bottom_right);
8112                        }
8113                        builder.line_to(next_top_right - curve_width);
8114                        if self.corner_radius > Pixels::ZERO {
8115                            builder.curve_to(next_top_right + curve_height, next_top_right);
8116                        }
8117                    }
8118                }
8119            } else {
8120                let curve_width = curve_width(line.start_x, line.end_x);
8121                builder.line_to(bottom_right - curve_height);
8122                if self.corner_radius > Pixels::ZERO {
8123                    builder.curve_to(bottom_right - curve_width, bottom_right);
8124                }
8125
8126                let bottom_left = point(line.start_x, bottom_right.y);
8127                builder.line_to(bottom_left + curve_width);
8128                if self.corner_radius > Pixels::ZERO {
8129                    builder.curve_to(bottom_left - curve_height, bottom_left);
8130                }
8131            }
8132        }
8133
8134        if first_line.start_x > last_line.start_x {
8135            let curve_width = curve_width(last_line.start_x, first_line.start_x);
8136            let second_top_left = point(last_line.start_x, start_y + self.line_height);
8137            builder.line_to(second_top_left + curve_height);
8138            if self.corner_radius > Pixels::ZERO {
8139                builder.curve_to(second_top_left + curve_width, second_top_left);
8140            }
8141            let first_bottom_left = point(first_line.start_x, second_top_left.y);
8142            builder.line_to(first_bottom_left - curve_width);
8143            if self.corner_radius > Pixels::ZERO {
8144                builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
8145            }
8146        }
8147
8148        builder.line_to(first_top_left + curve_height);
8149        if self.corner_radius > Pixels::ZERO {
8150            builder.curve_to(first_top_left + top_curve_width, first_top_left);
8151        }
8152        builder.line_to(first_top_right - top_curve_width);
8153
8154        if let Ok(path) = builder.build() {
8155            window.paint_path(path, self.color);
8156        }
8157    }
8158}
8159
8160enum CursorPopoverType {
8161    CodeContextMenu,
8162    EditPrediction,
8163}
8164
8165pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8166    (delta.pow(1.5) / 100.0).into()
8167}
8168
8169fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8170    (delta.pow(1.2) / 300.0).into()
8171}
8172
8173pub fn register_action<T: Action>(
8174    editor: &Entity<Editor>,
8175    window: &mut Window,
8176    listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
8177) {
8178    let editor = editor.clone();
8179    window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
8180        let action = action.downcast_ref().unwrap();
8181        if phase == DispatchPhase::Bubble {
8182            editor.update(cx, |editor, cx| {
8183                listener(editor, action, window, cx);
8184            })
8185        }
8186    })
8187}
8188
8189fn compute_auto_height_layout(
8190    editor: &mut Editor,
8191    max_lines: usize,
8192    max_line_number_width: Pixels,
8193    known_dimensions: Size<Option<Pixels>>,
8194    available_width: AvailableSpace,
8195    window: &mut Window,
8196    cx: &mut Context<Editor>,
8197) -> Option<Size<Pixels>> {
8198    let width = known_dimensions.width.or({
8199        if let AvailableSpace::Definite(available_width) = available_width {
8200            Some(available_width)
8201        } else {
8202            None
8203        }
8204    })?;
8205    if let Some(height) = known_dimensions.height {
8206        return Some(size(width, height));
8207    }
8208
8209    let style = editor.style.as_ref().unwrap();
8210    let font_id = window.text_system().resolve_font(&style.text.font());
8211    let font_size = style.text.font_size.to_pixels(window.rem_size());
8212    let line_height = style.text.line_height_in_pixels(window.rem_size());
8213    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8214
8215    let mut snapshot = editor.snapshot(window, cx);
8216    let gutter_dimensions = snapshot
8217        .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
8218        .unwrap_or_default();
8219
8220    editor.gutter_dimensions = gutter_dimensions;
8221    let text_width = width - gutter_dimensions.width;
8222    let overscroll = size(em_width, px(0.));
8223
8224    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
8225    if editor.set_wrap_width(Some(editor_width), cx) {
8226        snapshot = editor.snapshot(window, cx);
8227    }
8228
8229    let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
8230    let height = scroll_height
8231        .max(line_height)
8232        .min(line_height * max_lines as f32);
8233
8234    Some(size(width, height))
8235}
8236
8237#[cfg(test)]
8238mod tests {
8239    use super::*;
8240    use crate::{
8241        display_map::{BlockPlacement, BlockProperties},
8242        editor_tests::{init_test, update_test_language_settings},
8243        Editor, MultiBuffer,
8244    };
8245    use gpui::{TestAppContext, VisualTestContext};
8246    use language::language_settings;
8247    use log::info;
8248    use std::num::NonZeroU32;
8249    use util::test::sample_text;
8250
8251    #[gpui::test]
8252    fn test_shape_line_numbers(cx: &mut TestAppContext) {
8253        init_test(cx, |_| {});
8254        let window = cx.add_window(|window, cx| {
8255            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
8256            Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8257        });
8258
8259        let editor = window.root(cx).unwrap();
8260        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
8261        let line_height = window
8262            .update(cx, |_, window, _| {
8263                style.text.line_height_in_pixels(window.rem_size())
8264            })
8265            .unwrap();
8266        let element = EditorElement::new(&editor, style);
8267        let snapshot = window
8268            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
8269            .unwrap();
8270
8271        let layouts = cx
8272            .update_window(*window, |_, window, cx| {
8273                element.layout_line_numbers(
8274                    None,
8275                    GutterDimensions {
8276                        left_padding: Pixels::ZERO,
8277                        right_padding: Pixels::ZERO,
8278                        width: px(30.0),
8279                        margin: Pixels::ZERO,
8280                        git_blame_entries_width: None,
8281                    },
8282                    line_height,
8283                    gpui::Point::default(),
8284                    DisplayRow(0)..DisplayRow(6),
8285                    &(0..6)
8286                        .map(|row| RowInfo {
8287                            buffer_row: Some(row),
8288                            ..Default::default()
8289                        })
8290                        .collect::<Vec<_>>(),
8291                    Some(DisplayPoint::new(DisplayRow(0), 0)),
8292                    &snapshot,
8293                    window,
8294                    cx,
8295                )
8296            })
8297            .unwrap();
8298        assert_eq!(layouts.len(), 6);
8299
8300        let relative_rows = window
8301            .update(cx, |editor, window, cx| {
8302                let snapshot = editor.snapshot(window, cx);
8303                element.calculate_relative_line_numbers(
8304                    &snapshot,
8305                    &(DisplayRow(0)..DisplayRow(6)),
8306                    Some(DisplayRow(3)),
8307                )
8308            })
8309            .unwrap();
8310        assert_eq!(relative_rows[&DisplayRow(0)], 3);
8311        assert_eq!(relative_rows[&DisplayRow(1)], 2);
8312        assert_eq!(relative_rows[&DisplayRow(2)], 1);
8313        // current line has no relative number
8314        assert_eq!(relative_rows[&DisplayRow(4)], 1);
8315        assert_eq!(relative_rows[&DisplayRow(5)], 2);
8316
8317        // works if cursor is before screen
8318        let relative_rows = window
8319            .update(cx, |editor, window, cx| {
8320                let snapshot = editor.snapshot(window, cx);
8321                element.calculate_relative_line_numbers(
8322                    &snapshot,
8323                    &(DisplayRow(3)..DisplayRow(6)),
8324                    Some(DisplayRow(1)),
8325                )
8326            })
8327            .unwrap();
8328        assert_eq!(relative_rows.len(), 3);
8329        assert_eq!(relative_rows[&DisplayRow(3)], 2);
8330        assert_eq!(relative_rows[&DisplayRow(4)], 3);
8331        assert_eq!(relative_rows[&DisplayRow(5)], 4);
8332
8333        // works if cursor is after screen
8334        let relative_rows = window
8335            .update(cx, |editor, window, cx| {
8336                let snapshot = editor.snapshot(window, cx);
8337                element.calculate_relative_line_numbers(
8338                    &snapshot,
8339                    &(DisplayRow(0)..DisplayRow(3)),
8340                    Some(DisplayRow(6)),
8341                )
8342            })
8343            .unwrap();
8344        assert_eq!(relative_rows.len(), 3);
8345        assert_eq!(relative_rows[&DisplayRow(0)], 5);
8346        assert_eq!(relative_rows[&DisplayRow(1)], 4);
8347        assert_eq!(relative_rows[&DisplayRow(2)], 3);
8348    }
8349
8350    #[gpui::test]
8351    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
8352        init_test(cx, |_| {});
8353
8354        let window = cx.add_window(|window, cx| {
8355            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
8356            Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8357        });
8358        let cx = &mut VisualTestContext::from_window(*window, cx);
8359        let editor = window.root(cx).unwrap();
8360        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8361
8362        window
8363            .update(cx, |editor, window, cx| {
8364                editor.cursor_shape = CursorShape::Block;
8365                editor.change_selections(None, window, cx, |s| {
8366                    s.select_ranges([
8367                        Point::new(0, 0)..Point::new(1, 0),
8368                        Point::new(3, 2)..Point::new(3, 3),
8369                        Point::new(5, 6)..Point::new(6, 0),
8370                    ]);
8371                });
8372            })
8373            .unwrap();
8374
8375        let (_, state) = cx.draw(
8376            point(px(500.), px(500.)),
8377            size(px(500.), px(500.)),
8378            |_, _| EditorElement::new(&editor, style),
8379        );
8380
8381        assert_eq!(state.selections.len(), 1);
8382        let local_selections = &state.selections[0].1;
8383        assert_eq!(local_selections.len(), 3);
8384        // moves cursor back one line
8385        assert_eq!(
8386            local_selections[0].head,
8387            DisplayPoint::new(DisplayRow(0), 6)
8388        );
8389        assert_eq!(
8390            local_selections[0].range,
8391            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
8392        );
8393
8394        // moves cursor back one column
8395        assert_eq!(
8396            local_selections[1].range,
8397            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
8398        );
8399        assert_eq!(
8400            local_selections[1].head,
8401            DisplayPoint::new(DisplayRow(3), 2)
8402        );
8403
8404        // leaves cursor on the max point
8405        assert_eq!(
8406            local_selections[2].range,
8407            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
8408        );
8409        assert_eq!(
8410            local_selections[2].head,
8411            DisplayPoint::new(DisplayRow(6), 0)
8412        );
8413
8414        // active lines does not include 1 (even though the range of the selection does)
8415        assert_eq!(
8416            state.active_rows.keys().cloned().collect::<Vec<_>>(),
8417            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
8418        );
8419
8420        // multi-buffer support
8421        // in DisplayPoint coordinates, this is what we're dealing with:
8422        //  0: [[file
8423        //  1:   header
8424        //  2:   section]]
8425        //  3: aaaaaa
8426        //  4: bbbbbb
8427        //  5: cccccc
8428        //  6:
8429        //  7: [[footer]]
8430        //  8: [[header]]
8431        //  9: ffffff
8432        // 10: gggggg
8433        // 11: hhhhhh
8434        // 12:
8435        // 13: [[footer]]
8436        // 14: [[file
8437        // 15:   header
8438        // 16:   section]]
8439        // 17: bbbbbb
8440        // 18: cccccc
8441        // 19: dddddd
8442        // 20: [[footer]]
8443        let window = cx.add_window(|window, cx| {
8444            let buffer = MultiBuffer::build_multi(
8445                [
8446                    (
8447                        &(sample_text(8, 6, 'a') + "\n"),
8448                        vec![
8449                            Point::new(0, 0)..Point::new(3, 0),
8450                            Point::new(4, 0)..Point::new(7, 0),
8451                        ],
8452                    ),
8453                    (
8454                        &(sample_text(8, 6, 'a') + "\n"),
8455                        vec![Point::new(1, 0)..Point::new(3, 0)],
8456                    ),
8457                ],
8458                cx,
8459            );
8460            Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8461        });
8462        let editor = window.root(cx).unwrap();
8463        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8464        let _state = window.update(cx, |editor, window, cx| {
8465            editor.cursor_shape = CursorShape::Block;
8466            editor.change_selections(None, window, cx, |s| {
8467                s.select_display_ranges([
8468                    DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
8469                    DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
8470                ]);
8471            });
8472        });
8473
8474        let (_, state) = cx.draw(
8475            point(px(500.), px(500.)),
8476            size(px(500.), px(500.)),
8477            |_, _| EditorElement::new(&editor, style),
8478        );
8479        assert_eq!(state.selections.len(), 1);
8480        let local_selections = &state.selections[0].1;
8481        assert_eq!(local_selections.len(), 2);
8482
8483        // moves cursor on excerpt boundary back a line
8484        // and doesn't allow selection to bleed through
8485        assert_eq!(
8486            local_selections[0].range,
8487            DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
8488        );
8489        assert_eq!(
8490            local_selections[0].head,
8491            DisplayPoint::new(DisplayRow(6), 0)
8492        );
8493        // moves cursor on buffer boundary back two lines
8494        // and doesn't allow selection to bleed through
8495        assert_eq!(
8496            local_selections[1].range,
8497            DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
8498        );
8499        assert_eq!(
8500            local_selections[1].head,
8501            DisplayPoint::new(DisplayRow(12), 0)
8502        );
8503    }
8504
8505    #[gpui::test]
8506    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
8507        init_test(cx, |_| {});
8508
8509        let window = cx.add_window(|window, cx| {
8510            let buffer = MultiBuffer::build_simple("", cx);
8511            Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8512        });
8513        let cx = &mut VisualTestContext::from_window(*window, cx);
8514        let editor = window.root(cx).unwrap();
8515        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8516        window
8517            .update(cx, |editor, window, cx| {
8518                editor.set_placeholder_text("hello", cx);
8519                editor.insert_blocks(
8520                    [BlockProperties {
8521                        style: BlockStyle::Fixed,
8522                        placement: BlockPlacement::Above(Anchor::min()),
8523                        height: 3,
8524                        render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
8525                        priority: 0,
8526                    }],
8527                    None,
8528                    cx,
8529                );
8530
8531                // Blur the editor so that it displays placeholder text.
8532                window.blur();
8533            })
8534            .unwrap();
8535
8536        let (_, state) = cx.draw(
8537            point(px(500.), px(500.)),
8538            size(px(500.), px(500.)),
8539            |_, _| EditorElement::new(&editor, style),
8540        );
8541        assert_eq!(state.position_map.line_layouts.len(), 4);
8542        assert_eq!(state.line_numbers.len(), 1);
8543        assert_eq!(
8544            state
8545                .line_numbers
8546                .get(&MultiBufferRow(0))
8547                .map(|line_number| line_number.shaped_line.text.as_ref()),
8548            Some("1")
8549        );
8550    }
8551
8552    #[gpui::test]
8553    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
8554        const TAB_SIZE: u32 = 4;
8555
8556        let input_text = "\t \t|\t| a b";
8557        let expected_invisibles = vec![
8558            Invisible::Tab {
8559                line_start_offset: 0,
8560                line_end_offset: TAB_SIZE as usize,
8561            },
8562            Invisible::Whitespace {
8563                line_offset: TAB_SIZE as usize,
8564            },
8565            Invisible::Tab {
8566                line_start_offset: TAB_SIZE as usize + 1,
8567                line_end_offset: TAB_SIZE as usize * 2,
8568            },
8569            Invisible::Tab {
8570                line_start_offset: TAB_SIZE as usize * 2 + 1,
8571                line_end_offset: TAB_SIZE as usize * 3,
8572            },
8573            Invisible::Whitespace {
8574                line_offset: TAB_SIZE as usize * 3 + 1,
8575            },
8576            Invisible::Whitespace {
8577                line_offset: TAB_SIZE as usize * 3 + 3,
8578            },
8579        ];
8580        assert_eq!(
8581            expected_invisibles.len(),
8582            input_text
8583                .chars()
8584                .filter(|initial_char| initial_char.is_whitespace())
8585                .count(),
8586            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8587        );
8588
8589        for show_line_numbers in [true, false] {
8590            init_test(cx, |s| {
8591                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8592                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
8593            });
8594
8595            let actual_invisibles = collect_invisibles_from_new_editor(
8596                cx,
8597                EditorMode::Full,
8598                input_text,
8599                px(500.0),
8600                show_line_numbers,
8601            );
8602
8603            assert_eq!(expected_invisibles, actual_invisibles);
8604        }
8605    }
8606
8607    #[gpui::test]
8608    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
8609        init_test(cx, |s| {
8610            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8611            s.defaults.tab_size = NonZeroU32::new(4);
8612        });
8613
8614        for editor_mode_without_invisibles in [
8615            EditorMode::SingleLine { auto_width: false },
8616            EditorMode::AutoHeight { max_lines: 100 },
8617        ] {
8618            for show_line_numbers in [true, false] {
8619                let invisibles = collect_invisibles_from_new_editor(
8620                    cx,
8621                    editor_mode_without_invisibles,
8622                    "\t\t\t| | a b",
8623                    px(500.0),
8624                    show_line_numbers,
8625                );
8626                assert!(invisibles.is_empty(),
8627                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
8628            }
8629        }
8630    }
8631
8632    #[gpui::test]
8633    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
8634        let tab_size = 4;
8635        let input_text = "a\tbcd     ".repeat(9);
8636        let repeated_invisibles = [
8637            Invisible::Tab {
8638                line_start_offset: 1,
8639                line_end_offset: tab_size as usize,
8640            },
8641            Invisible::Whitespace {
8642                line_offset: tab_size as usize + 3,
8643            },
8644            Invisible::Whitespace {
8645                line_offset: tab_size as usize + 4,
8646            },
8647            Invisible::Whitespace {
8648                line_offset: tab_size as usize + 5,
8649            },
8650            Invisible::Whitespace {
8651                line_offset: tab_size as usize + 6,
8652            },
8653            Invisible::Whitespace {
8654                line_offset: tab_size as usize + 7,
8655            },
8656        ];
8657        let expected_invisibles = std::iter::once(repeated_invisibles)
8658            .cycle()
8659            .take(9)
8660            .flatten()
8661            .collect::<Vec<_>>();
8662        assert_eq!(
8663            expected_invisibles.len(),
8664            input_text
8665                .chars()
8666                .filter(|initial_char| initial_char.is_whitespace())
8667                .count(),
8668            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8669        );
8670        info!("Expected invisibles: {expected_invisibles:?}");
8671
8672        init_test(cx, |_| {});
8673
8674        // Put the same string with repeating whitespace pattern into editors of various size,
8675        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
8676        let resize_step = 10.0;
8677        let mut editor_width = 200.0;
8678        while editor_width <= 1000.0 {
8679            for show_line_numbers in [true, false] {
8680                update_test_language_settings(cx, |s| {
8681                    s.defaults.tab_size = NonZeroU32::new(tab_size);
8682                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8683                    s.defaults.preferred_line_length = Some(editor_width as u32);
8684                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
8685                });
8686
8687                let actual_invisibles = collect_invisibles_from_new_editor(
8688                    cx,
8689                    EditorMode::Full,
8690                    &input_text,
8691                    px(editor_width),
8692                    show_line_numbers,
8693                );
8694
8695                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
8696                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
8697                let mut i = 0;
8698                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
8699                    i = actual_index;
8700                    match expected_invisibles.get(i) {
8701                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
8702                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
8703                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
8704                            _ => {
8705                                panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
8706                            }
8707                        },
8708                        None => {
8709                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
8710                        }
8711                    }
8712                }
8713                let missing_expected_invisibles = &expected_invisibles[i + 1..];
8714                assert!(
8715                    missing_expected_invisibles.is_empty(),
8716                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
8717                );
8718
8719                editor_width += resize_step;
8720            }
8721        }
8722    }
8723
8724    fn collect_invisibles_from_new_editor(
8725        cx: &mut TestAppContext,
8726        editor_mode: EditorMode,
8727        input_text: &str,
8728        editor_width: Pixels,
8729        show_line_numbers: bool,
8730    ) -> Vec<Invisible> {
8731        info!(
8732            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
8733            editor_width.0
8734        );
8735        let window = cx.add_window(|window, cx| {
8736            let buffer = MultiBuffer::build_simple(input_text, cx);
8737            Editor::new(editor_mode, buffer, None, true, window, cx)
8738        });
8739        let cx = &mut VisualTestContext::from_window(*window, cx);
8740        let editor = window.root(cx).unwrap();
8741
8742        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8743        window
8744            .update(cx, |editor, _, cx| {
8745                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
8746                editor.set_wrap_width(Some(editor_width), cx);
8747                editor.set_show_line_numbers(show_line_numbers, cx);
8748            })
8749            .unwrap();
8750        let (_, state) = cx.draw(
8751            point(px(500.), px(500.)),
8752            size(px(500.), px(500.)),
8753            |_, _| EditorElement::new(&editor, style),
8754        );
8755        state
8756            .position_map
8757            .line_layouts
8758            .iter()
8759            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
8760            .cloned()
8761            .collect()
8762    }
8763}
8764
8765fn diff_hunk_controls(
8766    row: u32,
8767    status: &DiffHunkStatus,
8768    hunk_range: Range<Anchor>,
8769    line_height: Pixels,
8770    editor: &Entity<Editor>,
8771    cx: &mut App,
8772) -> AnyElement {
8773    h_flex()
8774        .h(line_height)
8775        .mr_1()
8776        .gap_1()
8777        .px_1()
8778        .pb_1()
8779        .border_b_1()
8780        .border_color(cx.theme().colors().border_variant)
8781        .rounded_b_lg()
8782        .bg(cx.theme().colors().editor_background)
8783        .gap_1()
8784        .child(if status.has_secondary_hunk() {
8785            Button::new(("stage", row as u64), "Stage")
8786                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
8787                .tooltip({
8788                    let focus_handle = editor.focus_handle(cx);
8789                    move |window, cx| {
8790                        Tooltip::for_action_in(
8791                            "Stage Hunk",
8792                            &::git::ToggleStaged,
8793                            &focus_handle,
8794                            window,
8795                            cx,
8796                        )
8797                    }
8798                })
8799                .on_click({
8800                    let editor = editor.clone();
8801                    move |_event, window, cx| {
8802                        editor.update(cx, |editor, cx| {
8803                            editor.stage_or_unstage_diff_hunks(
8804                                true,
8805                                &[hunk_range.start..hunk_range.start],
8806                                window,
8807                                cx,
8808                            );
8809                        });
8810                    }
8811                })
8812        } else {
8813            Button::new(("unstage", row as u64), "Unstage")
8814                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
8815                .tooltip({
8816                    let focus_handle = editor.focus_handle(cx);
8817                    move |window, cx| {
8818                        Tooltip::for_action_in(
8819                            "Unstage Hunk",
8820                            &::git::ToggleStaged,
8821                            &focus_handle,
8822                            window,
8823                            cx,
8824                        )
8825                    }
8826                })
8827                .on_click({
8828                    let editor = editor.clone();
8829                    move |_event, window, cx| {
8830                        editor.update(cx, |editor, cx| {
8831                            editor.stage_or_unstage_diff_hunks(
8832                                false,
8833                                &[hunk_range.start..hunk_range.start],
8834                                window,
8835                                cx,
8836                            );
8837                        });
8838                    }
8839                })
8840        })
8841        .child(
8842            Button::new("discard", "Restore")
8843                .tooltip({
8844                    let focus_handle = editor.focus_handle(cx);
8845                    move |window, cx| {
8846                        Tooltip::for_action_in(
8847                            "Restore Hunk",
8848                            &::git::Restore,
8849                            &focus_handle,
8850                            window,
8851                            cx,
8852                        )
8853                    }
8854                })
8855                .on_click({
8856                    let editor = editor.clone();
8857                    move |_event, window, cx| {
8858                        editor.update(cx, |editor, cx| {
8859                            let snapshot = editor.snapshot(window, cx);
8860                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
8861                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
8862                        });
8863                    }
8864                }),
8865        )
8866        .when(
8867            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
8868            |el| {
8869                el.child(
8870                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
8871                        .shape(IconButtonShape::Square)
8872                        .icon_size(IconSize::Small)
8873                        // .disabled(!has_multiple_hunks)
8874                        .tooltip({
8875                            let focus_handle = editor.focus_handle(cx);
8876                            move |window, cx| {
8877                                Tooltip::for_action_in(
8878                                    "Next Hunk",
8879                                    &GoToHunk::default(),
8880                                    &focus_handle,
8881                                    window,
8882                                    cx,
8883                                )
8884                            }
8885                        })
8886                        .on_click({
8887                            let editor = editor.clone();
8888                            move |_event, window, cx| {
8889                                editor.update(cx, |editor, cx| {
8890                                    let snapshot = editor.snapshot(window, cx);
8891                                    let position =
8892                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
8893                                    editor.go_to_hunk_after_or_before_position(
8894                                        &snapshot, position, true, true, window, cx,
8895                                    );
8896                                    editor.expand_selected_diff_hunks(cx);
8897                                });
8898                            }
8899                        }),
8900                )
8901                .child(
8902                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
8903                        .shape(IconButtonShape::Square)
8904                        .icon_size(IconSize::Small)
8905                        // .disabled(!has_multiple_hunks)
8906                        .tooltip({
8907                            let focus_handle = editor.focus_handle(cx);
8908                            move |window, cx| {
8909                                Tooltip::for_action_in(
8910                                    "Previous Hunk",
8911                                    &GoToPreviousHunk::default(),
8912                                    &focus_handle,
8913                                    window,
8914                                    cx,
8915                                )
8916                            }
8917                        })
8918                        .on_click({
8919                            let editor = editor.clone();
8920                            move |_event, window, cx| {
8921                                editor.update(cx, |editor, cx| {
8922                                    let snapshot = editor.snapshot(window, cx);
8923                                    let point =
8924                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
8925                                    editor.go_to_hunk_after_or_before_position(
8926                                        &snapshot, point, false, true, window, cx,
8927                                    );
8928                                    editor.expand_selected_diff_hunks(cx);
8929                                });
8930                            }
8931                        }),
8932                )
8933            },
8934        )
8935        .into_any_element()
8936}