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