element.rs

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