element.rs

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