element.rs

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