element.rs

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