element.rs

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