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