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