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