element.rs

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