element.rs

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