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