element.rs

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