element.rs

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