element.rs

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