element.rs

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