element.rs

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