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