element.rs

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