element.rs

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