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