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