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