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