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