element.rs

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