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