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