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