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