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