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