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