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