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    GoToPrevHunk, GutterDimensions, HalfPageDown, HalfPageUp, HandleInput, HoveredCursor,
  22    InlineCompletion, JumpData, LineDown, LineUp, OpenExcerpts, PageDown, PageUp, Point,
  23    RevertSelectedHunks, RowExt, RowRangeExt, SelectPhase, SelectedTextHighlight, Selection,
  24    SoftWrap, StickyHeaderExcerpt, ToPoint, ToggleFold, 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 as _,
  38    FontId, 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() - px(100.);
4192
4193                    let mut element = diff_hunk_controls(
4194                        display_row_range.start.0,
4195                        multi_buffer_range.clone(),
4196                        line_height,
4197                        &editor,
4198                        cx,
4199                    );
4200                    element.prepaint_as_root(
4201                        gpui::Point::new(x, y),
4202                        size(px(100.0), line_height).into(),
4203                        window,
4204                        cx,
4205                    );
4206                    controls.push(element);
4207                }
4208            }
4209        }
4210
4211        controls
4212    }
4213
4214    #[allow(clippy::too_many_arguments)]
4215    fn layout_signature_help(
4216        &self,
4217        hitbox: &Hitbox,
4218        content_origin: gpui::Point<Pixels>,
4219        scroll_pixel_position: gpui::Point<Pixels>,
4220        newest_selection_head: Option<DisplayPoint>,
4221        start_row: DisplayRow,
4222        line_layouts: &[LineWithInvisibles],
4223        line_height: Pixels,
4224        em_width: Pixels,
4225        window: &mut Window,
4226        cx: &mut App,
4227    ) {
4228        if !self.editor.focus_handle(cx).is_focused(window) {
4229            return;
4230        }
4231        let Some(newest_selection_head) = newest_selection_head else {
4232            return;
4233        };
4234        let selection_row = newest_selection_head.row();
4235        if selection_row < start_row {
4236            return;
4237        }
4238        let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
4239        else {
4240            return;
4241        };
4242
4243        let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
4244            - scroll_pixel_position.x
4245            + content_origin.x;
4246        let start_y =
4247            selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
4248
4249        let max_size = size(
4250            (120. * em_width) // Default size
4251                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4252                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4253            (16. * line_height) // Default size
4254                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4255                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4256        );
4257
4258        let maybe_element = self.editor.update(cx, |editor, cx| {
4259            if let Some(popover) = editor.signature_help_state.popover_mut() {
4260                let element = popover.render(max_size, cx);
4261                Some(element)
4262            } else {
4263                None
4264            }
4265        });
4266        if let Some(mut element) = maybe_element {
4267            let window_size = window.viewport_size();
4268            let size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
4269            let mut point = point(start_x, start_y - size.height);
4270
4271            // Adjusting to ensure the popover does not overflow in the X-axis direction.
4272            if point.x + size.width >= window_size.width {
4273                point.x = window_size.width - size.width;
4274            }
4275
4276            window.defer_draw(element, point, 1)
4277        }
4278    }
4279
4280    fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
4281        window.paint_layer(layout.hitbox.bounds, |window| {
4282            let scroll_top = layout.position_map.snapshot.scroll_position().y;
4283            let gutter_bg = cx.theme().colors().editor_gutter_background;
4284            window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
4285            window.paint_quad(fill(
4286                layout.position_map.text_hitbox.bounds,
4287                self.style.background,
4288            ));
4289
4290            if let EditorMode::Full = layout.mode {
4291                let mut active_rows = layout.active_rows.iter().peekable();
4292                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
4293                    let mut end_row = start_row.0;
4294                    while active_rows
4295                        .peek()
4296                        .map_or(false, |(active_row, has_selection)| {
4297                            active_row.0 == end_row + 1
4298                                && *has_selection == contains_non_empty_selection
4299                        })
4300                    {
4301                        active_rows.next().unwrap();
4302                        end_row += 1;
4303                    }
4304
4305                    if !contains_non_empty_selection {
4306                        let highlight_h_range =
4307                            match layout.position_map.snapshot.current_line_highlight {
4308                                CurrentLineHighlight::Gutter => Some(Range {
4309                                    start: layout.hitbox.left(),
4310                                    end: layout.gutter_hitbox.right(),
4311                                }),
4312                                CurrentLineHighlight::Line => Some(Range {
4313                                    start: layout.position_map.text_hitbox.bounds.left(),
4314                                    end: layout.position_map.text_hitbox.bounds.right(),
4315                                }),
4316                                CurrentLineHighlight::All => Some(Range {
4317                                    start: layout.hitbox.left(),
4318                                    end: layout.hitbox.right(),
4319                                }),
4320                                CurrentLineHighlight::None => None,
4321                            };
4322                        if let Some(range) = highlight_h_range {
4323                            let active_line_bg = cx.theme().colors().editor_active_line_background;
4324                            let bounds = Bounds {
4325                                origin: point(
4326                                    range.start,
4327                                    layout.hitbox.origin.y
4328                                        + (start_row.as_f32() - scroll_top)
4329                                            * layout.position_map.line_height,
4330                                ),
4331                                size: size(
4332                                    range.end - range.start,
4333                                    layout.position_map.line_height
4334                                        * (end_row - start_row.0 + 1) as f32,
4335                                ),
4336                            };
4337                            window.paint_quad(fill(bounds, active_line_bg));
4338                        }
4339                    }
4340                }
4341
4342                let mut paint_highlight =
4343                    |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
4344                        let origin = point(
4345                            layout.hitbox.origin.x,
4346                            layout.hitbox.origin.y
4347                                + (highlight_row_start.as_f32() - scroll_top)
4348                                    * layout.position_map.line_height,
4349                        );
4350                        let size = size(
4351                            layout.hitbox.size.width,
4352                            layout.position_map.line_height
4353                                * highlight_row_end.next_row().minus(highlight_row_start) as f32,
4354                        );
4355                        window.paint_quad(fill(Bounds { origin, size }, color));
4356                    };
4357
4358                let mut current_paint: Option<(gpui::Background, Range<DisplayRow>)> = None;
4359                for (&new_row, &new_background) in &layout.highlighted_rows {
4360                    match &mut current_paint {
4361                        Some((current_background, current_range)) => {
4362                            let current_background = *current_background;
4363                            let new_range_started = current_background != new_background
4364                                || current_range.end.next_row() != new_row;
4365                            if new_range_started {
4366                                paint_highlight(
4367                                    current_range.start,
4368                                    current_range.end,
4369                                    current_background,
4370                                );
4371                                current_paint = Some((new_background, new_row..new_row));
4372                                continue;
4373                            } else {
4374                                current_range.end = current_range.end.next_row();
4375                            }
4376                        }
4377                        None => current_paint = Some((new_background, new_row..new_row)),
4378                    };
4379                }
4380                if let Some((color, range)) = current_paint {
4381                    paint_highlight(range.start, range.end, color);
4382                }
4383
4384                let scroll_left =
4385                    layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
4386
4387                for (wrap_position, active) in layout.wrap_guides.iter() {
4388                    let x = (layout.position_map.text_hitbox.origin.x
4389                        + *wrap_position
4390                        + layout.position_map.em_width / 2.)
4391                        - scroll_left;
4392
4393                    let show_scrollbars = {
4394                        let (scrollbar_x, scrollbar_y) = &layout.scrollbars_layout.as_xy();
4395
4396                        scrollbar_x.as_ref().map_or(false, |sx| sx.visible)
4397                            || scrollbar_y.as_ref().map_or(false, |sy| sy.visible)
4398                    };
4399
4400                    if x < layout.position_map.text_hitbox.origin.x
4401                        || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
4402                    {
4403                        continue;
4404                    }
4405
4406                    let color = if *active {
4407                        cx.theme().colors().editor_active_wrap_guide
4408                    } else {
4409                        cx.theme().colors().editor_wrap_guide
4410                    };
4411                    window.paint_quad(fill(
4412                        Bounds {
4413                            origin: point(x, layout.position_map.text_hitbox.origin.y),
4414                            size: size(px(1.), layout.position_map.text_hitbox.size.height),
4415                        },
4416                        color,
4417                    ));
4418                }
4419            }
4420        })
4421    }
4422
4423    fn paint_indent_guides(
4424        &mut self,
4425        layout: &mut EditorLayout,
4426        window: &mut Window,
4427        cx: &mut App,
4428    ) {
4429        let Some(indent_guides) = &layout.indent_guides else {
4430            return;
4431        };
4432
4433        let faded_color = |color: Hsla, alpha: f32| {
4434            let mut faded = color;
4435            faded.a = alpha;
4436            faded
4437        };
4438
4439        for indent_guide in indent_guides {
4440            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
4441            let settings = indent_guide.settings;
4442
4443            // TODO fixed for now, expose them through themes later
4444            const INDENT_AWARE_ALPHA: f32 = 0.2;
4445            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
4446            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
4447            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
4448
4449            let line_color = match (settings.coloring, indent_guide.active) {
4450                (IndentGuideColoring::Disabled, _) => None,
4451                (IndentGuideColoring::Fixed, false) => {
4452                    Some(cx.theme().colors().editor_indent_guide)
4453                }
4454                (IndentGuideColoring::Fixed, true) => {
4455                    Some(cx.theme().colors().editor_indent_guide_active)
4456                }
4457                (IndentGuideColoring::IndentAware, false) => {
4458                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
4459                }
4460                (IndentGuideColoring::IndentAware, true) => {
4461                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
4462                }
4463            };
4464
4465            let background_color = match (settings.background_coloring, indent_guide.active) {
4466                (IndentGuideBackgroundColoring::Disabled, _) => None,
4467                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
4468                    indent_accent_colors,
4469                    INDENT_AWARE_BACKGROUND_ALPHA,
4470                )),
4471                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
4472                    indent_accent_colors,
4473                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
4474                )),
4475            };
4476
4477            let requested_line_width = if indent_guide.active {
4478                settings.active_line_width
4479            } else {
4480                settings.line_width
4481            }
4482            .clamp(1, 10);
4483            let mut line_indicator_width = 0.;
4484            if let Some(color) = line_color {
4485                window.paint_quad(fill(
4486                    Bounds {
4487                        origin: indent_guide.origin,
4488                        size: size(px(requested_line_width as f32), indent_guide.length),
4489                    },
4490                    color,
4491                ));
4492                line_indicator_width = requested_line_width as f32;
4493            }
4494
4495            if let Some(color) = background_color {
4496                let width = indent_guide.single_indent_width - px(line_indicator_width);
4497                window.paint_quad(fill(
4498                    Bounds {
4499                        origin: point(
4500                            indent_guide.origin.x + px(line_indicator_width),
4501                            indent_guide.origin.y,
4502                        ),
4503                        size: size(width, indent_guide.length),
4504                    },
4505                    color,
4506                ));
4507            }
4508        }
4509    }
4510
4511    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4512        let is_singleton = self.editor.read(cx).is_singleton(cx);
4513
4514        let line_height = layout.position_map.line_height;
4515        window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
4516
4517        for LineNumberLayout {
4518            shaped_line,
4519            hitbox,
4520            display_row,
4521        } in layout.line_numbers.values()
4522        {
4523            let Some(hitbox) = hitbox else {
4524                continue;
4525            };
4526
4527            let is_active = layout.active_rows.contains_key(&display_row);
4528
4529            let color = if is_active {
4530                cx.theme().colors().editor_active_line_number
4531            } else if !is_singleton && hitbox.is_hovered(window) {
4532                cx.theme().colors().editor_hover_line_number
4533            } else {
4534                cx.theme().colors().editor_line_number
4535            };
4536
4537            let Some(line) = self
4538                .shape_line_number(shaped_line.text.clone(), color, window)
4539                .log_err()
4540            else {
4541                continue;
4542            };
4543            let Some(()) = line.paint(hitbox.origin, line_height, window, cx).log_err() else {
4544                continue;
4545            };
4546            // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
4547            // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
4548            if is_singleton {
4549                window.set_cursor_style(CursorStyle::IBeam, &hitbox);
4550            } else {
4551                window.set_cursor_style(CursorStyle::PointingHand, &hitbox);
4552            }
4553        }
4554    }
4555
4556    fn paint_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4557        if layout.display_hunks.is_empty() {
4558            return;
4559        }
4560
4561        let line_height = layout.position_map.line_height;
4562        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4563            for (hunk, hitbox) in &layout.display_hunks {
4564                let hunk_to_paint = match hunk {
4565                    DisplayDiffHunk::Folded { .. } => {
4566                        let hunk_bounds = Self::diff_hunk_bounds(
4567                            &layout.position_map.snapshot,
4568                            line_height,
4569                            layout.gutter_hitbox.bounds,
4570                            hunk,
4571                        );
4572                        Some((
4573                            hunk_bounds,
4574                            cx.theme().status().modified,
4575                            Corners::all(px(0.)),
4576                            &DiffHunkSecondaryStatus::None,
4577                        ))
4578                    }
4579                    DisplayDiffHunk::Unfolded {
4580                        status,
4581                        display_row_range,
4582                        ..
4583                    } => hitbox.as_ref().map(|hunk_hitbox| match status {
4584                        DiffHunkStatus::Added(secondary_status) => (
4585                            hunk_hitbox.bounds,
4586                            cx.theme().status().created,
4587                            Corners::all(px(0.)),
4588                            secondary_status,
4589                        ),
4590                        DiffHunkStatus::Modified(secondary_status) => (
4591                            hunk_hitbox.bounds,
4592                            cx.theme().status().modified,
4593                            Corners::all(px(0.)),
4594                            secondary_status,
4595                        ),
4596                        DiffHunkStatus::Removed(secondary_status)
4597                            if !display_row_range.is_empty() =>
4598                        {
4599                            (
4600                                hunk_hitbox.bounds,
4601                                cx.theme().status().deleted,
4602                                Corners::all(px(0.)),
4603                                secondary_status,
4604                            )
4605                        }
4606                        DiffHunkStatus::Removed(secondary_status) => (
4607                            Bounds::new(
4608                                point(
4609                                    hunk_hitbox.origin.x - hunk_hitbox.size.width,
4610                                    hunk_hitbox.origin.y,
4611                                ),
4612                                size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
4613                            ),
4614                            cx.theme().status().deleted,
4615                            Corners::all(1. * line_height),
4616                            secondary_status,
4617                        ),
4618                    }),
4619                };
4620
4621                if let Some((hunk_bounds, mut background_color, corner_radii, secondary_status)) =
4622                    hunk_to_paint
4623                {
4624                    if *secondary_status != DiffHunkSecondaryStatus::None {
4625                        background_color.a *= 0.6;
4626                    }
4627                    window.paint_quad(quad(
4628                        hunk_bounds,
4629                        corner_radii,
4630                        background_color,
4631                        Edges::default(),
4632                        transparent_black(),
4633                    ));
4634                }
4635            }
4636        });
4637    }
4638
4639    fn diff_hunk_bounds(
4640        snapshot: &EditorSnapshot,
4641        line_height: Pixels,
4642        gutter_bounds: Bounds<Pixels>,
4643        hunk: &DisplayDiffHunk,
4644    ) -> Bounds<Pixels> {
4645        let scroll_position = snapshot.scroll_position();
4646        let scroll_top = scroll_position.y * line_height;
4647        let gutter_strip_width = (0.275 * line_height).floor();
4648
4649        match hunk {
4650            DisplayDiffHunk::Folded { display_row, .. } => {
4651                let start_y = display_row.as_f32() * line_height - scroll_top;
4652                let end_y = start_y + line_height;
4653                let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4654                let highlight_size = size(gutter_strip_width, end_y - start_y);
4655                Bounds::new(highlight_origin, highlight_size)
4656            }
4657            DisplayDiffHunk::Unfolded {
4658                display_row_range,
4659                status,
4660                ..
4661            } => {
4662                if status.is_removed() && display_row_range.is_empty() {
4663                    let row = display_row_range.start;
4664
4665                    let offset = line_height / 2.;
4666                    let start_y = row.as_f32() * line_height - offset - scroll_top;
4667                    let end_y = start_y + line_height;
4668
4669                    let width = (0.35 * line_height).floor();
4670                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4671                    let highlight_size = size(width, end_y - start_y);
4672                    Bounds::new(highlight_origin, highlight_size)
4673                } else {
4674                    let start_row = display_row_range.start;
4675                    let end_row = display_row_range.end;
4676                    // If we're in a multibuffer, row range span might include an
4677                    // excerpt header, so if we were to draw the marker straight away,
4678                    // the hunk might include the rows of that header.
4679                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
4680                    // Instead, we simply check whether the range we're dealing with includes
4681                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
4682                    let end_row_in_current_excerpt = snapshot
4683                        .blocks_in_range(start_row..end_row)
4684                        .find_map(|(start_row, block)| {
4685                            if matches!(block, Block::ExcerptBoundary { .. }) {
4686                                Some(start_row)
4687                            } else {
4688                                None
4689                            }
4690                        })
4691                        .unwrap_or(end_row);
4692
4693                    let start_y = start_row.as_f32() * line_height - scroll_top;
4694                    let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
4695
4696                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4697                    let highlight_size = size(gutter_strip_width, end_y - start_y);
4698                    Bounds::new(highlight_origin, highlight_size)
4699                }
4700            }
4701        }
4702    }
4703
4704    fn paint_gutter_indicators(
4705        &self,
4706        layout: &mut EditorLayout,
4707        window: &mut Window,
4708        cx: &mut App,
4709    ) {
4710        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4711            window.with_element_namespace("crease_toggles", |window| {
4712                for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
4713                    crease_toggle.paint(window, cx);
4714                }
4715            });
4716
4717            for test_indicator in layout.test_indicators.iter_mut() {
4718                test_indicator.paint(window, cx);
4719            }
4720
4721            if let Some(indicator) = layout.code_actions_indicator.as_mut() {
4722                indicator.paint(window, cx);
4723            }
4724        });
4725    }
4726
4727    fn paint_gutter_highlights(
4728        &self,
4729        layout: &mut EditorLayout,
4730        window: &mut Window,
4731        cx: &mut App,
4732    ) {
4733        for (_, hunk_hitbox) in &layout.display_hunks {
4734            if let Some(hunk_hitbox) = hunk_hitbox {
4735                if !self
4736                    .editor
4737                    .read(cx)
4738                    .buffer()
4739                    .read(cx)
4740                    .all_diff_hunks_expanded()
4741                {
4742                    window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
4743                }
4744            }
4745        }
4746
4747        let show_git_gutter = layout
4748            .position_map
4749            .snapshot
4750            .show_git_diff_gutter
4751            .unwrap_or_else(|| {
4752                matches!(
4753                    ProjectSettings::get_global(cx).git.git_gutter,
4754                    Some(GitGutterSetting::TrackedFiles)
4755                )
4756            });
4757        if show_git_gutter {
4758            Self::paint_diff_hunks(layout, window, cx)
4759        }
4760
4761        let highlight_width = 0.275 * layout.position_map.line_height;
4762        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
4763        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4764            for (range, color) in &layout.highlighted_gutter_ranges {
4765                let start_row = if range.start.row() < layout.visible_display_row_range.start {
4766                    layout.visible_display_row_range.start - DisplayRow(1)
4767                } else {
4768                    range.start.row()
4769                };
4770                let end_row = if range.end.row() > layout.visible_display_row_range.end {
4771                    layout.visible_display_row_range.end + DisplayRow(1)
4772                } else {
4773                    range.end.row()
4774                };
4775
4776                let start_y = layout.gutter_hitbox.top()
4777                    + start_row.0 as f32 * layout.position_map.line_height
4778                    - layout.position_map.scroll_pixel_position.y;
4779                let end_y = layout.gutter_hitbox.top()
4780                    + (end_row.0 + 1) as f32 * layout.position_map.line_height
4781                    - layout.position_map.scroll_pixel_position.y;
4782                let bounds = Bounds::from_corners(
4783                    point(layout.gutter_hitbox.left(), start_y),
4784                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
4785                );
4786                window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
4787            }
4788        });
4789    }
4790
4791    fn paint_blamed_display_rows(
4792        &self,
4793        layout: &mut EditorLayout,
4794        window: &mut Window,
4795        cx: &mut App,
4796    ) {
4797        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
4798            return;
4799        };
4800
4801        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4802            for mut blame_element in blamed_display_rows.into_iter() {
4803                blame_element.paint(window, cx);
4804            }
4805        })
4806    }
4807
4808    fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4809        window.with_content_mask(
4810            Some(ContentMask {
4811                bounds: layout.position_map.text_hitbox.bounds,
4812            }),
4813            |window| {
4814                let cursor_style = if self
4815                    .editor
4816                    .read(cx)
4817                    .hovered_link_state
4818                    .as_ref()
4819                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
4820                {
4821                    CursorStyle::PointingHand
4822                } else {
4823                    CursorStyle::IBeam
4824                };
4825                window.set_cursor_style(cursor_style, &layout.position_map.text_hitbox);
4826
4827                let invisible_display_ranges = self.paint_highlights(layout, window);
4828                self.paint_lines(&invisible_display_ranges, layout, window, cx);
4829                self.paint_redactions(layout, window);
4830                self.paint_cursors(layout, window, cx);
4831                self.paint_inline_blame(layout, window, cx);
4832                self.paint_diff_hunk_controls(layout, window, cx);
4833                window.with_element_namespace("crease_trailers", |window| {
4834                    for trailer in layout.crease_trailers.iter_mut().flatten() {
4835                        trailer.element.paint(window, cx);
4836                    }
4837                });
4838            },
4839        )
4840    }
4841
4842    fn paint_highlights(
4843        &mut self,
4844        layout: &mut EditorLayout,
4845        window: &mut Window,
4846    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
4847        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4848            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
4849            let line_end_overshoot = 0.15 * layout.position_map.line_height;
4850            for (range, color) in &layout.highlighted_ranges {
4851                self.paint_highlighted_range(
4852                    range.clone(),
4853                    *color,
4854                    Pixels::ZERO,
4855                    line_end_overshoot,
4856                    layout,
4857                    window,
4858                );
4859            }
4860
4861            let corner_radius = 0.15 * layout.position_map.line_height;
4862
4863            for (player_color, selections) in &layout.selections {
4864                for selection in selections.iter() {
4865                    self.paint_highlighted_range(
4866                        selection.range.clone(),
4867                        player_color.selection,
4868                        corner_radius,
4869                        corner_radius * 2.,
4870                        layout,
4871                        window,
4872                    );
4873
4874                    if selection.is_local && !selection.range.is_empty() {
4875                        invisible_display_ranges.push(selection.range.clone());
4876                    }
4877                }
4878            }
4879            invisible_display_ranges
4880        })
4881    }
4882
4883    fn paint_lines(
4884        &mut self,
4885        invisible_display_ranges: &[Range<DisplayPoint>],
4886        layout: &mut EditorLayout,
4887        window: &mut Window,
4888        cx: &mut App,
4889    ) {
4890        let whitespace_setting = self
4891            .editor
4892            .read(cx)
4893            .buffer
4894            .read(cx)
4895            .settings_at(0, cx)
4896            .show_whitespaces;
4897
4898        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
4899            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
4900            line_with_invisibles.draw(
4901                layout,
4902                row,
4903                layout.content_origin,
4904                whitespace_setting,
4905                invisible_display_ranges,
4906                window,
4907                cx,
4908            )
4909        }
4910
4911        for line_element in &mut layout.line_elements {
4912            line_element.paint(window, cx);
4913        }
4914    }
4915
4916    fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
4917        if layout.redacted_ranges.is_empty() {
4918            return;
4919        }
4920
4921        let line_end_overshoot = layout.line_end_overshoot();
4922
4923        // A softer than perfect black
4924        let redaction_color = gpui::rgb(0x0e1111);
4925
4926        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4927            for range in layout.redacted_ranges.iter() {
4928                self.paint_highlighted_range(
4929                    range.clone(),
4930                    redaction_color.into(),
4931                    Pixels::ZERO,
4932                    line_end_overshoot,
4933                    layout,
4934                    window,
4935                );
4936            }
4937        });
4938    }
4939
4940    fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4941        for cursor in &mut layout.visible_cursors {
4942            cursor.paint(layout.content_origin, window, cx);
4943        }
4944    }
4945
4946    fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4947        let (scrollbar_x, scrollbar_y) = layout.scrollbars_layout.as_xy();
4948
4949        if let Some(scrollbar_layout) = scrollbar_x {
4950            let hitbox = scrollbar_layout.hitbox.clone();
4951            let text_unit_size = scrollbar_layout.text_unit_size;
4952            let visible_range = scrollbar_layout.visible_range.clone();
4953            let thumb_bounds = scrollbar_layout.thumb_bounds();
4954
4955            if scrollbar_layout.visible {
4956                window.paint_layer(hitbox.bounds, |window| {
4957                    window.paint_quad(quad(
4958                        hitbox.bounds,
4959                        Corners::default(),
4960                        cx.theme().colors().scrollbar_track_background,
4961                        Edges {
4962                            top: Pixels::ZERO,
4963                            right: Pixels::ZERO,
4964                            bottom: Pixels::ZERO,
4965                            left: Pixels::ZERO,
4966                        },
4967                        cx.theme().colors().scrollbar_track_border,
4968                    ));
4969
4970                    window.paint_quad(quad(
4971                        thumb_bounds,
4972                        Corners::default(),
4973                        cx.theme().colors().scrollbar_thumb_background,
4974                        Edges {
4975                            top: Pixels::ZERO,
4976                            right: Pixels::ZERO,
4977                            bottom: Pixels::ZERO,
4978                            left: ScrollbarLayout::BORDER_WIDTH,
4979                        },
4980                        cx.theme().colors().scrollbar_thumb_border,
4981                    ));
4982                })
4983            }
4984
4985            window.set_cursor_style(CursorStyle::Arrow, &hitbox);
4986
4987            window.on_mouse_event({
4988                let editor = self.editor.clone();
4989
4990                // there may be a way to avoid this clone
4991                let hitbox = hitbox.clone();
4992
4993                let mut mouse_position = window.mouse_position();
4994                move |event: &MouseMoveEvent, phase, window, cx| {
4995                    if phase == DispatchPhase::Capture {
4996                        return;
4997                    }
4998
4999                    editor.update(cx, |editor, cx| {
5000                        if event.pressed_button == Some(MouseButton::Left)
5001                            && editor
5002                                .scroll_manager
5003                                .is_dragging_scrollbar(Axis::Horizontal)
5004                        {
5005                            let x = mouse_position.x;
5006                            let new_x = event.position.x;
5007                            if (hitbox.left()..hitbox.right()).contains(&x) {
5008                                let mut position = editor.scroll_position(cx);
5009
5010                                position.x += (new_x - x) / text_unit_size;
5011                                if position.x < 0.0 {
5012                                    position.x = 0.0;
5013                                }
5014                                editor.set_scroll_position(position, window, cx);
5015                            }
5016
5017                            cx.stop_propagation();
5018                        } else {
5019                            editor.scroll_manager.set_is_dragging_scrollbar(
5020                                Axis::Horizontal,
5021                                false,
5022                                cx,
5023                            );
5024
5025                            if hitbox.is_hovered(window) {
5026                                editor.scroll_manager.show_scrollbar(window, cx);
5027                            }
5028                        }
5029                        mouse_position = event.position;
5030                    })
5031                }
5032            });
5033
5034            if self
5035                .editor
5036                .read(cx)
5037                .scroll_manager
5038                .is_dragging_scrollbar(Axis::Horizontal)
5039            {
5040                window.on_mouse_event({
5041                    let editor = self.editor.clone();
5042                    move |_: &MouseUpEvent, phase, _, cx| {
5043                        if phase == DispatchPhase::Capture {
5044                            return;
5045                        }
5046
5047                        editor.update(cx, |editor, cx| {
5048                            editor.scroll_manager.set_is_dragging_scrollbar(
5049                                Axis::Horizontal,
5050                                false,
5051                                cx,
5052                            );
5053                            cx.stop_propagation();
5054                        });
5055                    }
5056                });
5057            } else {
5058                window.on_mouse_event({
5059                    let editor = self.editor.clone();
5060
5061                    move |event: &MouseDownEvent, phase, window, cx| {
5062                        if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
5063                            return;
5064                        }
5065
5066                        editor.update(cx, |editor, cx| {
5067                            editor.scroll_manager.set_is_dragging_scrollbar(
5068                                Axis::Horizontal,
5069                                true,
5070                                cx,
5071                            );
5072
5073                            let x = event.position.x;
5074
5075                            if x < thumb_bounds.left() || thumb_bounds.right() < x {
5076                                let center_row =
5077                                    ((x - hitbox.left()) / text_unit_size).round() as u32;
5078                                let top_row = center_row.saturating_sub(
5079                                    (visible_range.end - visible_range.start) as u32 / 2,
5080                                );
5081
5082                                let mut position = editor.scroll_position(cx);
5083                                position.x = top_row as f32;
5084
5085                                editor.set_scroll_position(position, window, cx);
5086                            } else {
5087                                editor.scroll_manager.show_scrollbar(window, cx);
5088                            }
5089
5090                            cx.stop_propagation();
5091                        });
5092                    }
5093                });
5094            }
5095        }
5096
5097        if let Some(scrollbar_layout) = scrollbar_y {
5098            let hitbox = scrollbar_layout.hitbox.clone();
5099            let text_unit_size = scrollbar_layout.text_unit_size;
5100            let visible_range = scrollbar_layout.visible_range.clone();
5101            let thumb_bounds = scrollbar_layout.thumb_bounds();
5102
5103            if scrollbar_layout.visible {
5104                window.paint_layer(hitbox.bounds, |window| {
5105                    window.paint_quad(quad(
5106                        hitbox.bounds,
5107                        Corners::default(),
5108                        cx.theme().colors().scrollbar_track_background,
5109                        Edges {
5110                            top: Pixels::ZERO,
5111                            right: Pixels::ZERO,
5112                            bottom: Pixels::ZERO,
5113                            left: ScrollbarLayout::BORDER_WIDTH,
5114                        },
5115                        cx.theme().colors().scrollbar_track_border,
5116                    ));
5117
5118                    let fast_markers =
5119                        self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
5120                    // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
5121                    self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx);
5122
5123                    let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
5124                    for marker in markers.iter().chain(&fast_markers) {
5125                        let mut marker = marker.clone();
5126                        marker.bounds.origin += hitbox.origin;
5127                        window.paint_quad(marker);
5128                    }
5129
5130                    window.paint_quad(quad(
5131                        thumb_bounds,
5132                        Corners::default(),
5133                        cx.theme().colors().scrollbar_thumb_background,
5134                        Edges {
5135                            top: Pixels::ZERO,
5136                            right: Pixels::ZERO,
5137                            bottom: Pixels::ZERO,
5138                            left: ScrollbarLayout::BORDER_WIDTH,
5139                        },
5140                        cx.theme().colors().scrollbar_thumb_border,
5141                    ));
5142                });
5143            }
5144
5145            window.set_cursor_style(CursorStyle::Arrow, &hitbox);
5146
5147            window.on_mouse_event({
5148                let editor = self.editor.clone();
5149
5150                let hitbox = hitbox.clone();
5151
5152                let mut mouse_position = window.mouse_position();
5153                move |event: &MouseMoveEvent, phase, window, cx| {
5154                    if phase == DispatchPhase::Capture {
5155                        return;
5156                    }
5157
5158                    editor.update(cx, |editor, cx| {
5159                        if event.pressed_button == Some(MouseButton::Left)
5160                            && editor.scroll_manager.is_dragging_scrollbar(Axis::Vertical)
5161                        {
5162                            let y = mouse_position.y;
5163                            let new_y = event.position.y;
5164                            if (hitbox.top()..hitbox.bottom()).contains(&y) {
5165                                let mut position = editor.scroll_position(cx);
5166                                position.y += (new_y - y) / text_unit_size;
5167                                if position.y < 0.0 {
5168                                    position.y = 0.0;
5169                                }
5170                                editor.set_scroll_position(position, window, cx);
5171                            }
5172                        } else {
5173                            editor.scroll_manager.set_is_dragging_scrollbar(
5174                                Axis::Vertical,
5175                                false,
5176                                cx,
5177                            );
5178
5179                            if hitbox.is_hovered(window) {
5180                                editor.scroll_manager.show_scrollbar(window, cx);
5181                            }
5182                        }
5183                        mouse_position = event.position;
5184                    })
5185                }
5186            });
5187
5188            if self
5189                .editor
5190                .read(cx)
5191                .scroll_manager
5192                .is_dragging_scrollbar(Axis::Vertical)
5193            {
5194                window.on_mouse_event({
5195                    let editor = self.editor.clone();
5196                    move |_: &MouseUpEvent, phase, _, cx| {
5197                        if phase == DispatchPhase::Capture {
5198                            return;
5199                        }
5200
5201                        editor.update(cx, |editor, cx| {
5202                            editor.scroll_manager.set_is_dragging_scrollbar(
5203                                Axis::Vertical,
5204                                false,
5205                                cx,
5206                            );
5207                            cx.stop_propagation();
5208                        });
5209                    }
5210                });
5211            } else {
5212                window.on_mouse_event({
5213                    let editor = self.editor.clone();
5214
5215                    move |event: &MouseDownEvent, phase, window, cx| {
5216                        if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
5217                            return;
5218                        }
5219
5220                        editor.update(cx, |editor, cx| {
5221                            editor.scroll_manager.set_is_dragging_scrollbar(
5222                                Axis::Vertical,
5223                                true,
5224                                cx,
5225                            );
5226
5227                            let y = event.position.y;
5228                            if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
5229                                let center_row =
5230                                    ((y - hitbox.top()) / text_unit_size).round() as u32;
5231                                let top_row = center_row.saturating_sub(
5232                                    (visible_range.end - visible_range.start) as u32 / 2,
5233                                );
5234                                let mut position = editor.scroll_position(cx);
5235                                position.y = top_row as f32;
5236                                editor.set_scroll_position(position, window, cx);
5237                            } else {
5238                                editor.scroll_manager.show_scrollbar(window, cx);
5239                            }
5240
5241                            cx.stop_propagation();
5242                        });
5243                    }
5244                });
5245            }
5246        }
5247    }
5248
5249    fn collect_fast_scrollbar_markers(
5250        &self,
5251        layout: &EditorLayout,
5252        scrollbar_layout: &ScrollbarLayout,
5253        cx: &mut App,
5254    ) -> Vec<PaintQuad> {
5255        const LIMIT: usize = 100;
5256        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
5257            return vec![];
5258        }
5259        let cursor_ranges = layout
5260            .cursors
5261            .iter()
5262            .map(|(point, color)| ColoredRange {
5263                start: point.row(),
5264                end: point.row(),
5265                color: *color,
5266            })
5267            .collect_vec();
5268        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
5269    }
5270
5271    fn refresh_slow_scrollbar_markers(
5272        &self,
5273        layout: &EditorLayout,
5274        scrollbar_layout: &ScrollbarLayout,
5275        window: &mut Window,
5276        cx: &mut App,
5277    ) {
5278        self.editor.update(cx, |editor, cx| {
5279            if !editor.is_singleton(cx)
5280                || !editor
5281                    .scrollbar_marker_state
5282                    .should_refresh(scrollbar_layout.hitbox.size)
5283            {
5284                return;
5285            }
5286
5287            let scrollbar_layout = scrollbar_layout.clone();
5288            let background_highlights = editor.background_highlights.clone();
5289            let snapshot = layout.position_map.snapshot.clone();
5290            let theme = cx.theme().clone();
5291            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
5292
5293            editor.scrollbar_marker_state.dirty = false;
5294            editor.scrollbar_marker_state.pending_refresh =
5295                Some(cx.spawn_in(window, |editor, mut cx| async move {
5296                    let scrollbar_size = scrollbar_layout.hitbox.size;
5297                    let scrollbar_markers = cx
5298                        .background_spawn(async move {
5299                            let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
5300                            let mut marker_quads = Vec::new();
5301                            if scrollbar_settings.git_diff {
5302                                let marker_row_ranges =
5303                                    snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
5304                                        let start_display_row =
5305                                            MultiBufferPoint::new(hunk.row_range.start.0, 0)
5306                                                .to_display_point(&snapshot.display_snapshot)
5307                                                .row();
5308                                        let mut end_display_row =
5309                                            MultiBufferPoint::new(hunk.row_range.end.0, 0)
5310                                                .to_display_point(&snapshot.display_snapshot)
5311                                                .row();
5312                                        if end_display_row != start_display_row {
5313                                            end_display_row.0 -= 1;
5314                                        }
5315                                        let color = match &hunk.status() {
5316                                            DiffHunkStatus::Added(_) => theme.status().created,
5317                                            DiffHunkStatus::Modified(_) => theme.status().modified,
5318                                            DiffHunkStatus::Removed(_) => theme.status().deleted,
5319                                        };
5320                                        ColoredRange {
5321                                            start: start_display_row,
5322                                            end: end_display_row,
5323                                            color,
5324                                        }
5325                                    });
5326
5327                                marker_quads.extend(
5328                                    scrollbar_layout
5329                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
5330                                );
5331                            }
5332
5333                            for (background_highlight_id, (_, background_ranges)) in
5334                                background_highlights.iter()
5335                            {
5336                                let is_search_highlights = *background_highlight_id
5337                                    == TypeId::of::<BufferSearchHighlights>();
5338                                let is_text_highlights = *background_highlight_id
5339                                    == TypeId::of::<SelectedTextHighlight>();
5340                                let is_symbol_occurrences = *background_highlight_id
5341                                    == TypeId::of::<DocumentHighlightRead>()
5342                                    || *background_highlight_id
5343                                        == TypeId::of::<DocumentHighlightWrite>();
5344                                if (is_search_highlights && scrollbar_settings.search_results)
5345                                    || (is_text_highlights && scrollbar_settings.selected_text)
5346                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
5347                                {
5348                                    let mut color = theme.status().info;
5349                                    if is_symbol_occurrences {
5350                                        color.fade_out(0.5);
5351                                    }
5352                                    let marker_row_ranges = background_ranges.iter().map(|range| {
5353                                        let display_start = range
5354                                            .start
5355                                            .to_display_point(&snapshot.display_snapshot);
5356                                        let display_end =
5357                                            range.end.to_display_point(&snapshot.display_snapshot);
5358                                        ColoredRange {
5359                                            start: display_start.row(),
5360                                            end: display_end.row(),
5361                                            color,
5362                                        }
5363                                    });
5364                                    marker_quads.extend(
5365                                        scrollbar_layout
5366                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
5367                                    );
5368                                }
5369                            }
5370
5371                            if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
5372                                let diagnostics = snapshot
5373                                    .buffer_snapshot
5374                                    .diagnostics_in_range::<Point>(Point::zero()..max_point)
5375                                    // Don't show diagnostics the user doesn't care about
5376                                    .filter(|diagnostic| {
5377                                        match (
5378                                            scrollbar_settings.diagnostics,
5379                                            diagnostic.diagnostic.severity,
5380                                        ) {
5381                                            (ScrollbarDiagnostics::All, _) => true,
5382                                            (
5383                                                ScrollbarDiagnostics::Error,
5384                                                DiagnosticSeverity::ERROR,
5385                                            ) => true,
5386                                            (
5387                                                ScrollbarDiagnostics::Warning,
5388                                                DiagnosticSeverity::ERROR
5389                                                | DiagnosticSeverity::WARNING,
5390                                            ) => true,
5391                                            (
5392                                                ScrollbarDiagnostics::Information,
5393                                                DiagnosticSeverity::ERROR
5394                                                | DiagnosticSeverity::WARNING
5395                                                | DiagnosticSeverity::INFORMATION,
5396                                            ) => true,
5397                                            (_, _) => false,
5398                                        }
5399                                    })
5400                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
5401                                    .sorted_by_key(|diagnostic| {
5402                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
5403                                    });
5404
5405                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
5406                                    let start_display = diagnostic
5407                                        .range
5408                                        .start
5409                                        .to_display_point(&snapshot.display_snapshot);
5410                                    let end_display = diagnostic
5411                                        .range
5412                                        .end
5413                                        .to_display_point(&snapshot.display_snapshot);
5414                                    let color = match diagnostic.diagnostic.severity {
5415                                        DiagnosticSeverity::ERROR => theme.status().error,
5416                                        DiagnosticSeverity::WARNING => theme.status().warning,
5417                                        DiagnosticSeverity::INFORMATION => theme.status().info,
5418                                        _ => theme.status().hint,
5419                                    };
5420                                    ColoredRange {
5421                                        start: start_display.row(),
5422                                        end: end_display.row(),
5423                                        color,
5424                                    }
5425                                });
5426                                marker_quads.extend(
5427                                    scrollbar_layout
5428                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
5429                                );
5430                            }
5431
5432                            Arc::from(marker_quads)
5433                        })
5434                        .await;
5435
5436                    editor.update(&mut cx, |editor, cx| {
5437                        editor.scrollbar_marker_state.markers = scrollbar_markers;
5438                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
5439                        editor.scrollbar_marker_state.pending_refresh = None;
5440                        cx.notify();
5441                    })?;
5442
5443                    Ok(())
5444                }));
5445        });
5446    }
5447
5448    #[allow(clippy::too_many_arguments)]
5449    fn paint_highlighted_range(
5450        &self,
5451        range: Range<DisplayPoint>,
5452        color: Hsla,
5453        corner_radius: Pixels,
5454        line_end_overshoot: Pixels,
5455        layout: &EditorLayout,
5456        window: &mut Window,
5457    ) {
5458        let start_row = layout.visible_display_row_range.start;
5459        let end_row = layout.visible_display_row_range.end;
5460        if range.start != range.end {
5461            let row_range = if range.end.column() == 0 {
5462                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
5463            } else {
5464                cmp::max(range.start.row(), start_row)
5465                    ..cmp::min(range.end.row().next_row(), end_row)
5466            };
5467
5468            let highlighted_range = HighlightedRange {
5469                color,
5470                line_height: layout.position_map.line_height,
5471                corner_radius,
5472                start_y: layout.content_origin.y
5473                    + row_range.start.as_f32() * layout.position_map.line_height
5474                    - layout.position_map.scroll_pixel_position.y,
5475                lines: row_range
5476                    .iter_rows()
5477                    .map(|row| {
5478                        let line_layout =
5479                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
5480                        HighlightedRangeLine {
5481                            start_x: if row == range.start.row() {
5482                                layout.content_origin.x
5483                                    + line_layout.x_for_index(range.start.column() as usize)
5484                                    - layout.position_map.scroll_pixel_position.x
5485                            } else {
5486                                layout.content_origin.x
5487                                    - layout.position_map.scroll_pixel_position.x
5488                            },
5489                            end_x: if row == range.end.row() {
5490                                layout.content_origin.x
5491                                    + line_layout.x_for_index(range.end.column() as usize)
5492                                    - layout.position_map.scroll_pixel_position.x
5493                            } else {
5494                                layout.content_origin.x + line_layout.width + line_end_overshoot
5495                                    - layout.position_map.scroll_pixel_position.x
5496                            },
5497                        }
5498                    })
5499                    .collect(),
5500            };
5501
5502            highlighted_range.paint(layout.position_map.text_hitbox.bounds, window);
5503        }
5504    }
5505
5506    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5507        if let Some(mut inline_blame) = layout.inline_blame.take() {
5508            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5509                inline_blame.paint(window, cx);
5510            })
5511        }
5512    }
5513
5514    fn paint_diff_hunk_controls(
5515        &mut self,
5516        layout: &mut EditorLayout,
5517        window: &mut Window,
5518        cx: &mut App,
5519    ) {
5520        for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
5521            diff_hunk_control.paint(window, cx);
5522        }
5523    }
5524
5525    fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5526        for mut block in layout.blocks.drain(..) {
5527            block.element.paint(window, cx);
5528        }
5529    }
5530
5531    fn paint_inline_completion_popover(
5532        &mut self,
5533        layout: &mut EditorLayout,
5534        window: &mut Window,
5535        cx: &mut App,
5536    ) {
5537        if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
5538            inline_completion_popover.paint(window, cx);
5539        }
5540    }
5541
5542    fn paint_mouse_context_menu(
5543        &mut self,
5544        layout: &mut EditorLayout,
5545        window: &mut Window,
5546        cx: &mut App,
5547    ) {
5548        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
5549            mouse_context_menu.paint(window, cx);
5550        }
5551    }
5552
5553    fn paint_scroll_wheel_listener(
5554        &mut self,
5555        layout: &EditorLayout,
5556        window: &mut Window,
5557        cx: &mut App,
5558    ) {
5559        window.on_mouse_event({
5560            let position_map = layout.position_map.clone();
5561            let editor = self.editor.clone();
5562            let hitbox = layout.hitbox.clone();
5563            let mut delta = ScrollDelta::default();
5564
5565            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
5566            // accidentally turn off their scrolling.
5567            let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
5568
5569            move |event: &ScrollWheelEvent, phase, window, cx| {
5570                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
5571                    delta = delta.coalesce(event.delta);
5572                    editor.update(cx, |editor, cx| {
5573                        let position_map: &PositionMap = &position_map;
5574
5575                        let line_height = position_map.line_height;
5576                        let max_glyph_width = position_map.em_width;
5577                        let (delta, axis) = match delta {
5578                            gpui::ScrollDelta::Pixels(mut pixels) => {
5579                                //Trackpad
5580                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
5581                                (pixels, axis)
5582                            }
5583
5584                            gpui::ScrollDelta::Lines(lines) => {
5585                                //Not trackpad
5586                                let pixels =
5587                                    point(lines.x * max_glyph_width, lines.y * line_height);
5588                                (pixels, None)
5589                            }
5590                        };
5591
5592                        let current_scroll_position = position_map.snapshot.scroll_position();
5593                        let x = (current_scroll_position.x * max_glyph_width
5594                            - (delta.x * scroll_sensitivity))
5595                            / max_glyph_width;
5596                        let y = (current_scroll_position.y * line_height
5597                            - (delta.y * scroll_sensitivity))
5598                            / line_height;
5599                        let mut scroll_position =
5600                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
5601                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
5602                        if forbid_vertical_scroll {
5603                            scroll_position.y = current_scroll_position.y;
5604                        }
5605
5606                        if scroll_position != current_scroll_position {
5607                            editor.scroll(scroll_position, axis, window, cx);
5608                            cx.stop_propagation();
5609                        } else if y < 0. {
5610                            // Due to clamping, we may fail to detect cases of overscroll to the top;
5611                            // We want the scroll manager to get an update in such cases and detect the change of direction
5612                            // on the next frame.
5613                            cx.notify();
5614                        }
5615                    });
5616                }
5617            }
5618        });
5619    }
5620
5621    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5622        self.paint_scroll_wheel_listener(layout, window, cx);
5623
5624        window.on_mouse_event({
5625            let position_map = layout.position_map.clone();
5626            let editor = self.editor.clone();
5627            let diff_hunk_range =
5628                layout
5629                    .display_hunks
5630                    .iter()
5631                    .find_map(|(hunk, hunk_hitbox)| match hunk {
5632                        DisplayDiffHunk::Folded { .. } => None,
5633                        DisplayDiffHunk::Unfolded {
5634                            multi_buffer_range, ..
5635                        } => {
5636                            if hunk_hitbox
5637                                .as_ref()
5638                                .map(|hitbox| hitbox.is_hovered(window))
5639                                .unwrap_or(false)
5640                            {
5641                                Some(multi_buffer_range.clone())
5642                            } else {
5643                                None
5644                            }
5645                        }
5646                    });
5647            let line_numbers = layout.line_numbers.clone();
5648
5649            move |event: &MouseDownEvent, phase, window, cx| {
5650                if phase == DispatchPhase::Bubble {
5651                    match event.button {
5652                        MouseButton::Left => editor.update(cx, |editor, cx| {
5653                            let pending_mouse_down = editor
5654                                .pending_mouse_down
5655                                .get_or_insert_with(Default::default)
5656                                .clone();
5657
5658                            *pending_mouse_down.borrow_mut() = Some(event.clone());
5659
5660                            Self::mouse_left_down(
5661                                editor,
5662                                event,
5663                                diff_hunk_range.clone(),
5664                                &position_map,
5665                                line_numbers.as_ref(),
5666                                window,
5667                                cx,
5668                            );
5669                        }),
5670                        MouseButton::Right => editor.update(cx, |editor, cx| {
5671                            Self::mouse_right_down(editor, event, &position_map, window, cx);
5672                        }),
5673                        MouseButton::Middle => editor.update(cx, |editor, cx| {
5674                            Self::mouse_middle_down(editor, event, &position_map, window, cx);
5675                        }),
5676                        _ => {}
5677                    };
5678                }
5679            }
5680        });
5681
5682        window.on_mouse_event({
5683            let editor = self.editor.clone();
5684            let position_map = layout.position_map.clone();
5685
5686            move |event: &MouseUpEvent, phase, window, cx| {
5687                if phase == DispatchPhase::Bubble {
5688                    editor.update(cx, |editor, cx| {
5689                        Self::mouse_up(editor, event, &position_map, window, cx)
5690                    });
5691                }
5692            }
5693        });
5694
5695        window.on_mouse_event({
5696            let editor = self.editor.clone();
5697            let position_map = layout.position_map.clone();
5698            let mut captured_mouse_down = None;
5699
5700            move |event: &MouseUpEvent, phase, window, cx| match phase {
5701                // Clear the pending mouse down during the capture phase,
5702                // so that it happens even if another event handler stops
5703                // propagation.
5704                DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
5705                    let pending_mouse_down = editor
5706                        .pending_mouse_down
5707                        .get_or_insert_with(Default::default)
5708                        .clone();
5709
5710                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
5711                    if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
5712                        captured_mouse_down = pending_mouse_down.take();
5713                        window.refresh();
5714                    }
5715                }),
5716                // Fire click handlers during the bubble phase.
5717                DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
5718                    if let Some(mouse_down) = captured_mouse_down.take() {
5719                        let event = ClickEvent {
5720                            down: mouse_down,
5721                            up: event.clone(),
5722                        };
5723                        Self::click(editor, &event, &position_map, window, cx);
5724                    }
5725                }),
5726            }
5727        });
5728
5729        window.on_mouse_event({
5730            let position_map = layout.position_map.clone();
5731            let editor = self.editor.clone();
5732
5733            move |event: &MouseMoveEvent, phase, window, cx| {
5734                if phase == DispatchPhase::Bubble {
5735                    editor.update(cx, |editor, cx| {
5736                        if editor.hover_state.focused(window, cx) {
5737                            return;
5738                        }
5739                        if event.pressed_button == Some(MouseButton::Left)
5740                            || event.pressed_button == Some(MouseButton::Middle)
5741                        {
5742                            Self::mouse_dragged(editor, event, &position_map, window, cx)
5743                        }
5744
5745                        Self::mouse_moved(editor, event, &position_map, window, cx)
5746                    });
5747                }
5748            }
5749        });
5750    }
5751
5752    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
5753        bounds.top_right().x - self.style.scrollbar_width
5754    }
5755
5756    fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
5757        let style = &self.style;
5758        let font_size = style.text.font_size.to_pixels(window.rem_size());
5759        let layout = window
5760            .text_system()
5761            .shape_line(
5762                SharedString::from(" ".repeat(column)),
5763                font_size,
5764                &[TextRun {
5765                    len: column,
5766                    font: style.text.font(),
5767                    color: Hsla::default(),
5768                    background_color: None,
5769                    underline: None,
5770                    strikethrough: None,
5771                }],
5772            )
5773            .unwrap();
5774
5775        layout.width
5776    }
5777
5778    fn max_line_number_width(
5779        &self,
5780        snapshot: &EditorSnapshot,
5781        window: &mut Window,
5782        cx: &mut App,
5783    ) -> Pixels {
5784        let digit_count = (snapshot.widest_line_number() as f32).log10().floor() as usize + 1;
5785        self.column_pixels(digit_count, window, cx)
5786    }
5787
5788    fn shape_line_number(
5789        &self,
5790        text: SharedString,
5791        color: Hsla,
5792        window: &mut Window,
5793    ) -> anyhow::Result<ShapedLine> {
5794        let run = TextRun {
5795            len: text.len(),
5796            font: self.style.text.font(),
5797            color,
5798            background_color: None,
5799            underline: None,
5800            strikethrough: None,
5801        };
5802        window.text_system().shape_line(
5803            text,
5804            self.style.text.font_size.to_pixels(window.rem_size()),
5805            &[run],
5806        )
5807    }
5808}
5809
5810fn header_jump_data(
5811    snapshot: &EditorSnapshot,
5812    block_row_start: DisplayRow,
5813    height: u32,
5814    for_excerpt: &ExcerptInfo,
5815) -> JumpData {
5816    let range = &for_excerpt.range;
5817    let buffer = &for_excerpt.buffer;
5818    let jump_anchor = range
5819        .primary
5820        .as_ref()
5821        .map_or(range.context.start, |primary| primary.start);
5822
5823    let excerpt_start = range.context.start;
5824    let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
5825    let rows_from_excerpt_start = if jump_anchor == excerpt_start {
5826        0
5827    } else {
5828        let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
5829        jump_position.row.saturating_sub(excerpt_start_point.row)
5830    };
5831
5832    let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
5833        .saturating_sub(
5834            snapshot
5835                .scroll_anchor
5836                .scroll_position(&snapshot.display_snapshot)
5837                .y as u32,
5838        );
5839
5840    JumpData::MultiBufferPoint {
5841        excerpt_id: for_excerpt.id,
5842        anchor: jump_anchor,
5843        position: jump_position,
5844        line_offset_from_top,
5845    }
5846}
5847
5848pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
5849
5850impl AcceptEditPredictionBinding {
5851    pub fn keystroke(&self) -> Option<&Keystroke> {
5852        if let Some(binding) = self.0.as_ref() {
5853            match &binding.keystrokes() {
5854                [keystroke] => Some(keystroke),
5855                _ => None,
5856            }
5857        } else {
5858            None
5859        }
5860    }
5861}
5862
5863#[allow(clippy::too_many_arguments)]
5864fn prepaint_gutter_button(
5865    button: IconButton,
5866    row: DisplayRow,
5867    line_height: Pixels,
5868    gutter_dimensions: &GutterDimensions,
5869    scroll_pixel_position: gpui::Point<Pixels>,
5870    gutter_hitbox: &Hitbox,
5871    rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
5872    window: &mut Window,
5873    cx: &mut App,
5874) -> AnyElement {
5875    let mut button = button.into_any_element();
5876    let available_space = size(
5877        AvailableSpace::MinContent,
5878        AvailableSpace::Definite(line_height),
5879    );
5880    let indicator_size = button.layout_as_root(available_space, window, cx);
5881
5882    let blame_width = gutter_dimensions.git_blame_entries_width;
5883    let gutter_width = rows_with_hunk_bounds
5884        .get(&row)
5885        .map(|bounds| bounds.size.width);
5886    let left_offset = blame_width.max(gutter_width).unwrap_or_default();
5887
5888    let mut x = left_offset;
5889    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
5890        - indicator_size.width
5891        - left_offset;
5892    x += available_width / 2.;
5893
5894    let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
5895    y += (line_height - indicator_size.height) / 2.;
5896
5897    button.prepaint_as_root(
5898        gutter_hitbox.origin + point(x, y),
5899        available_space,
5900        window,
5901        cx,
5902    );
5903    button
5904}
5905
5906fn render_inline_blame_entry(
5907    editor: Entity<Editor>,
5908    blame: &gpui::Entity<GitBlame>,
5909    blame_entry: BlameEntry,
5910    style: &EditorStyle,
5911    cx: &mut App,
5912) -> AnyElement {
5913    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5914
5915    let author = blame_entry.author.as_deref().unwrap_or_default();
5916    let summary_enabled = ProjectSettings::get_global(cx)
5917        .git
5918        .show_inline_commit_summary();
5919
5920    let text = match blame_entry.summary.as_ref() {
5921        Some(summary) if summary_enabled => {
5922            format!("{}, {} - {}", author, relative_timestamp, summary)
5923        }
5924        _ => format!("{}, {}", author, relative_timestamp),
5925    };
5926    let blame = blame.clone();
5927    let blame_entry = blame_entry.clone();
5928
5929    h_flex()
5930        .id("inline-blame")
5931        .w_full()
5932        .font_family(style.text.font().family)
5933        .text_color(cx.theme().status().hint)
5934        .line_height(style.text.line_height)
5935        .child(Icon::new(IconName::FileGit).color(Color::Hint))
5936        .child(text)
5937        .gap_2()
5938        .hoverable_tooltip(move |window, cx| {
5939            let details = blame.read(cx).details_for_entry(&blame_entry);
5940            let tooltip =
5941                cx.new(|cx| CommitTooltip::blame_entry(&blame_entry, details, window, cx));
5942            editor.update(cx, |editor, _| {
5943                editor.git_blame_inline_tooltip = Some(tooltip.downgrade())
5944            });
5945            tooltip.into()
5946        })
5947        .into_any()
5948}
5949
5950fn render_blame_entry(
5951    ix: usize,
5952    blame: &gpui::Entity<GitBlame>,
5953    blame_entry: BlameEntry,
5954    style: &EditorStyle,
5955    last_used_color: &mut Option<(PlayerColor, Oid)>,
5956    editor: Entity<Editor>,
5957    cx: &mut App,
5958) -> AnyElement {
5959    let mut sha_color = cx
5960        .theme()
5961        .players()
5962        .color_for_participant(blame_entry.sha.into());
5963    // If the last color we used is the same as the one we get for this line, but
5964    // the commit SHAs are different, then we try again to get a different color.
5965    match *last_used_color {
5966        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
5967            let index: u32 = blame_entry.sha.into();
5968            sha_color = cx.theme().players().color_for_participant(index + 1);
5969        }
5970        _ => {}
5971    };
5972    last_used_color.replace((sha_color, blame_entry.sha));
5973
5974    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5975
5976    let short_commit_id = blame_entry.sha.display_short();
5977
5978    let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
5979    let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
5980    let details = blame.read(cx).details_for_entry(&blame_entry);
5981
5982    h_flex()
5983        .w_full()
5984        .justify_between()
5985        .font_family(style.text.font().family)
5986        .line_height(style.text.line_height)
5987        .id(("blame", ix))
5988        .text_color(cx.theme().status().hint)
5989        .pr_2()
5990        .gap_2()
5991        .child(
5992            h_flex()
5993                .items_center()
5994                .gap_2()
5995                .child(div().text_color(sha_color.cursor).child(short_commit_id))
5996                .child(name),
5997        )
5998        .child(relative_timestamp)
5999        .on_mouse_down(MouseButton::Right, {
6000            let blame_entry = blame_entry.clone();
6001            let details = details.clone();
6002            move |event, window, cx| {
6003                deploy_blame_entry_context_menu(
6004                    &blame_entry,
6005                    details.as_ref(),
6006                    editor.clone(),
6007                    event.position,
6008                    window,
6009                    cx,
6010                );
6011            }
6012        })
6013        .hover(|style| style.bg(cx.theme().colors().element_hover))
6014        .when_some(
6015            details
6016                .as_ref()
6017                .and_then(|details| details.permalink.clone()),
6018            |this, url| {
6019                this.cursor_pointer().on_click(move |_, _, cx| {
6020                    cx.stop_propagation();
6021                    cx.open_url(url.as_str())
6022                })
6023            },
6024        )
6025        .hoverable_tooltip(move |window, cx| {
6026            cx.new(|cx| CommitTooltip::blame_entry(&blame_entry, details.clone(), window, cx))
6027                .into()
6028        })
6029        .into_any()
6030}
6031
6032fn deploy_blame_entry_context_menu(
6033    blame_entry: &BlameEntry,
6034    details: Option<&ParsedCommitMessage>,
6035    editor: Entity<Editor>,
6036    position: gpui::Point<Pixels>,
6037    window: &mut Window,
6038    cx: &mut App,
6039) {
6040    let context_menu = ContextMenu::build(window, cx, move |menu, _, _| {
6041        let sha = format!("{}", blame_entry.sha);
6042        menu.on_blur_subscription(Subscription::new(|| {}))
6043            .entry("Copy commit SHA", None, move |_, cx| {
6044                cx.write_to_clipboard(ClipboardItem::new_string(sha.clone()));
6045            })
6046            .when_some(
6047                details.and_then(|details| details.permalink.clone()),
6048                |this, url| {
6049                    this.entry("Open permalink", None, move |_, cx| {
6050                        cx.open_url(url.as_str())
6051                    })
6052                },
6053            )
6054    });
6055
6056    editor.update(cx, move |editor, cx| {
6057        editor.mouse_context_menu = Some(MouseContextMenu::new(
6058            MenuPosition::PinnedToScreen(position),
6059            context_menu,
6060            window,
6061            cx,
6062        ));
6063        cx.notify();
6064    });
6065}
6066
6067#[derive(Debug)]
6068pub(crate) struct LineWithInvisibles {
6069    fragments: SmallVec<[LineFragment; 1]>,
6070    invisibles: Vec<Invisible>,
6071    len: usize,
6072    width: Pixels,
6073    font_size: Pixels,
6074}
6075
6076#[allow(clippy::large_enum_variant)]
6077enum LineFragment {
6078    Text(ShapedLine),
6079    Element {
6080        element: Option<AnyElement>,
6081        size: Size<Pixels>,
6082        len: usize,
6083    },
6084}
6085
6086impl fmt::Debug for LineFragment {
6087    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6088        match self {
6089            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
6090            LineFragment::Element { size, len, .. } => f
6091                .debug_struct("Element")
6092                .field("size", size)
6093                .field("len", len)
6094                .finish(),
6095        }
6096    }
6097}
6098
6099impl LineWithInvisibles {
6100    #[allow(clippy::too_many_arguments)]
6101    fn from_chunks<'a>(
6102        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
6103        editor_style: &EditorStyle,
6104        max_line_len: usize,
6105        max_line_count: usize,
6106        editor_mode: EditorMode,
6107        text_width: Pixels,
6108        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6109        window: &mut Window,
6110        cx: &mut App,
6111    ) -> Vec<Self> {
6112        let text_style = &editor_style.text;
6113        let mut layouts = Vec::with_capacity(max_line_count);
6114        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
6115        let mut line = String::new();
6116        let mut invisibles = Vec::new();
6117        let mut width = Pixels::ZERO;
6118        let mut len = 0;
6119        let mut styles = Vec::new();
6120        let mut non_whitespace_added = false;
6121        let mut row = 0;
6122        let mut line_exceeded_max_len = false;
6123        let font_size = text_style.font_size.to_pixels(window.rem_size());
6124
6125        let ellipsis = SharedString::from("");
6126
6127        for highlighted_chunk in chunks.chain([HighlightedChunk {
6128            text: "\n",
6129            style: None,
6130            is_tab: false,
6131            replacement: None,
6132        }]) {
6133            if let Some(replacement) = highlighted_chunk.replacement {
6134                if !line.is_empty() {
6135                    let shaped_line = window
6136                        .text_system()
6137                        .shape_line(line.clone().into(), font_size, &styles)
6138                        .unwrap();
6139                    width += shaped_line.width;
6140                    len += shaped_line.len;
6141                    fragments.push(LineFragment::Text(shaped_line));
6142                    line.clear();
6143                    styles.clear();
6144                }
6145
6146                match replacement {
6147                    ChunkReplacement::Renderer(renderer) => {
6148                        let available_width = if renderer.constrain_width {
6149                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
6150                                ellipsis.clone()
6151                            } else {
6152                                SharedString::from(Arc::from(highlighted_chunk.text))
6153                            };
6154                            let shaped_line = window
6155                                .text_system()
6156                                .shape_line(
6157                                    chunk,
6158                                    font_size,
6159                                    &[text_style.to_run(highlighted_chunk.text.len())],
6160                                )
6161                                .unwrap();
6162                            AvailableSpace::Definite(shaped_line.width)
6163                        } else {
6164                            AvailableSpace::MinContent
6165                        };
6166
6167                        let mut element = (renderer.render)(&mut ChunkRendererContext {
6168                            context: cx,
6169                            window,
6170                            max_width: text_width,
6171                        });
6172                        let line_height = text_style.line_height_in_pixels(window.rem_size());
6173                        let size = element.layout_as_root(
6174                            size(available_width, AvailableSpace::Definite(line_height)),
6175                            window,
6176                            cx,
6177                        );
6178
6179                        width += size.width;
6180                        len += highlighted_chunk.text.len();
6181                        fragments.push(LineFragment::Element {
6182                            element: Some(element),
6183                            size,
6184                            len: highlighted_chunk.text.len(),
6185                        });
6186                    }
6187                    ChunkReplacement::Str(x) => {
6188                        let text_style = if let Some(style) = highlighted_chunk.style {
6189                            Cow::Owned(text_style.clone().highlight(style))
6190                        } else {
6191                            Cow::Borrowed(text_style)
6192                        };
6193
6194                        let run = TextRun {
6195                            len: x.len(),
6196                            font: text_style.font(),
6197                            color: text_style.color,
6198                            background_color: text_style.background_color,
6199                            underline: text_style.underline,
6200                            strikethrough: text_style.strikethrough,
6201                        };
6202                        let line_layout = window
6203                            .text_system()
6204                            .shape_line(x, font_size, &[run])
6205                            .unwrap()
6206                            .with_len(highlighted_chunk.text.len());
6207
6208                        width += line_layout.width;
6209                        len += highlighted_chunk.text.len();
6210                        fragments.push(LineFragment::Text(line_layout))
6211                    }
6212                }
6213            } else {
6214                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
6215                    if ix > 0 {
6216                        let shaped_line = window
6217                            .text_system()
6218                            .shape_line(line.clone().into(), font_size, &styles)
6219                            .unwrap();
6220                        width += shaped_line.width;
6221                        len += shaped_line.len;
6222                        fragments.push(LineFragment::Text(shaped_line));
6223                        layouts.push(Self {
6224                            width: mem::take(&mut width),
6225                            len: mem::take(&mut len),
6226                            fragments: mem::take(&mut fragments),
6227                            invisibles: std::mem::take(&mut invisibles),
6228                            font_size,
6229                        });
6230
6231                        line.clear();
6232                        styles.clear();
6233                        row += 1;
6234                        line_exceeded_max_len = false;
6235                        non_whitespace_added = false;
6236                        if row == max_line_count {
6237                            return layouts;
6238                        }
6239                    }
6240
6241                    if !line_chunk.is_empty() && !line_exceeded_max_len {
6242                        let text_style = if let Some(style) = highlighted_chunk.style {
6243                            Cow::Owned(text_style.clone().highlight(style))
6244                        } else {
6245                            Cow::Borrowed(text_style)
6246                        };
6247
6248                        if line.len() + line_chunk.len() > max_line_len {
6249                            let mut chunk_len = max_line_len - line.len();
6250                            while !line_chunk.is_char_boundary(chunk_len) {
6251                                chunk_len -= 1;
6252                            }
6253                            line_chunk = &line_chunk[..chunk_len];
6254                            line_exceeded_max_len = true;
6255                        }
6256
6257                        styles.push(TextRun {
6258                            len: line_chunk.len(),
6259                            font: text_style.font(),
6260                            color: text_style.color,
6261                            background_color: text_style.background_color,
6262                            underline: text_style.underline,
6263                            strikethrough: text_style.strikethrough,
6264                        });
6265
6266                        if editor_mode == EditorMode::Full {
6267                            // Line wrap pads its contents with fake whitespaces,
6268                            // avoid printing them
6269                            let is_soft_wrapped = is_row_soft_wrapped(row);
6270                            if highlighted_chunk.is_tab {
6271                                if non_whitespace_added || !is_soft_wrapped {
6272                                    invisibles.push(Invisible::Tab {
6273                                        line_start_offset: line.len(),
6274                                        line_end_offset: line.len() + line_chunk.len(),
6275                                    });
6276                                }
6277                            } else {
6278                                invisibles.extend(line_chunk.char_indices().filter_map(
6279                                    |(index, c)| {
6280                                        let is_whitespace = c.is_whitespace();
6281                                        non_whitespace_added |= !is_whitespace;
6282                                        if is_whitespace
6283                                            && (non_whitespace_added || !is_soft_wrapped)
6284                                        {
6285                                            Some(Invisible::Whitespace {
6286                                                line_offset: line.len() + index,
6287                                            })
6288                                        } else {
6289                                            None
6290                                        }
6291                                    },
6292                                ))
6293                            }
6294                        }
6295
6296                        line.push_str(line_chunk);
6297                    }
6298                }
6299            }
6300        }
6301
6302        layouts
6303    }
6304
6305    #[allow(clippy::too_many_arguments)]
6306    fn prepaint(
6307        &mut self,
6308        line_height: Pixels,
6309        scroll_pixel_position: gpui::Point<Pixels>,
6310        row: DisplayRow,
6311        content_origin: gpui::Point<Pixels>,
6312        line_elements: &mut SmallVec<[AnyElement; 1]>,
6313        window: &mut Window,
6314        cx: &mut App,
6315    ) {
6316        let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
6317        let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
6318        for fragment in &mut self.fragments {
6319            match fragment {
6320                LineFragment::Text(line) => {
6321                    fragment_origin.x += line.width;
6322                }
6323                LineFragment::Element { element, size, .. } => {
6324                    let mut element = element
6325                        .take()
6326                        .expect("you can't prepaint LineWithInvisibles twice");
6327
6328                    // Center the element vertically within the line.
6329                    let mut element_origin = fragment_origin;
6330                    element_origin.y += (line_height - size.height) / 2.;
6331                    element.prepaint_at(element_origin, window, cx);
6332                    line_elements.push(element);
6333
6334                    fragment_origin.x += size.width;
6335                }
6336            }
6337        }
6338    }
6339
6340    #[allow(clippy::too_many_arguments)]
6341    fn draw(
6342        &self,
6343        layout: &EditorLayout,
6344        row: DisplayRow,
6345        content_origin: gpui::Point<Pixels>,
6346        whitespace_setting: ShowWhitespaceSetting,
6347        selection_ranges: &[Range<DisplayPoint>],
6348        window: &mut Window,
6349        cx: &mut App,
6350    ) {
6351        let line_height = layout.position_map.line_height;
6352        let line_y = line_height
6353            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6354
6355        let mut fragment_origin =
6356            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6357
6358        for fragment in &self.fragments {
6359            match fragment {
6360                LineFragment::Text(line) => {
6361                    line.paint(fragment_origin, line_height, window, cx)
6362                        .log_err();
6363                    fragment_origin.x += line.width;
6364                }
6365                LineFragment::Element { size, .. } => {
6366                    fragment_origin.x += size.width;
6367                }
6368            }
6369        }
6370
6371        self.draw_invisibles(
6372            selection_ranges,
6373            layout,
6374            content_origin,
6375            line_y,
6376            row,
6377            line_height,
6378            whitespace_setting,
6379            window,
6380            cx,
6381        );
6382    }
6383
6384    #[allow(clippy::too_many_arguments)]
6385    fn draw_invisibles(
6386        &self,
6387        selection_ranges: &[Range<DisplayPoint>],
6388        layout: &EditorLayout,
6389        content_origin: gpui::Point<Pixels>,
6390        line_y: Pixels,
6391        row: DisplayRow,
6392        line_height: Pixels,
6393        whitespace_setting: ShowWhitespaceSetting,
6394        window: &mut Window,
6395        cx: &mut App,
6396    ) {
6397        let extract_whitespace_info = |invisible: &Invisible| {
6398            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
6399                Invisible::Tab {
6400                    line_start_offset,
6401                    line_end_offset,
6402                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
6403                Invisible::Whitespace { line_offset } => {
6404                    (*line_offset, line_offset + 1, &layout.space_invisible)
6405                }
6406            };
6407
6408            let x_offset = self.x_for_index(token_offset);
6409            let invisible_offset =
6410                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
6411            let origin = content_origin
6412                + gpui::point(
6413                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
6414                    line_y,
6415                );
6416
6417            (
6418                [token_offset, token_end_offset],
6419                Box::new(move |window: &mut Window, cx: &mut App| {
6420                    invisible_symbol
6421                        .paint(origin, line_height, window, cx)
6422                        .log_err();
6423                }),
6424            )
6425        };
6426
6427        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
6428        match whitespace_setting {
6429            ShowWhitespaceSetting::None => (),
6430            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
6431            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
6432                let invisible_point = DisplayPoint::new(row, start as u32);
6433                if !selection_ranges
6434                    .iter()
6435                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
6436                {
6437                    return;
6438                }
6439
6440                paint(window, cx);
6441            }),
6442
6443            // For a whitespace to be on a boundary, any of the following conditions need to be met:
6444            // - It is a tab
6445            // - It is adjacent to an edge (start or end)
6446            // - It is adjacent to a whitespace (left or right)
6447            ShowWhitespaceSetting::Boundary => {
6448                // 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
6449                // the above cases.
6450                // Note: We zip in the original `invisibles` to check for tab equality
6451                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
6452                for (([start, end], paint), invisible) in
6453                    invisible_iter.zip_eq(self.invisibles.iter())
6454                {
6455                    let should_render = match (&last_seen, invisible) {
6456                        (_, Invisible::Tab { .. }) => true,
6457                        (Some((_, last_end, _)), _) => *last_end == start,
6458                        _ => false,
6459                    };
6460
6461                    if should_render || start == 0 || end == self.len {
6462                        paint(window, cx);
6463
6464                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
6465                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
6466                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
6467                            // Note that we need to make sure that the last one is actually adjacent
6468                            if !should_render_last && last_end == start {
6469                                paint_last(window, cx);
6470                            }
6471                        }
6472                    }
6473
6474                    // Manually render anything within a selection
6475                    let invisible_point = DisplayPoint::new(row, start as u32);
6476                    if selection_ranges.iter().any(|region| {
6477                        region.start <= invisible_point && invisible_point < region.end
6478                    }) {
6479                        paint(window, cx);
6480                    }
6481
6482                    last_seen = Some((should_render, end, paint));
6483                }
6484            }
6485        }
6486    }
6487
6488    pub fn x_for_index(&self, index: usize) -> Pixels {
6489        let mut fragment_start_x = Pixels::ZERO;
6490        let mut fragment_start_index = 0;
6491
6492        for fragment in &self.fragments {
6493            match fragment {
6494                LineFragment::Text(shaped_line) => {
6495                    let fragment_end_index = fragment_start_index + shaped_line.len;
6496                    if index < fragment_end_index {
6497                        return fragment_start_x
6498                            + shaped_line.x_for_index(index - fragment_start_index);
6499                    }
6500                    fragment_start_x += shaped_line.width;
6501                    fragment_start_index = fragment_end_index;
6502                }
6503                LineFragment::Element { len, size, .. } => {
6504                    let fragment_end_index = fragment_start_index + len;
6505                    if index < fragment_end_index {
6506                        return fragment_start_x;
6507                    }
6508                    fragment_start_x += size.width;
6509                    fragment_start_index = fragment_end_index;
6510                }
6511            }
6512        }
6513
6514        fragment_start_x
6515    }
6516
6517    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
6518        let mut fragment_start_x = Pixels::ZERO;
6519        let mut fragment_start_index = 0;
6520
6521        for fragment in &self.fragments {
6522            match fragment {
6523                LineFragment::Text(shaped_line) => {
6524                    let fragment_end_x = fragment_start_x + shaped_line.width;
6525                    if x < fragment_end_x {
6526                        return Some(
6527                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
6528                        );
6529                    }
6530                    fragment_start_x = fragment_end_x;
6531                    fragment_start_index += shaped_line.len;
6532                }
6533                LineFragment::Element { len, size, .. } => {
6534                    let fragment_end_x = fragment_start_x + size.width;
6535                    if x < fragment_end_x {
6536                        return Some(fragment_start_index);
6537                    }
6538                    fragment_start_index += len;
6539                    fragment_start_x = fragment_end_x;
6540                }
6541            }
6542        }
6543
6544        None
6545    }
6546
6547    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
6548        let mut fragment_start_index = 0;
6549
6550        for fragment in &self.fragments {
6551            match fragment {
6552                LineFragment::Text(shaped_line) => {
6553                    let fragment_end_index = fragment_start_index + shaped_line.len;
6554                    if index < fragment_end_index {
6555                        return shaped_line.font_id_for_index(index - fragment_start_index);
6556                    }
6557                    fragment_start_index = fragment_end_index;
6558                }
6559                LineFragment::Element { len, .. } => {
6560                    let fragment_end_index = fragment_start_index + len;
6561                    if index < fragment_end_index {
6562                        return None;
6563                    }
6564                    fragment_start_index = fragment_end_index;
6565                }
6566            }
6567        }
6568
6569        None
6570    }
6571}
6572
6573#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6574enum Invisible {
6575    /// A tab character
6576    ///
6577    /// A tab character is internally represented by spaces (configured by the user's tab width)
6578    /// aligned to the nearest column, so it's necessary to store the start and end offset for
6579    /// adjacency checks.
6580    Tab {
6581        line_start_offset: usize,
6582        line_end_offset: usize,
6583    },
6584    Whitespace {
6585        line_offset: usize,
6586    },
6587}
6588
6589impl EditorElement {
6590    /// Returns the rem size to use when rendering the [`EditorElement`].
6591    ///
6592    /// This allows UI elements to scale based on the `buffer_font_size`.
6593    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
6594        match self.editor.read(cx).mode {
6595            EditorMode::Full => {
6596                let buffer_font_size = self.style.text.font_size;
6597                match buffer_font_size {
6598                    AbsoluteLength::Pixels(pixels) => {
6599                        let rem_size_scale = {
6600                            // Our default UI font size is 14px on a 16px base scale.
6601                            // This means the default UI font size is 0.875rems.
6602                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
6603
6604                            // We then determine the delta between a single rem and the default font
6605                            // size scale.
6606                            let default_font_size_delta = 1. - default_font_size_scale;
6607
6608                            // Finally, we add this delta to 1rem to get the scale factor that
6609                            // should be used to scale up the UI.
6610                            1. + default_font_size_delta
6611                        };
6612
6613                        Some(pixels * rem_size_scale)
6614                    }
6615                    AbsoluteLength::Rems(rems) => {
6616                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
6617                    }
6618                }
6619            }
6620            // We currently use single-line and auto-height editors in UI contexts,
6621            // so we don't want to scale everything with the buffer font size, as it
6622            // ends up looking off.
6623            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
6624        }
6625    }
6626}
6627
6628impl Element for EditorElement {
6629    type RequestLayoutState = ();
6630    type PrepaintState = EditorLayout;
6631
6632    fn id(&self) -> Option<ElementId> {
6633        None
6634    }
6635
6636    fn request_layout(
6637        &mut self,
6638        _: Option<&GlobalElementId>,
6639        window: &mut Window,
6640        cx: &mut App,
6641    ) -> (gpui::LayoutId, ()) {
6642        let rem_size = self.rem_size(cx);
6643        window.with_rem_size(rem_size, |window| {
6644            self.editor.update(cx, |editor, cx| {
6645                editor.set_style(self.style.clone(), window, cx);
6646
6647                let layout_id = match editor.mode {
6648                    EditorMode::SingleLine { auto_width } => {
6649                        let rem_size = window.rem_size();
6650
6651                        let height = self.style.text.line_height_in_pixels(rem_size);
6652                        if auto_width {
6653                            let editor_handle = cx.entity().clone();
6654                            let style = self.style.clone();
6655                            window.request_measured_layout(
6656                                Style::default(),
6657                                move |_, _, window, cx| {
6658                                    let editor_snapshot = editor_handle
6659                                        .update(cx, |editor, cx| editor.snapshot(window, cx));
6660                                    let line = Self::layout_lines(
6661                                        DisplayRow(0)..DisplayRow(1),
6662                                        &editor_snapshot,
6663                                        &style,
6664                                        px(f32::MAX),
6665                                        |_| false, // Single lines never soft wrap
6666                                        window,
6667                                        cx,
6668                                    )
6669                                    .pop()
6670                                    .unwrap();
6671
6672                                    let font_id =
6673                                        window.text_system().resolve_font(&style.text.font());
6674                                    let font_size =
6675                                        style.text.font_size.to_pixels(window.rem_size());
6676                                    let em_width =
6677                                        window.text_system().em_width(font_id, font_size).unwrap();
6678
6679                                    size(line.width + em_width, height)
6680                                },
6681                            )
6682                        } else {
6683                            let mut style = Style::default();
6684                            style.size.height = height.into();
6685                            style.size.width = relative(1.).into();
6686                            window.request_layout(style, None, cx)
6687                        }
6688                    }
6689                    EditorMode::AutoHeight { max_lines } => {
6690                        let editor_handle = cx.entity().clone();
6691                        let max_line_number_width =
6692                            self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
6693                        window.request_measured_layout(
6694                            Style::default(),
6695                            move |known_dimensions, available_space, window, cx| {
6696                                editor_handle
6697                                    .update(cx, |editor, cx| {
6698                                        compute_auto_height_layout(
6699                                            editor,
6700                                            max_lines,
6701                                            max_line_number_width,
6702                                            known_dimensions,
6703                                            available_space.width,
6704                                            window,
6705                                            cx,
6706                                        )
6707                                    })
6708                                    .unwrap_or_default()
6709                            },
6710                        )
6711                    }
6712                    EditorMode::Full => {
6713                        let mut style = Style::default();
6714                        style.size.width = relative(1.).into();
6715                        style.size.height = relative(1.).into();
6716                        window.request_layout(style, None, cx)
6717                    }
6718                };
6719
6720                (layout_id, ())
6721            })
6722        })
6723    }
6724
6725    fn prepaint(
6726        &mut self,
6727        _: Option<&GlobalElementId>,
6728        bounds: Bounds<Pixels>,
6729        _: &mut Self::RequestLayoutState,
6730        window: &mut Window,
6731        cx: &mut App,
6732    ) -> Self::PrepaintState {
6733        let text_style = TextStyleRefinement {
6734            font_size: Some(self.style.text.font_size),
6735            line_height: Some(self.style.text.line_height),
6736            ..Default::default()
6737        };
6738        let focus_handle = self.editor.focus_handle(cx);
6739        window.set_view_id(self.editor.entity_id());
6740        window.set_focus_handle(&focus_handle, cx);
6741
6742        let rem_size = self.rem_size(cx);
6743        window.with_rem_size(rem_size, |window| {
6744            window.with_text_style(Some(text_style), |window| {
6745                window.with_content_mask(Some(ContentMask { bounds }), |window| {
6746                    let mut snapshot = self
6747                        .editor
6748                        .update(cx, |editor, cx| editor.snapshot(window, cx));
6749                    let style = self.style.clone();
6750
6751                    let font_id = window.text_system().resolve_font(&style.text.font());
6752                    let font_size = style.text.font_size.to_pixels(window.rem_size());
6753                    let line_height = style.text.line_height_in_pixels(window.rem_size());
6754                    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
6755                    let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
6756
6757                    let letter_size = size(em_width, line_height);
6758
6759                    let gutter_dimensions = snapshot
6760                        .gutter_dimensions(
6761                            font_id,
6762                            font_size,
6763                            self.max_line_number_width(&snapshot, window, cx),
6764                            cx,
6765                        )
6766                        .unwrap_or_default();
6767                    let text_width = bounds.size.width - gutter_dimensions.width;
6768
6769                    let editor_width =
6770                        text_width - gutter_dimensions.margin - em_width - style.scrollbar_width;
6771
6772                    snapshot = self.editor.update(cx, |editor, cx| {
6773                        editor.last_bounds = Some(bounds);
6774                        editor.gutter_dimensions = gutter_dimensions;
6775                        editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
6776
6777                        if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
6778                            snapshot
6779                        } else {
6780                            let wrap_width = match editor.soft_wrap_mode(cx) {
6781                                SoftWrap::GitDiff => None,
6782                                SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
6783                                SoftWrap::EditorWidth => Some(editor_width),
6784                                SoftWrap::Column(column) => Some(column as f32 * em_advance),
6785                                SoftWrap::Bounded(column) => {
6786                                    Some(editor_width.min(column as f32 * em_advance))
6787                                }
6788                            };
6789
6790                            if editor.set_wrap_width(wrap_width, cx) {
6791                                editor.snapshot(window, cx)
6792                            } else {
6793                                snapshot
6794                            }
6795                        }
6796                    });
6797
6798                    let wrap_guides = self
6799                        .editor
6800                        .read(cx)
6801                        .wrap_guides(cx)
6802                        .iter()
6803                        .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
6804                        .collect::<SmallVec<[_; 2]>>();
6805
6806                    let hitbox = window.insert_hitbox(bounds, false);
6807                    let gutter_hitbox =
6808                        window.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
6809                    let text_hitbox = window.insert_hitbox(
6810                        Bounds {
6811                            origin: gutter_hitbox.top_right(),
6812                            size: size(text_width, bounds.size.height),
6813                        },
6814                        false,
6815                    );
6816                    // Offset the content_bounds from the text_bounds by the gutter margin (which
6817                    // is roughly half a character wide) to make hit testing work more like how we want.
6818                    let content_origin =
6819                        text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
6820
6821                    let scrollbar_bounds =
6822                        Bounds::from_corners(content_origin, bounds.bottom_right());
6823
6824                    let height_in_lines = scrollbar_bounds.size.height / line_height;
6825
6826                    // NOTE: The max row number in the current file, minus one
6827                    let max_row = snapshot.max_point().row().as_f32();
6828
6829                    // NOTE: The max scroll position for the top of the window
6830                    let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
6831                        (max_row - height_in_lines + 1.).max(0.)
6832                    } else {
6833                        let settings = EditorSettings::get_global(cx);
6834                        match settings.scroll_beyond_last_line {
6835                            ScrollBeyondLastLine::OnePage => max_row,
6836                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
6837                            ScrollBeyondLastLine::VerticalScrollMargin => {
6838                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
6839                                    .max(0.)
6840                            }
6841                        }
6842                    };
6843
6844                    // TODO: Autoscrolling for both axes
6845                    let mut autoscroll_request = None;
6846                    let mut autoscroll_containing_element = false;
6847                    let mut autoscroll_horizontally = false;
6848                    self.editor.update(cx, |editor, cx| {
6849                        autoscroll_request = editor.autoscroll_request();
6850                        autoscroll_containing_element =
6851                            autoscroll_request.is_some() || editor.has_pending_selection();
6852                        // TODO: Is this horizontal or vertical?!
6853                        autoscroll_horizontally = editor.autoscroll_vertically(
6854                            bounds,
6855                            line_height,
6856                            max_scroll_top,
6857                            window,
6858                            cx,
6859                        );
6860                        snapshot = editor.snapshot(window, cx);
6861                    });
6862
6863                    let mut scroll_position = snapshot.scroll_position();
6864                    // The scroll position is a fractional point, the whole number of which represents
6865                    // the top of the window in terms of display rows.
6866                    let start_row = DisplayRow(scroll_position.y as u32);
6867                    let max_row = snapshot.max_point().row();
6868                    let end_row = cmp::min(
6869                        (scroll_position.y + height_in_lines).ceil() as u32,
6870                        max_row.next_row().0,
6871                    );
6872                    let end_row = DisplayRow(end_row);
6873
6874                    let row_infos = snapshot
6875                        .row_infos(start_row)
6876                        .take((start_row..end_row).len())
6877                        .collect::<Vec<RowInfo>>();
6878                    let is_row_soft_wrapped = |row: usize| {
6879                        row_infos
6880                            .get(row)
6881                            .map_or(true, |info| info.buffer_row.is_none())
6882                    };
6883
6884                    let start_anchor = if start_row == Default::default() {
6885                        Anchor::min()
6886                    } else {
6887                        snapshot.buffer_snapshot.anchor_before(
6888                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
6889                        )
6890                    };
6891                    let end_anchor = if end_row > max_row {
6892                        Anchor::max()
6893                    } else {
6894                        snapshot.buffer_snapshot.anchor_before(
6895                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
6896                        )
6897                    };
6898
6899                    let (mut highlighted_rows, distinguish_unstaged_hunks) =
6900                        self.editor.update(cx, |editor, cx| {
6901                            (
6902                                editor.highlighted_display_rows(window, cx),
6903                                editor.distinguish_unstaged_diff_hunks,
6904                            )
6905                        });
6906
6907                    for (ix, row_info) in row_infos.iter().enumerate() {
6908                        let background = match row_info.diff_status {
6909                            Some(DiffHunkStatus::Added(secondary_status)) => {
6910                                let color = style.status.created_background;
6911                                match secondary_status {
6912                                    DiffHunkSecondaryStatus::HasSecondaryHunk
6913                                    | DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk
6914                                        if distinguish_unstaged_hunks =>
6915                                    {
6916                                        pattern_slash(color, line_height.0 / 4.0)
6917                                    }
6918                                    _ => color.into(),
6919                                }
6920                            }
6921                            Some(DiffHunkStatus::Removed(secondary_status)) => {
6922                                let color = style.status.deleted_background;
6923                                match secondary_status {
6924                                    DiffHunkSecondaryStatus::HasSecondaryHunk
6925                                    | DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk
6926                                        if distinguish_unstaged_hunks =>
6927                                    {
6928                                        pattern_slash(color, line_height.0 / 4.0)
6929                                    }
6930                                    _ => color.into(),
6931                                }
6932                            }
6933                            _ => continue,
6934                        };
6935
6936                        highlighted_rows
6937                            .entry(start_row + DisplayRow(ix as u32))
6938                            .or_insert(background);
6939                    }
6940
6941                    let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
6942                        start_anchor..end_anchor,
6943                        &snapshot.display_snapshot,
6944                        cx.theme().colors(),
6945                    );
6946                    let highlighted_gutter_ranges =
6947                        self.editor.read(cx).gutter_highlights_in_range(
6948                            start_anchor..end_anchor,
6949                            &snapshot.display_snapshot,
6950                            cx,
6951                        );
6952
6953                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
6954                        start_anchor..end_anchor,
6955                        &snapshot.display_snapshot,
6956                        cx,
6957                    );
6958
6959                    let (local_selections, selected_buffer_ids): (
6960                        Vec<Selection<Point>>,
6961                        Vec<BufferId>,
6962                    ) = self.editor.update(cx, |editor, cx| {
6963                        let all_selections = editor.selections.all::<Point>(cx);
6964                        let selected_buffer_ids = if editor.is_singleton(cx) {
6965                            Vec::new()
6966                        } else {
6967                            let mut selected_buffer_ids = Vec::with_capacity(all_selections.len());
6968
6969                            for selection in all_selections {
6970                                for buffer_id in snapshot
6971                                    .buffer_snapshot
6972                                    .buffer_ids_for_range(selection.range())
6973                                {
6974                                    if selected_buffer_ids.last() != Some(&buffer_id) {
6975                                        selected_buffer_ids.push(buffer_id);
6976                                    }
6977                                }
6978                            }
6979
6980                            selected_buffer_ids
6981                        };
6982
6983                        let mut selections = editor
6984                            .selections
6985                            .disjoint_in_range(start_anchor..end_anchor, cx);
6986                        selections.extend(editor.selections.pending(cx));
6987
6988                        (selections, selected_buffer_ids)
6989                    });
6990
6991                    let (selections, active_rows, newest_selection_head) = self.layout_selections(
6992                        start_anchor,
6993                        end_anchor,
6994                        &local_selections,
6995                        &snapshot,
6996                        start_row,
6997                        end_row,
6998                        window,
6999                        cx,
7000                    );
7001
7002                    let line_numbers = self.layout_line_numbers(
7003                        Some(&gutter_hitbox),
7004                        gutter_dimensions,
7005                        line_height,
7006                        scroll_position,
7007                        start_row..end_row,
7008                        &row_infos,
7009                        newest_selection_head,
7010                        &snapshot,
7011                        window,
7012                        cx,
7013                    );
7014
7015                    let mut crease_toggles =
7016                        window.with_element_namespace("crease_toggles", |window| {
7017                            self.layout_crease_toggles(
7018                                start_row..end_row,
7019                                &row_infos,
7020                                &active_rows,
7021                                &snapshot,
7022                                window,
7023                                cx,
7024                            )
7025                        });
7026                    let crease_trailers =
7027                        window.with_element_namespace("crease_trailers", |window| {
7028                            self.layout_crease_trailers(
7029                                row_infos.iter().copied(),
7030                                &snapshot,
7031                                window,
7032                                cx,
7033                            )
7034                        });
7035
7036                    let display_hunks = self.layout_gutter_diff_hunks(
7037                        line_height,
7038                        &gutter_hitbox,
7039                        start_row..end_row,
7040                        &snapshot,
7041                        window,
7042                        cx,
7043                    );
7044
7045                    let mut line_layouts = Self::layout_lines(
7046                        start_row..end_row,
7047                        &snapshot,
7048                        &self.style,
7049                        editor_width,
7050                        is_row_soft_wrapped,
7051                        window,
7052                        cx,
7053                    );
7054
7055                    let longest_line_blame_width = self
7056                        .editor
7057                        .update(cx, |editor, cx| {
7058                            if !editor.show_git_blame_inline {
7059                                return None;
7060                            }
7061                            let blame = editor.blame.as_ref()?;
7062                            let blame_entry = blame
7063                                .update(cx, |blame, cx| {
7064                                    let row_infos =
7065                                        snapshot.row_infos(snapshot.longest_row()).next()?;
7066                                    blame.blame_for_rows(&[row_infos], cx).next()
7067                                })
7068                                .flatten()?;
7069                            let mut element = render_inline_blame_entry(
7070                                self.editor.clone(),
7071                                blame,
7072                                blame_entry,
7073                                &style,
7074                                cx,
7075                            );
7076                            let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
7077                            Some(
7078                                element
7079                                    .layout_as_root(AvailableSpace::min_size(), window, cx)
7080                                    .width
7081                                    + inline_blame_padding,
7082                            )
7083                        })
7084                        .unwrap_or(Pixels::ZERO);
7085
7086                    let longest_line_width = layout_line(
7087                        snapshot.longest_row(),
7088                        &snapshot,
7089                        &style,
7090                        editor_width,
7091                        is_row_soft_wrapped,
7092                        window,
7093                        cx,
7094                    )
7095                    .width;
7096
7097                    let scrollbar_range_data = ScrollbarRangeData::new(
7098                        scrollbar_bounds,
7099                        letter_size,
7100                        &snapshot,
7101                        longest_line_width,
7102                        longest_line_blame_width,
7103                        &style,
7104                        editor_width,
7105                        cx,
7106                    );
7107
7108                    let scroll_range_bounds = scrollbar_range_data.scroll_range;
7109                    let mut scroll_width = scroll_range_bounds.size.width;
7110
7111                    let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
7112                        snapshot.sticky_header_excerpt(start_row)
7113                    } else {
7114                        None
7115                    };
7116                    let sticky_header_excerpt_id =
7117                        sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
7118
7119                    let blocks = window.with_element_namespace("blocks", |window| {
7120                        self.render_blocks(
7121                            start_row..end_row,
7122                            &snapshot,
7123                            &hitbox,
7124                            &text_hitbox,
7125                            editor_width,
7126                            &mut scroll_width,
7127                            &gutter_dimensions,
7128                            em_width,
7129                            gutter_dimensions.full_width(),
7130                            line_height,
7131                            &line_layouts,
7132                            &local_selections,
7133                            &selected_buffer_ids,
7134                            is_row_soft_wrapped,
7135                            sticky_header_excerpt_id,
7136                            window,
7137                            cx,
7138                        )
7139                    });
7140                    let mut blocks = match blocks {
7141                        Ok(blocks) => blocks,
7142                        Err(resized_blocks) => {
7143                            self.editor.update(cx, |editor, cx| {
7144                                editor.resize_blocks(resized_blocks, autoscroll_request, cx)
7145                            });
7146                            return self.prepaint(None, bounds, &mut (), window, cx);
7147                        }
7148                    };
7149
7150                    let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
7151                        window.with_element_namespace("blocks", |window| {
7152                            self.layout_sticky_buffer_header(
7153                                sticky_header_excerpt,
7154                                scroll_position.y,
7155                                line_height,
7156                                &snapshot,
7157                                &hitbox,
7158                                &selected_buffer_ids,
7159                                window,
7160                                cx,
7161                            )
7162                        })
7163                    });
7164
7165                    let start_buffer_row =
7166                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
7167                    let end_buffer_row =
7168                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
7169
7170                    let scroll_max = point(
7171                        ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7172                        max_row.as_f32(),
7173                    );
7174
7175                    self.editor.update(cx, |editor, cx| {
7176                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7177
7178                        let autoscrolled = if autoscroll_horizontally {
7179                            editor.autoscroll_horizontally(
7180                                start_row,
7181                                editor_width - (letter_size.width / 2.0) + style.scrollbar_width,
7182                                scroll_width,
7183                                em_width,
7184                                &line_layouts,
7185                                cx,
7186                            )
7187                        } else {
7188                            false
7189                        };
7190
7191                        if clamped || autoscrolled {
7192                            snapshot = editor.snapshot(window, cx);
7193                            scroll_position = snapshot.scroll_position();
7194                        }
7195                    });
7196
7197                    let scroll_pixel_position = point(
7198                        scroll_position.x * em_width,
7199                        scroll_position.y * line_height,
7200                    );
7201
7202                    let indent_guides = self.layout_indent_guides(
7203                        content_origin,
7204                        text_hitbox.origin,
7205                        start_buffer_row..end_buffer_row,
7206                        scroll_pixel_position,
7207                        line_height,
7208                        &snapshot,
7209                        window,
7210                        cx,
7211                    );
7212
7213                    let crease_trailers =
7214                        window.with_element_namespace("crease_trailers", |window| {
7215                            self.prepaint_crease_trailers(
7216                                crease_trailers,
7217                                &line_layouts,
7218                                line_height,
7219                                content_origin,
7220                                scroll_pixel_position,
7221                                em_width,
7222                                window,
7223                                cx,
7224                            )
7225                        });
7226
7227                    let mut inline_blame = None;
7228                    if let Some(newest_selection_head) = newest_selection_head {
7229                        let display_row = newest_selection_head.row();
7230                        if (start_row..end_row).contains(&display_row) {
7231                            let line_ix = display_row.minus(start_row) as usize;
7232                            let row_info = &row_infos[line_ix];
7233                            let line_layout = &line_layouts[line_ix];
7234                            let crease_trailer_layout = crease_trailers[line_ix].as_ref();
7235                            inline_blame = self.layout_inline_blame(
7236                                display_row,
7237                                row_info,
7238                                line_layout,
7239                                crease_trailer_layout,
7240                                em_width,
7241                                content_origin,
7242                                scroll_pixel_position,
7243                                line_height,
7244                                window,
7245                                cx,
7246                            );
7247                        }
7248                    }
7249
7250                    let blamed_display_rows = self.layout_blame_entries(
7251                        &row_infos,
7252                        em_width,
7253                        scroll_position,
7254                        line_height,
7255                        &gutter_hitbox,
7256                        gutter_dimensions.git_blame_entries_width,
7257                        window,
7258                        cx,
7259                    );
7260
7261                    let scroll_max = point(
7262                        ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7263                        max_scroll_top,
7264                    );
7265
7266                    self.editor.update(cx, |editor, cx| {
7267                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7268
7269                        let autoscrolled = if autoscroll_horizontally {
7270                            editor.autoscroll_horizontally(
7271                                start_row,
7272                                editor_width - (letter_size.width / 2.0) + style.scrollbar_width,
7273                                scroll_width,
7274                                em_width,
7275                                &line_layouts,
7276                                cx,
7277                            )
7278                        } else {
7279                            false
7280                        };
7281
7282                        if clamped || autoscrolled {
7283                            snapshot = editor.snapshot(window, cx);
7284                            scroll_position = snapshot.scroll_position();
7285                        }
7286                    });
7287
7288                    let line_elements = self.prepaint_lines(
7289                        start_row,
7290                        &mut line_layouts,
7291                        line_height,
7292                        scroll_pixel_position,
7293                        content_origin,
7294                        window,
7295                        cx,
7296                    );
7297
7298                    let mut block_start_rows = HashSet::default();
7299
7300                    window.with_element_namespace("blocks", |window| {
7301                        self.layout_blocks(
7302                            &mut blocks,
7303                            &mut block_start_rows,
7304                            &hitbox,
7305                            line_height,
7306                            scroll_pixel_position,
7307                            window,
7308                            cx,
7309                        );
7310                    });
7311
7312                    let cursors = self.collect_cursors(&snapshot, cx);
7313                    let visible_row_range = start_row..end_row;
7314                    let non_visible_cursors = cursors
7315                        .iter()
7316                        .any(|c| !visible_row_range.contains(&c.0.row()));
7317
7318                    let visible_cursors = self.layout_visible_cursors(
7319                        &snapshot,
7320                        &selections,
7321                        &block_start_rows,
7322                        start_row..end_row,
7323                        &line_layouts,
7324                        &text_hitbox,
7325                        content_origin,
7326                        scroll_position,
7327                        scroll_pixel_position,
7328                        line_height,
7329                        em_width,
7330                        em_advance,
7331                        autoscroll_containing_element,
7332                        window,
7333                        cx,
7334                    );
7335
7336                    let scrollbars_layout = self.layout_scrollbars(
7337                        &snapshot,
7338                        scrollbar_range_data,
7339                        scroll_position,
7340                        non_visible_cursors,
7341                        window,
7342                        cx,
7343                    );
7344
7345                    let gutter_settings = EditorSettings::get_global(cx).gutter;
7346
7347                    let rows_with_hunk_bounds = display_hunks
7348                        .iter()
7349                        .filter_map(|(hunk, hitbox)| Some((hunk, hitbox.as_ref()?.bounds)))
7350                        .fold(
7351                            HashMap::default(),
7352                            |mut rows_with_hunk_bounds, (hunk, bounds)| {
7353                                match hunk {
7354                                    DisplayDiffHunk::Folded { display_row } => {
7355                                        rows_with_hunk_bounds.insert(*display_row, bounds);
7356                                    }
7357                                    DisplayDiffHunk::Unfolded {
7358                                        display_row_range, ..
7359                                    } => {
7360                                        for display_row in display_row_range.iter_rows() {
7361                                            rows_with_hunk_bounds.insert(display_row, bounds);
7362                                        }
7363                                    }
7364                                }
7365                                rows_with_hunk_bounds
7366                            },
7367                        );
7368                    let mut code_actions_indicator = None;
7369                    if let Some(newest_selection_head) = newest_selection_head {
7370                        let newest_selection_point =
7371                            newest_selection_head.to_point(&snapshot.display_snapshot);
7372
7373                        if (start_row..end_row).contains(&newest_selection_head.row()) {
7374                            self.layout_cursor_popovers(
7375                                line_height,
7376                                &text_hitbox,
7377                                content_origin,
7378                                start_row,
7379                                scroll_pixel_position,
7380                                &line_layouts,
7381                                newest_selection_head,
7382                                newest_selection_point,
7383                                &style,
7384                                window,
7385                                cx,
7386                            );
7387
7388                            let show_code_actions = snapshot
7389                                .show_code_actions
7390                                .unwrap_or(gutter_settings.code_actions);
7391                            if show_code_actions {
7392                                let newest_selection_point =
7393                                    newest_selection_head.to_point(&snapshot.display_snapshot);
7394                                if !snapshot
7395                                    .is_line_folded(MultiBufferRow(newest_selection_point.row))
7396                                {
7397                                    let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
7398                                        MultiBufferRow(newest_selection_point.row),
7399                                    );
7400                                    if let Some((buffer, range)) = buffer {
7401                                        let buffer_id = buffer.remote_id();
7402                                        let row = range.start.row;
7403                                        let has_test_indicator = self
7404                                            .editor
7405                                            .read(cx)
7406                                            .tasks
7407                                            .contains_key(&(buffer_id, row));
7408
7409                                        if !has_test_indicator {
7410                                            code_actions_indicator = self
7411                                                .layout_code_actions_indicator(
7412                                                    line_height,
7413                                                    newest_selection_head,
7414                                                    scroll_pixel_position,
7415                                                    &gutter_dimensions,
7416                                                    &gutter_hitbox,
7417                                                    &rows_with_hunk_bounds,
7418                                                    window,
7419                                                    cx,
7420                                                );
7421                                        }
7422                                    }
7423                                }
7424                            }
7425                        }
7426                    }
7427
7428                    self.layout_gutter_menu(
7429                        line_height,
7430                        &text_hitbox,
7431                        content_origin,
7432                        scroll_pixel_position,
7433                        gutter_dimensions.width - gutter_dimensions.left_padding,
7434                        window,
7435                        cx,
7436                    );
7437
7438                    let test_indicators = if gutter_settings.runnables {
7439                        self.layout_run_indicators(
7440                            line_height,
7441                            start_row..end_row,
7442                            scroll_pixel_position,
7443                            &gutter_dimensions,
7444                            &gutter_hitbox,
7445                            &rows_with_hunk_bounds,
7446                            &snapshot,
7447                            window,
7448                            cx,
7449                        )
7450                    } else {
7451                        Vec::new()
7452                    };
7453
7454                    self.layout_signature_help(
7455                        &hitbox,
7456                        content_origin,
7457                        scroll_pixel_position,
7458                        newest_selection_head,
7459                        start_row,
7460                        &line_layouts,
7461                        line_height,
7462                        em_width,
7463                        window,
7464                        cx,
7465                    );
7466
7467                    if !cx.has_active_drag() {
7468                        self.layout_hover_popovers(
7469                            &snapshot,
7470                            &hitbox,
7471                            &text_hitbox,
7472                            start_row..end_row,
7473                            content_origin,
7474                            scroll_pixel_position,
7475                            &line_layouts,
7476                            line_height,
7477                            em_width,
7478                            window,
7479                            cx,
7480                        );
7481                    }
7482
7483                    let inline_completion_popover = self.layout_edit_prediction_popover(
7484                        &text_hitbox.bounds,
7485                        content_origin,
7486                        &snapshot,
7487                        start_row..end_row,
7488                        scroll_position.y,
7489                        scroll_position.y + height_in_lines,
7490                        &line_layouts,
7491                        line_height,
7492                        scroll_pixel_position,
7493                        newest_selection_head,
7494                        editor_width,
7495                        &style,
7496                        window,
7497                        cx,
7498                    );
7499
7500                    let mouse_context_menu = self.layout_mouse_context_menu(
7501                        &snapshot,
7502                        start_row..end_row,
7503                        content_origin,
7504                        window,
7505                        cx,
7506                    );
7507
7508                    window.with_element_namespace("crease_toggles", |window| {
7509                        self.prepaint_crease_toggles(
7510                            &mut crease_toggles,
7511                            line_height,
7512                            &gutter_dimensions,
7513                            gutter_settings,
7514                            scroll_pixel_position,
7515                            &gutter_hitbox,
7516                            window,
7517                            cx,
7518                        )
7519                    });
7520
7521                    let invisible_symbol_font_size = font_size / 2.;
7522                    let tab_invisible = window
7523                        .text_system()
7524                        .shape_line(
7525                            "".into(),
7526                            invisible_symbol_font_size,
7527                            &[TextRun {
7528                                len: "".len(),
7529                                font: self.style.text.font(),
7530                                color: cx.theme().colors().editor_invisible,
7531                                background_color: None,
7532                                underline: None,
7533                                strikethrough: None,
7534                            }],
7535                        )
7536                        .unwrap();
7537                    let space_invisible = window
7538                        .text_system()
7539                        .shape_line(
7540                            "".into(),
7541                            invisible_symbol_font_size,
7542                            &[TextRun {
7543                                len: "".len(),
7544                                font: self.style.text.font(),
7545                                color: cx.theme().colors().editor_invisible,
7546                                background_color: None,
7547                                underline: None,
7548                                strikethrough: None,
7549                            }],
7550                        )
7551                        .unwrap();
7552
7553                    let mode = snapshot.mode;
7554
7555                    let position_map = Rc::new(PositionMap {
7556                        size: bounds.size,
7557                        visible_row_range,
7558                        scroll_pixel_position,
7559                        scroll_max,
7560                        line_layouts,
7561                        line_height,
7562                        em_width,
7563                        em_advance,
7564                        snapshot,
7565                        gutter_hitbox: gutter_hitbox.clone(),
7566                        text_hitbox: text_hitbox.clone(),
7567                    });
7568
7569                    self.editor.update(cx, |editor, _| {
7570                        editor.last_position_map = Some(position_map.clone())
7571                    });
7572
7573                    let hunk_controls = self.layout_diff_hunk_controls(
7574                        start_row..end_row,
7575                        &row_infos,
7576                        &text_hitbox,
7577                        &position_map,
7578                        newest_selection_head,
7579                        line_height,
7580                        scroll_pixel_position,
7581                        &display_hunks,
7582                        self.editor.clone(),
7583                        window,
7584                        cx,
7585                    );
7586
7587                    EditorLayout {
7588                        mode,
7589                        position_map,
7590                        visible_display_row_range: start_row..end_row,
7591                        wrap_guides,
7592                        indent_guides,
7593                        hitbox,
7594                        gutter_hitbox,
7595                        display_hunks,
7596                        content_origin,
7597                        scrollbars_layout,
7598                        active_rows,
7599                        highlighted_rows,
7600                        highlighted_ranges,
7601                        highlighted_gutter_ranges,
7602                        redacted_ranges,
7603                        line_elements,
7604                        line_numbers,
7605                        blamed_display_rows,
7606                        inline_blame,
7607                        blocks,
7608                        cursors,
7609                        visible_cursors,
7610                        selections,
7611                        inline_completion_popover,
7612                        diff_hunk_controls: hunk_controls,
7613                        mouse_context_menu,
7614                        test_indicators,
7615                        code_actions_indicator,
7616                        crease_toggles,
7617                        crease_trailers,
7618                        tab_invisible,
7619                        space_invisible,
7620                        sticky_buffer_header,
7621                    }
7622                })
7623            })
7624        })
7625    }
7626
7627    fn paint(
7628        &mut self,
7629        _: Option<&GlobalElementId>,
7630        bounds: Bounds<gpui::Pixels>,
7631        _: &mut Self::RequestLayoutState,
7632        layout: &mut Self::PrepaintState,
7633        window: &mut Window,
7634        cx: &mut App,
7635    ) {
7636        let focus_handle = self.editor.focus_handle(cx);
7637        let key_context = self
7638            .editor
7639            .update(cx, |editor, cx| editor.key_context(window, cx));
7640
7641        window.set_key_context(key_context);
7642        window.handle_input(
7643            &focus_handle,
7644            ElementInputHandler::new(bounds, self.editor.clone()),
7645            cx,
7646        );
7647        self.register_actions(window, cx);
7648        self.register_key_listeners(window, cx, layout);
7649
7650        let text_style = TextStyleRefinement {
7651            font_size: Some(self.style.text.font_size),
7652            line_height: Some(self.style.text.line_height),
7653            ..Default::default()
7654        };
7655        let rem_size = self.rem_size(cx);
7656        window.with_rem_size(rem_size, |window| {
7657            window.with_text_style(Some(text_style), |window| {
7658                window.with_content_mask(Some(ContentMask { bounds }), |window| {
7659                    self.paint_mouse_listeners(layout, window, cx);
7660                    self.paint_background(layout, window, cx);
7661                    self.paint_indent_guides(layout, window, cx);
7662
7663                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
7664                        self.paint_blamed_display_rows(layout, window, cx);
7665                        self.paint_line_numbers(layout, window, cx);
7666                    }
7667
7668                    self.paint_text(layout, window, cx);
7669
7670                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
7671                        self.paint_gutter_highlights(layout, window, cx);
7672                        self.paint_gutter_indicators(layout, window, cx);
7673                    }
7674
7675                    if !layout.blocks.is_empty() {
7676                        window.with_element_namespace("blocks", |window| {
7677                            self.paint_blocks(layout, window, cx);
7678                        });
7679                    }
7680
7681                    window.with_element_namespace("blocks", |window| {
7682                        if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
7683                            sticky_header.paint(window, cx)
7684                        }
7685                    });
7686
7687                    self.paint_scrollbars(layout, window, cx);
7688                    self.paint_inline_completion_popover(layout, window, cx);
7689                    self.paint_mouse_context_menu(layout, window, cx);
7690                });
7691            })
7692        })
7693    }
7694}
7695
7696pub(super) fn gutter_bounds(
7697    editor_bounds: Bounds<Pixels>,
7698    gutter_dimensions: GutterDimensions,
7699) -> Bounds<Pixels> {
7700    Bounds {
7701        origin: editor_bounds.origin,
7702        size: size(gutter_dimensions.width, editor_bounds.size.height),
7703    }
7704}
7705
7706struct ScrollbarRangeData {
7707    scrollbar_bounds: Bounds<Pixels>,
7708    scroll_range: Bounds<Pixels>,
7709    letter_size: Size<Pixels>,
7710}
7711
7712impl ScrollbarRangeData {
7713    #[allow(clippy::too_many_arguments)]
7714    pub fn new(
7715        scrollbar_bounds: Bounds<Pixels>,
7716        letter_size: Size<Pixels>,
7717        snapshot: &EditorSnapshot,
7718        longest_line_width: Pixels,
7719        longest_line_blame_width: Pixels,
7720        style: &EditorStyle,
7721        editor_width: Pixels,
7722        cx: &mut App,
7723    ) -> ScrollbarRangeData {
7724        // TODO: Simplify this function down, it requires a lot of parameters
7725        let max_row = snapshot.max_point().row();
7726        let text_bounds_size = size(longest_line_width, max_row.0 as f32 * letter_size.height);
7727
7728        let settings = EditorSettings::get_global(cx);
7729        let scroll_beyond_last_line: Pixels = match settings.scroll_beyond_last_line {
7730            ScrollBeyondLastLine::OnePage => px(scrollbar_bounds.size.height / letter_size.height),
7731            ScrollBeyondLastLine::Off => px(1.),
7732            ScrollBeyondLastLine::VerticalScrollMargin => px(1.0 + settings.vertical_scroll_margin),
7733        };
7734
7735        let right_margin = if longest_line_width + longest_line_blame_width >= editor_width {
7736            letter_size.width + style.scrollbar_width
7737        } else {
7738            px(0.0)
7739        };
7740
7741        let overscroll = size(
7742            right_margin + longest_line_blame_width,
7743            letter_size.height * scroll_beyond_last_line,
7744        );
7745
7746        let scroll_range = Bounds {
7747            origin: scrollbar_bounds.origin,
7748            size: text_bounds_size + overscroll,
7749        };
7750
7751        ScrollbarRangeData {
7752            scrollbar_bounds,
7753            scroll_range,
7754            letter_size,
7755        }
7756    }
7757}
7758
7759impl IntoElement for EditorElement {
7760    type Element = Self;
7761
7762    fn into_element(self) -> Self::Element {
7763        self
7764    }
7765}
7766
7767pub struct EditorLayout {
7768    position_map: Rc<PositionMap>,
7769    hitbox: Hitbox,
7770    gutter_hitbox: Hitbox,
7771    content_origin: gpui::Point<Pixels>,
7772    scrollbars_layout: AxisPair<Option<ScrollbarLayout>>,
7773    mode: EditorMode,
7774    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
7775    indent_guides: Option<Vec<IndentGuideLayout>>,
7776    visible_display_row_range: Range<DisplayRow>,
7777    active_rows: BTreeMap<DisplayRow, bool>,
7778    highlighted_rows: BTreeMap<DisplayRow, gpui::Background>,
7779    line_elements: SmallVec<[AnyElement; 1]>,
7780    line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
7781    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
7782    blamed_display_rows: Option<Vec<AnyElement>>,
7783    inline_blame: Option<AnyElement>,
7784    blocks: Vec<BlockLayout>,
7785    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7786    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7787    redacted_ranges: Vec<Range<DisplayPoint>>,
7788    cursors: Vec<(DisplayPoint, Hsla)>,
7789    visible_cursors: Vec<CursorLayout>,
7790    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
7791    code_actions_indicator: Option<AnyElement>,
7792    test_indicators: Vec<AnyElement>,
7793    crease_toggles: Vec<Option<AnyElement>>,
7794    diff_hunk_controls: Vec<AnyElement>,
7795    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
7796    inline_completion_popover: Option<AnyElement>,
7797    mouse_context_menu: Option<AnyElement>,
7798    tab_invisible: ShapedLine,
7799    space_invisible: ShapedLine,
7800    sticky_buffer_header: Option<AnyElement>,
7801}
7802
7803impl EditorLayout {
7804    fn line_end_overshoot(&self) -> Pixels {
7805        0.15 * self.position_map.line_height
7806    }
7807}
7808
7809struct LineNumberLayout {
7810    shaped_line: ShapedLine,
7811    hitbox: Option<Hitbox>,
7812    display_row: DisplayRow,
7813}
7814
7815struct ColoredRange<T> {
7816    start: T,
7817    end: T,
7818    color: Hsla,
7819}
7820
7821#[derive(Clone)]
7822struct ScrollbarLayout {
7823    hitbox: Hitbox,
7824    visible_range: Range<f32>,
7825    visible: bool,
7826    text_unit_size: Pixels,
7827    thumb_size: Pixels,
7828    axis: Axis,
7829}
7830
7831impl ScrollbarLayout {
7832    const BORDER_WIDTH: Pixels = px(1.0);
7833    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
7834    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
7835    // const MIN_THUMB_HEIGHT: Pixels = px(20.0);
7836
7837    fn thumb_bounds(&self) -> Bounds<Pixels> {
7838        match self.axis {
7839            Axis::Vertical => {
7840                let thumb_top = self.y_for_row(self.visible_range.start);
7841                let thumb_bottom = thumb_top + self.thumb_size;
7842                Bounds::from_corners(
7843                    point(self.hitbox.left(), thumb_top),
7844                    point(self.hitbox.right(), thumb_bottom),
7845                )
7846            }
7847            Axis::Horizontal => {
7848                let thumb_left =
7849                    self.hitbox.left() + self.visible_range.start * self.text_unit_size;
7850                let thumb_right = thumb_left + self.thumb_size;
7851                Bounds::from_corners(
7852                    point(thumb_left, self.hitbox.top()),
7853                    point(thumb_right, self.hitbox.bottom()),
7854                )
7855            }
7856        }
7857    }
7858
7859    fn y_for_row(&self, row: f32) -> Pixels {
7860        self.hitbox.top() + row * self.text_unit_size
7861    }
7862
7863    fn marker_quads_for_ranges(
7864        &self,
7865        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
7866        column: Option<usize>,
7867    ) -> Vec<PaintQuad> {
7868        struct MinMax {
7869            min: Pixels,
7870            max: Pixels,
7871        }
7872        let (x_range, height_limit) = if let Some(column) = column {
7873            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
7874            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
7875            let end = start + column_width;
7876            (
7877                Range { start, end },
7878                MinMax {
7879                    min: Self::MIN_MARKER_HEIGHT,
7880                    max: px(f32::MAX),
7881                },
7882            )
7883        } else {
7884            (
7885                Range {
7886                    start: Self::BORDER_WIDTH,
7887                    end: self.hitbox.size.width,
7888                },
7889                MinMax {
7890                    min: Self::LINE_MARKER_HEIGHT,
7891                    max: Self::LINE_MARKER_HEIGHT,
7892                },
7893            )
7894        };
7895
7896        let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
7897        let mut pixel_ranges = row_ranges
7898            .into_iter()
7899            .map(|range| {
7900                let start_y = row_to_y(range.start);
7901                let end_y = row_to_y(range.end)
7902                    + self
7903                        .text_unit_size
7904                        .max(height_limit.min)
7905                        .min(height_limit.max);
7906                ColoredRange {
7907                    start: start_y,
7908                    end: end_y,
7909                    color: range.color,
7910                }
7911            })
7912            .peekable();
7913
7914        let mut quads = Vec::new();
7915        while let Some(mut pixel_range) = pixel_ranges.next() {
7916            while let Some(next_pixel_range) = pixel_ranges.peek() {
7917                if pixel_range.end >= next_pixel_range.start - px(1.0)
7918                    && pixel_range.color == next_pixel_range.color
7919                {
7920                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
7921                    pixel_ranges.next();
7922                } else {
7923                    break;
7924                }
7925            }
7926
7927            let bounds = Bounds::from_corners(
7928                point(x_range.start, pixel_range.start),
7929                point(x_range.end, pixel_range.end),
7930            );
7931            quads.push(quad(
7932                bounds,
7933                Corners::default(),
7934                pixel_range.color,
7935                Edges::default(),
7936                Hsla::transparent_black(),
7937            ));
7938        }
7939
7940        quads
7941    }
7942}
7943
7944struct CreaseTrailerLayout {
7945    element: AnyElement,
7946    bounds: Bounds<Pixels>,
7947}
7948
7949pub(crate) struct PositionMap {
7950    pub size: Size<Pixels>,
7951    pub line_height: Pixels,
7952    pub scroll_pixel_position: gpui::Point<Pixels>,
7953    pub scroll_max: gpui::Point<f32>,
7954    pub em_width: Pixels,
7955    pub em_advance: Pixels,
7956    pub visible_row_range: Range<DisplayRow>,
7957    pub line_layouts: Vec<LineWithInvisibles>,
7958    pub snapshot: EditorSnapshot,
7959    pub text_hitbox: Hitbox,
7960    pub gutter_hitbox: Hitbox,
7961}
7962
7963#[derive(Debug, Copy, Clone)]
7964pub struct PointForPosition {
7965    pub previous_valid: DisplayPoint,
7966    pub next_valid: DisplayPoint,
7967    pub exact_unclipped: DisplayPoint,
7968    pub column_overshoot_after_line_end: u32,
7969}
7970
7971impl PointForPosition {
7972    pub fn as_valid(&self) -> Option<DisplayPoint> {
7973        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
7974            Some(self.previous_valid)
7975        } else {
7976            None
7977        }
7978    }
7979}
7980
7981impl PositionMap {
7982    pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
7983        let text_bounds = self.text_hitbox.bounds;
7984        let scroll_position = self.snapshot.scroll_position();
7985        let position = position - text_bounds.origin;
7986        let y = position.y.max(px(0.)).min(self.size.height);
7987        let x = position.x + (scroll_position.x * self.em_width);
7988        let row = ((y / self.line_height) + scroll_position.y) as u32;
7989
7990        let (column, x_overshoot_after_line_end) = if let Some(line) = self
7991            .line_layouts
7992            .get(row as usize - scroll_position.y as usize)
7993        {
7994            if let Some(ix) = line.index_for_x(x) {
7995                (ix as u32, px(0.))
7996            } else {
7997                (line.len as u32, px(0.).max(x - line.width))
7998            }
7999        } else {
8000            (0, x)
8001        };
8002
8003        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
8004        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
8005        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
8006
8007        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
8008        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
8009        PointForPosition {
8010            previous_valid,
8011            next_valid,
8012            exact_unclipped,
8013            column_overshoot_after_line_end,
8014        }
8015    }
8016}
8017
8018struct BlockLayout {
8019    id: BlockId,
8020    row: Option<DisplayRow>,
8021    element: AnyElement,
8022    available_space: Size<AvailableSpace>,
8023    style: BlockStyle,
8024}
8025
8026fn layout_line(
8027    row: DisplayRow,
8028    snapshot: &EditorSnapshot,
8029    style: &EditorStyle,
8030    text_width: Pixels,
8031    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
8032    window: &mut Window,
8033    cx: &mut App,
8034) -> LineWithInvisibles {
8035    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
8036    LineWithInvisibles::from_chunks(
8037        chunks,
8038        &style,
8039        MAX_LINE_LEN,
8040        1,
8041        snapshot.mode,
8042        text_width,
8043        is_row_soft_wrapped,
8044        window,
8045        cx,
8046    )
8047    .pop()
8048    .unwrap()
8049}
8050
8051#[derive(Debug)]
8052pub struct IndentGuideLayout {
8053    origin: gpui::Point<Pixels>,
8054    length: Pixels,
8055    single_indent_width: Pixels,
8056    depth: u32,
8057    active: bool,
8058    settings: IndentGuideSettings,
8059}
8060
8061pub struct CursorLayout {
8062    origin: gpui::Point<Pixels>,
8063    block_width: Pixels,
8064    line_height: Pixels,
8065    color: Hsla,
8066    shape: CursorShape,
8067    block_text: Option<ShapedLine>,
8068    cursor_name: Option<AnyElement>,
8069}
8070
8071#[derive(Debug)]
8072pub struct CursorName {
8073    string: SharedString,
8074    color: Hsla,
8075    is_top_row: bool,
8076}
8077
8078impl CursorLayout {
8079    pub fn new(
8080        origin: gpui::Point<Pixels>,
8081        block_width: Pixels,
8082        line_height: Pixels,
8083        color: Hsla,
8084        shape: CursorShape,
8085        block_text: Option<ShapedLine>,
8086    ) -> CursorLayout {
8087        CursorLayout {
8088            origin,
8089            block_width,
8090            line_height,
8091            color,
8092            shape,
8093            block_text,
8094            cursor_name: None,
8095        }
8096    }
8097
8098    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8099        Bounds {
8100            origin: self.origin + origin,
8101            size: size(self.block_width, self.line_height),
8102        }
8103    }
8104
8105    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8106        match self.shape {
8107            CursorShape::Bar => Bounds {
8108                origin: self.origin + origin,
8109                size: size(px(2.0), self.line_height),
8110            },
8111            CursorShape::Block | CursorShape::Hollow => Bounds {
8112                origin: self.origin + origin,
8113                size: size(self.block_width, self.line_height),
8114            },
8115            CursorShape::Underline => Bounds {
8116                origin: self.origin
8117                    + origin
8118                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
8119                size: size(self.block_width, px(2.0)),
8120            },
8121        }
8122    }
8123
8124    pub fn layout(
8125        &mut self,
8126        origin: gpui::Point<Pixels>,
8127        cursor_name: Option<CursorName>,
8128        window: &mut Window,
8129        cx: &mut App,
8130    ) {
8131        if let Some(cursor_name) = cursor_name {
8132            let bounds = self.bounds(origin);
8133            let text_size = self.line_height / 1.5;
8134
8135            let name_origin = if cursor_name.is_top_row {
8136                point(bounds.right() - px(1.), bounds.top())
8137            } else {
8138                match self.shape {
8139                    CursorShape::Bar => point(
8140                        bounds.right() - px(2.),
8141                        bounds.top() - text_size / 2. - px(1.),
8142                    ),
8143                    _ => point(
8144                        bounds.right() - px(1.),
8145                        bounds.top() - text_size / 2. - px(1.),
8146                    ),
8147                }
8148            };
8149            let mut name_element = div()
8150                .bg(self.color)
8151                .text_size(text_size)
8152                .px_0p5()
8153                .line_height(text_size + px(2.))
8154                .text_color(cursor_name.color)
8155                .child(cursor_name.string.clone())
8156                .into_any_element();
8157
8158            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
8159
8160            self.cursor_name = Some(name_element);
8161        }
8162    }
8163
8164    pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
8165        let bounds = self.bounds(origin);
8166
8167        //Draw background or border quad
8168        let cursor = if matches!(self.shape, CursorShape::Hollow) {
8169            outline(bounds, self.color)
8170        } else {
8171            fill(bounds, self.color)
8172        };
8173
8174        if let Some(name) = &mut self.cursor_name {
8175            name.paint(window, cx);
8176        }
8177
8178        window.paint_quad(cursor);
8179
8180        if let Some(block_text) = &self.block_text {
8181            block_text
8182                .paint(self.origin + origin, self.line_height, window, cx)
8183                .log_err();
8184        }
8185    }
8186
8187    pub fn shape(&self) -> CursorShape {
8188        self.shape
8189    }
8190}
8191
8192#[derive(Debug)]
8193pub struct HighlightedRange {
8194    pub start_y: Pixels,
8195    pub line_height: Pixels,
8196    pub lines: Vec<HighlightedRangeLine>,
8197    pub color: Hsla,
8198    pub corner_radius: Pixels,
8199}
8200
8201#[derive(Debug)]
8202pub struct HighlightedRangeLine {
8203    pub start_x: Pixels,
8204    pub end_x: Pixels,
8205}
8206
8207impl HighlightedRange {
8208    pub fn paint(&self, bounds: Bounds<Pixels>, window: &mut Window) {
8209        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
8210            self.paint_lines(self.start_y, &self.lines[0..1], bounds, window);
8211            self.paint_lines(
8212                self.start_y + self.line_height,
8213                &self.lines[1..],
8214                bounds,
8215                window,
8216            );
8217        } else {
8218            self.paint_lines(self.start_y, &self.lines, bounds, window);
8219        }
8220    }
8221
8222    fn paint_lines(
8223        &self,
8224        start_y: Pixels,
8225        lines: &[HighlightedRangeLine],
8226        _bounds: Bounds<Pixels>,
8227        window: &mut Window,
8228    ) {
8229        if lines.is_empty() {
8230            return;
8231        }
8232
8233        let first_line = lines.first().unwrap();
8234        let last_line = lines.last().unwrap();
8235
8236        let first_top_left = point(first_line.start_x, start_y);
8237        let first_top_right = point(first_line.end_x, start_y);
8238
8239        let curve_height = point(Pixels::ZERO, self.corner_radius);
8240        let curve_width = |start_x: Pixels, end_x: Pixels| {
8241            let max = (end_x - start_x) / 2.;
8242            let width = if max < self.corner_radius {
8243                max
8244            } else {
8245                self.corner_radius
8246            };
8247
8248            point(width, Pixels::ZERO)
8249        };
8250
8251        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
8252        let mut builder = gpui::PathBuilder::fill();
8253        builder.move_to(first_top_right - top_curve_width);
8254        builder.curve_to(first_top_right + curve_height, first_top_right);
8255
8256        let mut iter = lines.iter().enumerate().peekable();
8257        while let Some((ix, line)) = iter.next() {
8258            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
8259
8260            if let Some((_, next_line)) = iter.peek() {
8261                let next_top_right = point(next_line.end_x, bottom_right.y);
8262
8263                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
8264                    Ordering::Equal => {
8265                        builder.line_to(bottom_right);
8266                    }
8267                    Ordering::Less => {
8268                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
8269                        builder.line_to(bottom_right - curve_height);
8270                        if self.corner_radius > Pixels::ZERO {
8271                            builder.curve_to(bottom_right - curve_width, bottom_right);
8272                        }
8273                        builder.line_to(next_top_right + curve_width);
8274                        if self.corner_radius > Pixels::ZERO {
8275                            builder.curve_to(next_top_right + curve_height, next_top_right);
8276                        }
8277                    }
8278                    Ordering::Greater => {
8279                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
8280                        builder.line_to(bottom_right - curve_height);
8281                        if self.corner_radius > Pixels::ZERO {
8282                            builder.curve_to(bottom_right + curve_width, bottom_right);
8283                        }
8284                        builder.line_to(next_top_right - curve_width);
8285                        if self.corner_radius > Pixels::ZERO {
8286                            builder.curve_to(next_top_right + curve_height, next_top_right);
8287                        }
8288                    }
8289                }
8290            } else {
8291                let curve_width = curve_width(line.start_x, line.end_x);
8292                builder.line_to(bottom_right - curve_height);
8293                if self.corner_radius > Pixels::ZERO {
8294                    builder.curve_to(bottom_right - curve_width, bottom_right);
8295                }
8296
8297                let bottom_left = point(line.start_x, bottom_right.y);
8298                builder.line_to(bottom_left + curve_width);
8299                if self.corner_radius > Pixels::ZERO {
8300                    builder.curve_to(bottom_left - curve_height, bottom_left);
8301                }
8302            }
8303        }
8304
8305        if first_line.start_x > last_line.start_x {
8306            let curve_width = curve_width(last_line.start_x, first_line.start_x);
8307            let second_top_left = point(last_line.start_x, start_y + self.line_height);
8308            builder.line_to(second_top_left + curve_height);
8309            if self.corner_radius > Pixels::ZERO {
8310                builder.curve_to(second_top_left + curve_width, second_top_left);
8311            }
8312            let first_bottom_left = point(first_line.start_x, second_top_left.y);
8313            builder.line_to(first_bottom_left - curve_width);
8314            if self.corner_radius > Pixels::ZERO {
8315                builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
8316            }
8317        }
8318
8319        builder.line_to(first_top_left + curve_height);
8320        if self.corner_radius > Pixels::ZERO {
8321            builder.curve_to(first_top_left + top_curve_width, first_top_left);
8322        }
8323        builder.line_to(first_top_right - top_curve_width);
8324
8325        if let Ok(path) = builder.build() {
8326            window.paint_path(path, self.color);
8327        }
8328    }
8329}
8330
8331enum CursorPopoverType {
8332    CodeContextMenu,
8333    EditPrediction,
8334}
8335
8336pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8337    (delta.pow(1.5) / 100.0).into()
8338}
8339
8340fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8341    (delta.pow(1.2) / 300.0).into()
8342}
8343
8344pub fn register_action<T: Action>(
8345    editor: &Entity<Editor>,
8346    window: &mut Window,
8347    listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
8348) {
8349    let editor = editor.clone();
8350    window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
8351        let action = action.downcast_ref().unwrap();
8352        if phase == DispatchPhase::Bubble {
8353            editor.update(cx, |editor, cx| {
8354                listener(editor, action, window, cx);
8355            })
8356        }
8357    })
8358}
8359
8360fn compute_auto_height_layout(
8361    editor: &mut Editor,
8362    max_lines: usize,
8363    max_line_number_width: Pixels,
8364    known_dimensions: Size<Option<Pixels>>,
8365    available_width: AvailableSpace,
8366    window: &mut Window,
8367    cx: &mut Context<Editor>,
8368) -> Option<Size<Pixels>> {
8369    let width = known_dimensions.width.or({
8370        if let AvailableSpace::Definite(available_width) = available_width {
8371            Some(available_width)
8372        } else {
8373            None
8374        }
8375    })?;
8376    if let Some(height) = known_dimensions.height {
8377        return Some(size(width, height));
8378    }
8379
8380    let style = editor.style.as_ref().unwrap();
8381    let font_id = window.text_system().resolve_font(&style.text.font());
8382    let font_size = style.text.font_size.to_pixels(window.rem_size());
8383    let line_height = style.text.line_height_in_pixels(window.rem_size());
8384    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8385
8386    let mut snapshot = editor.snapshot(window, cx);
8387    let gutter_dimensions = snapshot
8388        .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
8389        .unwrap_or_default();
8390
8391    editor.gutter_dimensions = gutter_dimensions;
8392    let text_width = width - gutter_dimensions.width;
8393    let overscroll = size(em_width, px(0.));
8394
8395    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
8396    if editor.set_wrap_width(Some(editor_width), cx) {
8397        snapshot = editor.snapshot(window, cx);
8398    }
8399
8400    let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
8401    let height = scroll_height
8402        .max(line_height)
8403        .min(line_height * max_lines as f32);
8404
8405    Some(size(width, height))
8406}
8407
8408#[cfg(test)]
8409mod tests {
8410    use super::*;
8411    use crate::{
8412        display_map::{BlockPlacement, BlockProperties},
8413        editor_tests::{init_test, update_test_language_settings},
8414        Editor, MultiBuffer,
8415    };
8416    use gpui::{TestAppContext, VisualTestContext};
8417    use language::language_settings;
8418    use log::info;
8419    use similar::DiffableStr;
8420    use std::num::NonZeroU32;
8421    use util::test::sample_text;
8422
8423    #[gpui::test]
8424    fn test_shape_line_numbers(cx: &mut TestAppContext) {
8425        init_test(cx, |_| {});
8426        let window = cx.add_window(|window, cx| {
8427            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
8428            Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8429        });
8430
8431        let editor = window.root(cx).unwrap();
8432        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
8433        let line_height = window
8434            .update(cx, |_, window, _| {
8435                style.text.line_height_in_pixels(window.rem_size())
8436            })
8437            .unwrap();
8438        let element = EditorElement::new(&editor, style);
8439        let snapshot = window
8440            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
8441            .unwrap();
8442
8443        let layouts = cx
8444            .update_window(*window, |_, window, cx| {
8445                element.layout_line_numbers(
8446                    None,
8447                    GutterDimensions {
8448                        left_padding: Pixels::ZERO,
8449                        right_padding: Pixels::ZERO,
8450                        width: px(30.0),
8451                        margin: Pixels::ZERO,
8452                        git_blame_entries_width: None,
8453                    },
8454                    line_height,
8455                    gpui::Point::default(),
8456                    DisplayRow(0)..DisplayRow(6),
8457                    &(0..6)
8458                        .map(|row| RowInfo {
8459                            buffer_row: Some(row),
8460                            ..Default::default()
8461                        })
8462                        .collect::<Vec<_>>(),
8463                    Some(DisplayPoint::new(DisplayRow(0), 0)),
8464                    &snapshot,
8465                    window,
8466                    cx,
8467                )
8468            })
8469            .unwrap();
8470        assert_eq!(layouts.len(), 6);
8471
8472        let relative_rows = window
8473            .update(cx, |editor, window, cx| {
8474                let snapshot = editor.snapshot(window, cx);
8475                element.calculate_relative_line_numbers(
8476                    &snapshot,
8477                    &(DisplayRow(0)..DisplayRow(6)),
8478                    Some(DisplayRow(3)),
8479                )
8480            })
8481            .unwrap();
8482        assert_eq!(relative_rows[&DisplayRow(0)], 3);
8483        assert_eq!(relative_rows[&DisplayRow(1)], 2);
8484        assert_eq!(relative_rows[&DisplayRow(2)], 1);
8485        // current line has no relative number
8486        assert_eq!(relative_rows[&DisplayRow(4)], 1);
8487        assert_eq!(relative_rows[&DisplayRow(5)], 2);
8488
8489        // works if cursor is before screen
8490        let relative_rows = window
8491            .update(cx, |editor, window, cx| {
8492                let snapshot = editor.snapshot(window, cx);
8493                element.calculate_relative_line_numbers(
8494                    &snapshot,
8495                    &(DisplayRow(3)..DisplayRow(6)),
8496                    Some(DisplayRow(1)),
8497                )
8498            })
8499            .unwrap();
8500        assert_eq!(relative_rows.len(), 3);
8501        assert_eq!(relative_rows[&DisplayRow(3)], 2);
8502        assert_eq!(relative_rows[&DisplayRow(4)], 3);
8503        assert_eq!(relative_rows[&DisplayRow(5)], 4);
8504
8505        // works if cursor is after screen
8506        let relative_rows = window
8507            .update(cx, |editor, window, cx| {
8508                let snapshot = editor.snapshot(window, cx);
8509                element.calculate_relative_line_numbers(
8510                    &snapshot,
8511                    &(DisplayRow(0)..DisplayRow(3)),
8512                    Some(DisplayRow(6)),
8513                )
8514            })
8515            .unwrap();
8516        assert_eq!(relative_rows.len(), 3);
8517        assert_eq!(relative_rows[&DisplayRow(0)], 5);
8518        assert_eq!(relative_rows[&DisplayRow(1)], 4);
8519        assert_eq!(relative_rows[&DisplayRow(2)], 3);
8520    }
8521
8522    #[gpui::test]
8523    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
8524        init_test(cx, |_| {});
8525
8526        let window = cx.add_window(|window, cx| {
8527            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
8528            Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8529        });
8530        let cx = &mut VisualTestContext::from_window(*window, cx);
8531        let editor = window.root(cx).unwrap();
8532        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8533
8534        window
8535            .update(cx, |editor, window, cx| {
8536                editor.cursor_shape = CursorShape::Block;
8537                editor.change_selections(None, window, cx, |s| {
8538                    s.select_ranges([
8539                        Point::new(0, 0)..Point::new(1, 0),
8540                        Point::new(3, 2)..Point::new(3, 3),
8541                        Point::new(5, 6)..Point::new(6, 0),
8542                    ]);
8543                });
8544            })
8545            .unwrap();
8546
8547        let (_, state) = cx.draw(
8548            point(px(500.), px(500.)),
8549            size(px(500.), px(500.)),
8550            |_, _| EditorElement::new(&editor, style),
8551        );
8552
8553        assert_eq!(state.selections.len(), 1);
8554        let local_selections = &state.selections[0].1;
8555        assert_eq!(local_selections.len(), 3);
8556        // moves cursor back one line
8557        assert_eq!(
8558            local_selections[0].head,
8559            DisplayPoint::new(DisplayRow(0), 6)
8560        );
8561        assert_eq!(
8562            local_selections[0].range,
8563            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
8564        );
8565
8566        // moves cursor back one column
8567        assert_eq!(
8568            local_selections[1].range,
8569            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
8570        );
8571        assert_eq!(
8572            local_selections[1].head,
8573            DisplayPoint::new(DisplayRow(3), 2)
8574        );
8575
8576        // leaves cursor on the max point
8577        assert_eq!(
8578            local_selections[2].range,
8579            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
8580        );
8581        assert_eq!(
8582            local_selections[2].head,
8583            DisplayPoint::new(DisplayRow(6), 0)
8584        );
8585
8586        // active lines does not include 1 (even though the range of the selection does)
8587        assert_eq!(
8588            state.active_rows.keys().cloned().collect::<Vec<_>>(),
8589            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
8590        );
8591
8592        // multi-buffer support
8593        // in DisplayPoint coordinates, this is what we're dealing with:
8594        //  0: [[file
8595        //  1:   header
8596        //  2:   section]]
8597        //  3: aaaaaa
8598        //  4: bbbbbb
8599        //  5: cccccc
8600        //  6:
8601        //  7: [[footer]]
8602        //  8: [[header]]
8603        //  9: ffffff
8604        // 10: gggggg
8605        // 11: hhhhhh
8606        // 12:
8607        // 13: [[footer]]
8608        // 14: [[file
8609        // 15:   header
8610        // 16:   section]]
8611        // 17: bbbbbb
8612        // 18: cccccc
8613        // 19: dddddd
8614        // 20: [[footer]]
8615        let window = cx.add_window(|window, cx| {
8616            let buffer = MultiBuffer::build_multi(
8617                [
8618                    (
8619                        &(sample_text(8, 6, 'a') + "\n"),
8620                        vec![
8621                            Point::new(0, 0)..Point::new(3, 0),
8622                            Point::new(4, 0)..Point::new(7, 0),
8623                        ],
8624                    ),
8625                    (
8626                        &(sample_text(8, 6, 'a') + "\n"),
8627                        vec![Point::new(1, 0)..Point::new(3, 0)],
8628                    ),
8629                ],
8630                cx,
8631            );
8632            Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8633        });
8634        let editor = window.root(cx).unwrap();
8635        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8636        let _state = window.update(cx, |editor, window, cx| {
8637            editor.cursor_shape = CursorShape::Block;
8638            editor.change_selections(None, window, cx, |s| {
8639                s.select_display_ranges([
8640                    DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
8641                    DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
8642                ]);
8643            });
8644        });
8645
8646        let (_, state) = cx.draw(
8647            point(px(500.), px(500.)),
8648            size(px(500.), px(500.)),
8649            |_, _| EditorElement::new(&editor, style),
8650        );
8651        assert_eq!(state.selections.len(), 1);
8652        let local_selections = &state.selections[0].1;
8653        assert_eq!(local_selections.len(), 2);
8654
8655        // moves cursor on excerpt boundary back a line
8656        // and doesn't allow selection to bleed through
8657        assert_eq!(
8658            local_selections[0].range,
8659            DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
8660        );
8661        assert_eq!(
8662            local_selections[0].head,
8663            DisplayPoint::new(DisplayRow(6), 0)
8664        );
8665        // moves cursor on buffer boundary back two lines
8666        // and doesn't allow selection to bleed through
8667        assert_eq!(
8668            local_selections[1].range,
8669            DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
8670        );
8671        assert_eq!(
8672            local_selections[1].head,
8673            DisplayPoint::new(DisplayRow(12), 0)
8674        );
8675    }
8676
8677    #[gpui::test]
8678    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
8679        init_test(cx, |_| {});
8680
8681        let window = cx.add_window(|window, cx| {
8682            let buffer = MultiBuffer::build_simple("", cx);
8683            Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8684        });
8685        let cx = &mut VisualTestContext::from_window(*window, cx);
8686        let editor = window.root(cx).unwrap();
8687        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8688        window
8689            .update(cx, |editor, window, cx| {
8690                editor.set_placeholder_text("hello", cx);
8691                editor.insert_blocks(
8692                    [BlockProperties {
8693                        style: BlockStyle::Fixed,
8694                        placement: BlockPlacement::Above(Anchor::min()),
8695                        height: 3,
8696                        render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
8697                        priority: 0,
8698                    }],
8699                    None,
8700                    cx,
8701                );
8702
8703                // Blur the editor so that it displays placeholder text.
8704                window.blur();
8705            })
8706            .unwrap();
8707
8708        let (_, state) = cx.draw(
8709            point(px(500.), px(500.)),
8710            size(px(500.), px(500.)),
8711            |_, _| EditorElement::new(&editor, style),
8712        );
8713        assert_eq!(state.position_map.line_layouts.len(), 4);
8714        assert_eq!(state.line_numbers.len(), 1);
8715        assert_eq!(
8716            state
8717                .line_numbers
8718                .get(&MultiBufferRow(0))
8719                .and_then(|line_number| line_number.shaped_line.text.as_str()),
8720            Some("1")
8721        );
8722    }
8723
8724    #[gpui::test]
8725    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
8726        const TAB_SIZE: u32 = 4;
8727
8728        let input_text = "\t \t|\t| a b";
8729        let expected_invisibles = vec![
8730            Invisible::Tab {
8731                line_start_offset: 0,
8732                line_end_offset: TAB_SIZE as usize,
8733            },
8734            Invisible::Whitespace {
8735                line_offset: TAB_SIZE as usize,
8736            },
8737            Invisible::Tab {
8738                line_start_offset: TAB_SIZE as usize + 1,
8739                line_end_offset: TAB_SIZE as usize * 2,
8740            },
8741            Invisible::Tab {
8742                line_start_offset: TAB_SIZE as usize * 2 + 1,
8743                line_end_offset: TAB_SIZE as usize * 3,
8744            },
8745            Invisible::Whitespace {
8746                line_offset: TAB_SIZE as usize * 3 + 1,
8747            },
8748            Invisible::Whitespace {
8749                line_offset: TAB_SIZE as usize * 3 + 3,
8750            },
8751        ];
8752        assert_eq!(
8753            expected_invisibles.len(),
8754            input_text
8755                .chars()
8756                .filter(|initial_char| initial_char.is_whitespace())
8757                .count(),
8758            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8759        );
8760
8761        for show_line_numbers in [true, false] {
8762            init_test(cx, |s| {
8763                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8764                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
8765            });
8766
8767            let actual_invisibles = collect_invisibles_from_new_editor(
8768                cx,
8769                EditorMode::Full,
8770                input_text,
8771                px(500.0),
8772                show_line_numbers,
8773            );
8774
8775            assert_eq!(expected_invisibles, actual_invisibles);
8776        }
8777    }
8778
8779    #[gpui::test]
8780    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
8781        init_test(cx, |s| {
8782            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8783            s.defaults.tab_size = NonZeroU32::new(4);
8784        });
8785
8786        for editor_mode_without_invisibles in [
8787            EditorMode::SingleLine { auto_width: false },
8788            EditorMode::AutoHeight { max_lines: 100 },
8789        ] {
8790            for show_line_numbers in [true, false] {
8791                let invisibles = collect_invisibles_from_new_editor(
8792                    cx,
8793                    editor_mode_without_invisibles,
8794                    "\t\t\t| | a b",
8795                    px(500.0),
8796                    show_line_numbers,
8797                );
8798                assert!(invisibles.is_empty(),
8799                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
8800            }
8801        }
8802    }
8803
8804    #[gpui::test]
8805    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
8806        let tab_size = 4;
8807        let input_text = "a\tbcd     ".repeat(9);
8808        let repeated_invisibles = [
8809            Invisible::Tab {
8810                line_start_offset: 1,
8811                line_end_offset: tab_size as usize,
8812            },
8813            Invisible::Whitespace {
8814                line_offset: tab_size as usize + 3,
8815            },
8816            Invisible::Whitespace {
8817                line_offset: tab_size as usize + 4,
8818            },
8819            Invisible::Whitespace {
8820                line_offset: tab_size as usize + 5,
8821            },
8822            Invisible::Whitespace {
8823                line_offset: tab_size as usize + 6,
8824            },
8825            Invisible::Whitespace {
8826                line_offset: tab_size as usize + 7,
8827            },
8828        ];
8829        let expected_invisibles = std::iter::once(repeated_invisibles)
8830            .cycle()
8831            .take(9)
8832            .flatten()
8833            .collect::<Vec<_>>();
8834        assert_eq!(
8835            expected_invisibles.len(),
8836            input_text
8837                .chars()
8838                .filter(|initial_char| initial_char.is_whitespace())
8839                .count(),
8840            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8841        );
8842        info!("Expected invisibles: {expected_invisibles:?}");
8843
8844        init_test(cx, |_| {});
8845
8846        // Put the same string with repeating whitespace pattern into editors of various size,
8847        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
8848        let resize_step = 10.0;
8849        let mut editor_width = 200.0;
8850        while editor_width <= 1000.0 {
8851            for show_line_numbers in [true, false] {
8852                update_test_language_settings(cx, |s| {
8853                    s.defaults.tab_size = NonZeroU32::new(tab_size);
8854                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8855                    s.defaults.preferred_line_length = Some(editor_width as u32);
8856                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
8857                });
8858
8859                let actual_invisibles = collect_invisibles_from_new_editor(
8860                    cx,
8861                    EditorMode::Full,
8862                    &input_text,
8863                    px(editor_width),
8864                    show_line_numbers,
8865                );
8866
8867                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
8868                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
8869                let mut i = 0;
8870                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
8871                    i = actual_index;
8872                    match expected_invisibles.get(i) {
8873                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
8874                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
8875                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
8876                            _ => {
8877                                panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
8878                            }
8879                        },
8880                        None => {
8881                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
8882                        }
8883                    }
8884                }
8885                let missing_expected_invisibles = &expected_invisibles[i + 1..];
8886                assert!(
8887                    missing_expected_invisibles.is_empty(),
8888                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
8889                );
8890
8891                editor_width += resize_step;
8892            }
8893        }
8894    }
8895
8896    fn collect_invisibles_from_new_editor(
8897        cx: &mut TestAppContext,
8898        editor_mode: EditorMode,
8899        input_text: &str,
8900        editor_width: Pixels,
8901        show_line_numbers: bool,
8902    ) -> Vec<Invisible> {
8903        info!(
8904            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
8905            editor_width.0
8906        );
8907        let window = cx.add_window(|window, cx| {
8908            let buffer = MultiBuffer::build_simple(input_text, cx);
8909            Editor::new(editor_mode, buffer, None, true, window, cx)
8910        });
8911        let cx = &mut VisualTestContext::from_window(*window, cx);
8912        let editor = window.root(cx).unwrap();
8913
8914        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8915        window
8916            .update(cx, |editor, _, cx| {
8917                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
8918                editor.set_wrap_width(Some(editor_width), cx);
8919                editor.set_show_line_numbers(show_line_numbers, cx);
8920            })
8921            .unwrap();
8922        let (_, state) = cx.draw(
8923            point(px(500.), px(500.)),
8924            size(px(500.), px(500.)),
8925            |_, _| EditorElement::new(&editor, style),
8926        );
8927        state
8928            .position_map
8929            .line_layouts
8930            .iter()
8931            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
8932            .cloned()
8933            .collect()
8934    }
8935}
8936
8937fn diff_hunk_controls(
8938    row: u32,
8939    hunk_range: Range<Anchor>,
8940    line_height: Pixels,
8941    editor: &Entity<Editor>,
8942    cx: &mut App,
8943) -> AnyElement {
8944    h_flex()
8945        .h(line_height)
8946        .mr_1()
8947        .gap_1()
8948        .px_1()
8949        .pb_1()
8950        .border_b_1()
8951        .border_color(cx.theme().colors().border_variant)
8952        .rounded_b_lg()
8953        .bg(cx.theme().colors().editor_background)
8954        .gap_1()
8955        .child(
8956            IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
8957                .shape(IconButtonShape::Square)
8958                .icon_size(IconSize::Small)
8959                // .disabled(!has_multiple_hunks)
8960                .tooltip({
8961                    let focus_handle = editor.focus_handle(cx);
8962                    move |window, cx| {
8963                        Tooltip::for_action_in("Next Hunk", &GoToHunk, &focus_handle, window, cx)
8964                    }
8965                })
8966                .on_click({
8967                    let editor = editor.clone();
8968                    move |_event, window, cx| {
8969                        editor.update(cx, |editor, cx| {
8970                            let snapshot = editor.snapshot(window, cx);
8971                            let position = hunk_range.end.to_point(&snapshot.buffer_snapshot);
8972                            editor.go_to_hunk_after_position(&snapshot, position, window, cx);
8973                            editor.expand_selected_diff_hunks(cx);
8974                        });
8975                    }
8976                }),
8977        )
8978        .child(
8979            IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
8980                .shape(IconButtonShape::Square)
8981                .icon_size(IconSize::Small)
8982                // .disabled(!has_multiple_hunks)
8983                .tooltip({
8984                    let focus_handle = editor.focus_handle(cx);
8985                    move |window, cx| {
8986                        Tooltip::for_action_in(
8987                            "Previous Hunk",
8988                            &GoToPrevHunk,
8989                            &focus_handle,
8990                            window,
8991                            cx,
8992                        )
8993                    }
8994                })
8995                .on_click({
8996                    let editor = editor.clone();
8997                    move |_event, window, cx| {
8998                        editor.update(cx, |editor, cx| {
8999                            let snapshot = editor.snapshot(window, cx);
9000                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
9001                            editor.go_to_hunk_before_position(&snapshot, point, window, cx);
9002                            editor.expand_selected_diff_hunks(cx);
9003                        });
9004                    }
9005                }),
9006        )
9007        .child(
9008            IconButton::new("discard", IconName::Undo)
9009                .shape(IconButtonShape::Square)
9010                .icon_size(IconSize::Small)
9011                .tooltip({
9012                    let focus_handle = editor.focus_handle(cx);
9013                    move |window, cx| {
9014                        Tooltip::for_action_in(
9015                            "Discard Hunk",
9016                            &RevertSelectedHunks,
9017                            &focus_handle,
9018                            window,
9019                            cx,
9020                        )
9021                    }
9022                })
9023                .on_click({
9024                    let editor = editor.clone();
9025                    move |_event, window, cx| {
9026                        editor.update(cx, |editor, cx| {
9027                            let snapshot = editor.snapshot(window, cx);
9028                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
9029                            editor.revert_hunks_in_ranges([point..point].into_iter(), window, cx);
9030                        });
9031                    }
9032                }),
9033        )
9034        .into_any_element()
9035}