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