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