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