element.rs

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