element.rs

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