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