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