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