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        if !self.editor.read(cx).disable_scrolling {
5682            self.paint_scroll_wheel_listener(layout, window, cx);
5683        }
5684
5685        window.on_mouse_event({
5686            let position_map = layout.position_map.clone();
5687            let editor = self.editor.clone();
5688            let diff_hunk_range =
5689                layout
5690                    .display_hunks
5691                    .iter()
5692                    .find_map(|(hunk, hunk_hitbox)| match hunk {
5693                        DisplayDiffHunk::Folded { .. } => None,
5694                        DisplayDiffHunk::Unfolded {
5695                            multi_buffer_range, ..
5696                        } => {
5697                            if hunk_hitbox
5698                                .as_ref()
5699                                .map(|hitbox| hitbox.is_hovered(window))
5700                                .unwrap_or(false)
5701                            {
5702                                Some(multi_buffer_range.clone())
5703                            } else {
5704                                None
5705                            }
5706                        }
5707                    });
5708            let line_numbers = layout.line_numbers.clone();
5709
5710            move |event: &MouseDownEvent, phase, window, cx| {
5711                if phase == DispatchPhase::Bubble {
5712                    match event.button {
5713                        MouseButton::Left => editor.update(cx, |editor, cx| {
5714                            let pending_mouse_down = editor
5715                                .pending_mouse_down
5716                                .get_or_insert_with(Default::default)
5717                                .clone();
5718
5719                            *pending_mouse_down.borrow_mut() = Some(event.clone());
5720
5721                            Self::mouse_left_down(
5722                                editor,
5723                                event,
5724                                diff_hunk_range.clone(),
5725                                &position_map,
5726                                line_numbers.as_ref(),
5727                                window,
5728                                cx,
5729                            );
5730                        }),
5731                        MouseButton::Right => editor.update(cx, |editor, cx| {
5732                            Self::mouse_right_down(editor, event, &position_map, window, cx);
5733                        }),
5734                        MouseButton::Middle => editor.update(cx, |editor, cx| {
5735                            Self::mouse_middle_down(editor, event, &position_map, window, cx);
5736                        }),
5737                        _ => {}
5738                    };
5739                }
5740            }
5741        });
5742
5743        window.on_mouse_event({
5744            let editor = self.editor.clone();
5745            let position_map = layout.position_map.clone();
5746
5747            move |event: &MouseUpEvent, phase, window, cx| {
5748                if phase == DispatchPhase::Bubble {
5749                    editor.update(cx, |editor, cx| {
5750                        Self::mouse_up(editor, event, &position_map, window, cx)
5751                    });
5752                }
5753            }
5754        });
5755
5756        window.on_mouse_event({
5757            let editor = self.editor.clone();
5758            let position_map = layout.position_map.clone();
5759            let mut captured_mouse_down = None;
5760
5761            move |event: &MouseUpEvent, phase, window, cx| match phase {
5762                // Clear the pending mouse down during the capture phase,
5763                // so that it happens even if another event handler stops
5764                // propagation.
5765                DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
5766                    let pending_mouse_down = editor
5767                        .pending_mouse_down
5768                        .get_or_insert_with(Default::default)
5769                        .clone();
5770
5771                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
5772                    if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
5773                        captured_mouse_down = pending_mouse_down.take();
5774                        window.refresh();
5775                    }
5776                }),
5777                // Fire click handlers during the bubble phase.
5778                DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
5779                    if let Some(mouse_down) = captured_mouse_down.take() {
5780                        let event = ClickEvent {
5781                            down: mouse_down,
5782                            up: event.clone(),
5783                        };
5784                        Self::click(editor, &event, &position_map, window, cx);
5785                    }
5786                }),
5787            }
5788        });
5789
5790        window.on_mouse_event({
5791            let position_map = layout.position_map.clone();
5792            let editor = self.editor.clone();
5793
5794            move |event: &MouseMoveEvent, phase, window, cx| {
5795                if phase == DispatchPhase::Bubble {
5796                    editor.update(cx, |editor, cx| {
5797                        if editor.hover_state.focused(window, cx) {
5798                            return;
5799                        }
5800                        if event.pressed_button == Some(MouseButton::Left)
5801                            || event.pressed_button == Some(MouseButton::Middle)
5802                        {
5803                            Self::mouse_dragged(editor, event, &position_map, window, cx)
5804                        }
5805
5806                        Self::mouse_moved(editor, event, &position_map, window, cx)
5807                    });
5808                }
5809            }
5810        });
5811    }
5812
5813    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
5814        bounds.top_right().x - self.style.scrollbar_width
5815    }
5816
5817    fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
5818        let style = &self.style;
5819        let font_size = style.text.font_size.to_pixels(window.rem_size());
5820        let layout = window
5821            .text_system()
5822            .shape_line(
5823                SharedString::from(" ".repeat(column)),
5824                font_size,
5825                &[TextRun {
5826                    len: column,
5827                    font: style.text.font(),
5828                    color: Hsla::default(),
5829                    background_color: None,
5830                    underline: None,
5831                    strikethrough: None,
5832                }],
5833            )
5834            .unwrap();
5835
5836        layout.width
5837    }
5838
5839    fn max_line_number_width(
5840        &self,
5841        snapshot: &EditorSnapshot,
5842        window: &mut Window,
5843        cx: &mut App,
5844    ) -> Pixels {
5845        let digit_count = snapshot.widest_line_number().ilog10() + 1;
5846        self.column_pixels(digit_count as usize, window, cx)
5847    }
5848
5849    fn shape_line_number(
5850        &self,
5851        text: SharedString,
5852        color: Hsla,
5853        window: &mut Window,
5854    ) -> anyhow::Result<ShapedLine> {
5855        let run = TextRun {
5856            len: text.len(),
5857            font: self.style.text.font(),
5858            color,
5859            background_color: None,
5860            underline: None,
5861            strikethrough: None,
5862        };
5863        window.text_system().shape_line(
5864            text,
5865            self.style.text.font_size.to_pixels(window.rem_size()),
5866            &[run],
5867        )
5868    }
5869
5870    fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
5871        let unstaged = status.has_secondary_hunk();
5872        let unstaged_hollow = ProjectSettings::get_global(cx)
5873            .git
5874            .hunk_style
5875            .map_or(false, |style| {
5876                matches!(style, GitHunkStyleSetting::UnstagedHollow)
5877            });
5878
5879        unstaged == unstaged_hollow
5880    }
5881}
5882
5883fn header_jump_data(
5884    snapshot: &EditorSnapshot,
5885    block_row_start: DisplayRow,
5886    height: u32,
5887    for_excerpt: &ExcerptInfo,
5888) -> JumpData {
5889    let range = &for_excerpt.range;
5890    let buffer = &for_excerpt.buffer;
5891    let jump_anchor = range.primary.start;
5892
5893    let excerpt_start = range.context.start;
5894    let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
5895    let rows_from_excerpt_start = if jump_anchor == excerpt_start {
5896        0
5897    } else {
5898        let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
5899        jump_position.row.saturating_sub(excerpt_start_point.row)
5900    };
5901
5902    let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
5903        .saturating_sub(
5904            snapshot
5905                .scroll_anchor
5906                .scroll_position(&snapshot.display_snapshot)
5907                .y as u32,
5908        );
5909
5910    JumpData::MultiBufferPoint {
5911        excerpt_id: for_excerpt.id,
5912        anchor: jump_anchor,
5913        position: jump_position,
5914        line_offset_from_top,
5915    }
5916}
5917
5918pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
5919
5920impl AcceptEditPredictionBinding {
5921    pub fn keystroke(&self) -> Option<&Keystroke> {
5922        if let Some(binding) = self.0.as_ref() {
5923            match &binding.keystrokes() {
5924                [keystroke] => Some(keystroke),
5925                _ => None,
5926            }
5927        } else {
5928            None
5929        }
5930    }
5931}
5932
5933fn prepaint_gutter_button(
5934    button: IconButton,
5935    row: DisplayRow,
5936    line_height: Pixels,
5937    gutter_dimensions: &GutterDimensions,
5938    scroll_pixel_position: gpui::Point<Pixels>,
5939    gutter_hitbox: &Hitbox,
5940    display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
5941    window: &mut Window,
5942    cx: &mut App,
5943) -> AnyElement {
5944    let mut button = button.into_any_element();
5945
5946    let available_space = size(
5947        AvailableSpace::MinContent,
5948        AvailableSpace::Definite(line_height),
5949    );
5950    let indicator_size = button.layout_as_root(available_space, window, cx);
5951
5952    let blame_width = gutter_dimensions.git_blame_entries_width;
5953    let gutter_width = display_hunks
5954        .binary_search_by(|(hunk, _)| match hunk {
5955            DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
5956            DisplayDiffHunk::Unfolded {
5957                display_row_range, ..
5958            } => {
5959                if display_row_range.end <= row {
5960                    Ordering::Less
5961                } else if display_row_range.start > row {
5962                    Ordering::Greater
5963                } else {
5964                    Ordering::Equal
5965                }
5966            }
5967        })
5968        .ok()
5969        .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
5970    let left_offset = blame_width.max(gutter_width).unwrap_or_default();
5971
5972    let mut x = left_offset;
5973    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
5974        - indicator_size.width
5975        - left_offset;
5976    x += available_width / 2.;
5977
5978    let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
5979    y += (line_height - indicator_size.height) / 2.;
5980
5981    button.prepaint_as_root(
5982        gutter_hitbox.origin + point(x, y),
5983        available_space,
5984        window,
5985        cx,
5986    );
5987    button
5988}
5989
5990fn render_inline_blame_entry(
5991    blame_entry: BlameEntry,
5992    style: &EditorStyle,
5993    cx: &mut App,
5994) -> Option<AnyElement> {
5995    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
5996    renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
5997}
5998
5999fn render_blame_entry_popover(
6000    blame_entry: BlameEntry,
6001    scroll_handle: ScrollHandle,
6002    commit_message: Option<ParsedCommitMessage>,
6003    markdown: Entity<Markdown>,
6004    workspace: WeakEntity<Workspace>,
6005    blame: &Entity<GitBlame>,
6006    window: &mut Window,
6007    cx: &mut App,
6008) -> Option<AnyElement> {
6009    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
6010    let blame = blame.read(cx);
6011    let repository = blame.repository(cx)?.clone();
6012    renderer.render_blame_entry_popover(
6013        blame_entry,
6014        scroll_handle,
6015        commit_message,
6016        markdown,
6017        repository,
6018        workspace,
6019        window,
6020        cx,
6021    )
6022}
6023
6024fn render_blame_entry(
6025    ix: usize,
6026    blame: &Entity<GitBlame>,
6027    blame_entry: BlameEntry,
6028    style: &EditorStyle,
6029    last_used_color: &mut Option<(PlayerColor, Oid)>,
6030    editor: Entity<Editor>,
6031    workspace: Entity<Workspace>,
6032    renderer: Arc<dyn BlameRenderer>,
6033    cx: &mut App,
6034) -> Option<AnyElement> {
6035    let mut sha_color = cx
6036        .theme()
6037        .players()
6038        .color_for_participant(blame_entry.sha.into());
6039
6040    // If the last color we used is the same as the one we get for this line, but
6041    // the commit SHAs are different, then we try again to get a different color.
6042    match *last_used_color {
6043        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
6044            let index: u32 = blame_entry.sha.into();
6045            sha_color = cx.theme().players().color_for_participant(index + 1);
6046        }
6047        _ => {}
6048    };
6049    last_used_color.replace((sha_color, blame_entry.sha));
6050
6051    let blame = blame.read(cx);
6052    let details = blame.details_for_entry(&blame_entry);
6053    let repository = blame.repository(cx)?;
6054    renderer.render_blame_entry(
6055        &style.text,
6056        blame_entry,
6057        details,
6058        repository,
6059        workspace.downgrade(),
6060        editor,
6061        ix,
6062        sha_color.cursor,
6063        cx,
6064    )
6065}
6066
6067#[derive(Debug)]
6068pub(crate) struct LineWithInvisibles {
6069    fragments: SmallVec<[LineFragment; 1]>,
6070    invisibles: Vec<Invisible>,
6071    len: usize,
6072    pub(crate) width: Pixels,
6073    font_size: Pixels,
6074}
6075
6076#[allow(clippy::large_enum_variant)]
6077enum LineFragment {
6078    Text(ShapedLine),
6079    Element {
6080        id: FoldId,
6081        element: Option<AnyElement>,
6082        size: Size<Pixels>,
6083        len: usize,
6084    },
6085}
6086
6087impl fmt::Debug for LineFragment {
6088    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6089        match self {
6090            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
6091            LineFragment::Element { size, len, .. } => f
6092                .debug_struct("Element")
6093                .field("size", size)
6094                .field("len", len)
6095                .finish(),
6096        }
6097    }
6098}
6099
6100impl LineWithInvisibles {
6101    fn from_chunks<'a>(
6102        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
6103        editor_style: &EditorStyle,
6104        max_line_len: usize,
6105        max_line_count: usize,
6106        editor_mode: EditorMode,
6107        text_width: Pixels,
6108        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6109        window: &mut Window,
6110        cx: &mut App,
6111    ) -> Vec<Self> {
6112        let text_style = &editor_style.text;
6113        let mut layouts = Vec::with_capacity(max_line_count);
6114        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
6115        let mut line = String::new();
6116        let mut invisibles = Vec::new();
6117        let mut width = Pixels::ZERO;
6118        let mut len = 0;
6119        let mut styles = Vec::new();
6120        let mut non_whitespace_added = false;
6121        let mut row = 0;
6122        let mut line_exceeded_max_len = false;
6123        let font_size = text_style.font_size.to_pixels(window.rem_size());
6124
6125        let ellipsis = SharedString::from("");
6126
6127        for highlighted_chunk in chunks.chain([HighlightedChunk {
6128            text: "\n",
6129            style: None,
6130            is_tab: false,
6131            replacement: None,
6132        }]) {
6133            if let Some(replacement) = highlighted_chunk.replacement {
6134                if !line.is_empty() {
6135                    let shaped_line = window
6136                        .text_system()
6137                        .shape_line(line.clone().into(), font_size, &styles)
6138                        .unwrap();
6139                    width += shaped_line.width;
6140                    len += shaped_line.len;
6141                    fragments.push(LineFragment::Text(shaped_line));
6142                    line.clear();
6143                    styles.clear();
6144                }
6145
6146                match replacement {
6147                    ChunkReplacement::Renderer(renderer) => {
6148                        let available_width = if renderer.constrain_width {
6149                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
6150                                ellipsis.clone()
6151                            } else {
6152                                SharedString::from(Arc::from(highlighted_chunk.text))
6153                            };
6154                            let shaped_line = window
6155                                .text_system()
6156                                .shape_line(
6157                                    chunk,
6158                                    font_size,
6159                                    &[text_style.to_run(highlighted_chunk.text.len())],
6160                                )
6161                                .unwrap();
6162                            AvailableSpace::Definite(shaped_line.width)
6163                        } else {
6164                            AvailableSpace::MinContent
6165                        };
6166
6167                        let mut element = (renderer.render)(&mut ChunkRendererContext {
6168                            context: cx,
6169                            window,
6170                            max_width: text_width,
6171                        });
6172                        let line_height = text_style.line_height_in_pixels(window.rem_size());
6173                        let size = element.layout_as_root(
6174                            size(available_width, AvailableSpace::Definite(line_height)),
6175                            window,
6176                            cx,
6177                        );
6178
6179                        width += size.width;
6180                        len += highlighted_chunk.text.len();
6181                        fragments.push(LineFragment::Element {
6182                            id: renderer.id,
6183                            element: Some(element),
6184                            size,
6185                            len: highlighted_chunk.text.len(),
6186                        });
6187                    }
6188                    ChunkReplacement::Str(x) => {
6189                        let text_style = if let Some(style) = highlighted_chunk.style {
6190                            Cow::Owned(text_style.clone().highlight(style))
6191                        } else {
6192                            Cow::Borrowed(text_style)
6193                        };
6194
6195                        let run = TextRun {
6196                            len: x.len(),
6197                            font: text_style.font(),
6198                            color: text_style.color,
6199                            background_color: text_style.background_color,
6200                            underline: text_style.underline,
6201                            strikethrough: text_style.strikethrough,
6202                        };
6203                        let line_layout = window
6204                            .text_system()
6205                            .shape_line(x, font_size, &[run])
6206                            .unwrap()
6207                            .with_len(highlighted_chunk.text.len());
6208
6209                        width += line_layout.width;
6210                        len += highlighted_chunk.text.len();
6211                        fragments.push(LineFragment::Text(line_layout))
6212                    }
6213                }
6214            } else {
6215                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
6216                    if ix > 0 {
6217                        let shaped_line = window
6218                            .text_system()
6219                            .shape_line(line.clone().into(), font_size, &styles)
6220                            .unwrap();
6221                        width += shaped_line.width;
6222                        len += shaped_line.len;
6223                        fragments.push(LineFragment::Text(shaped_line));
6224                        layouts.push(Self {
6225                            width: mem::take(&mut width),
6226                            len: mem::take(&mut len),
6227                            fragments: mem::take(&mut fragments),
6228                            invisibles: std::mem::take(&mut invisibles),
6229                            font_size,
6230                        });
6231
6232                        line.clear();
6233                        styles.clear();
6234                        row += 1;
6235                        line_exceeded_max_len = false;
6236                        non_whitespace_added = false;
6237                        if row == max_line_count {
6238                            return layouts;
6239                        }
6240                    }
6241
6242                    if !line_chunk.is_empty() && !line_exceeded_max_len {
6243                        let text_style = if let Some(style) = highlighted_chunk.style {
6244                            Cow::Owned(text_style.clone().highlight(style))
6245                        } else {
6246                            Cow::Borrowed(text_style)
6247                        };
6248
6249                        if line.len() + line_chunk.len() > max_line_len {
6250                            let mut chunk_len = max_line_len - line.len();
6251                            while !line_chunk.is_char_boundary(chunk_len) {
6252                                chunk_len -= 1;
6253                            }
6254                            line_chunk = &line_chunk[..chunk_len];
6255                            line_exceeded_max_len = true;
6256                        }
6257
6258                        styles.push(TextRun {
6259                            len: line_chunk.len(),
6260                            font: text_style.font(),
6261                            color: text_style.color,
6262                            background_color: text_style.background_color,
6263                            underline: text_style.underline,
6264                            strikethrough: text_style.strikethrough,
6265                        });
6266
6267                        if editor_mode.is_full() {
6268                            // Line wrap pads its contents with fake whitespaces,
6269                            // avoid printing them
6270                            let is_soft_wrapped = is_row_soft_wrapped(row);
6271                            if highlighted_chunk.is_tab {
6272                                if non_whitespace_added || !is_soft_wrapped {
6273                                    invisibles.push(Invisible::Tab {
6274                                        line_start_offset: line.len(),
6275                                        line_end_offset: line.len() + line_chunk.len(),
6276                                    });
6277                                }
6278                            } else {
6279                                invisibles.extend(line_chunk.char_indices().filter_map(
6280                                    |(index, c)| {
6281                                        let is_whitespace = c.is_whitespace();
6282                                        non_whitespace_added |= !is_whitespace;
6283                                        if is_whitespace
6284                                            && (non_whitespace_added || !is_soft_wrapped)
6285                                        {
6286                                            Some(Invisible::Whitespace {
6287                                                line_offset: line.len() + index,
6288                                            })
6289                                        } else {
6290                                            None
6291                                        }
6292                                    },
6293                                ))
6294                            }
6295                        }
6296
6297                        line.push_str(line_chunk);
6298                    }
6299                }
6300            }
6301        }
6302
6303        layouts
6304    }
6305
6306    fn prepaint(
6307        &mut self,
6308        line_height: Pixels,
6309        scroll_pixel_position: gpui::Point<Pixels>,
6310        row: DisplayRow,
6311        content_origin: gpui::Point<Pixels>,
6312        line_elements: &mut SmallVec<[AnyElement; 1]>,
6313        window: &mut Window,
6314        cx: &mut App,
6315    ) {
6316        let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
6317        let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
6318        for fragment in &mut self.fragments {
6319            match fragment {
6320                LineFragment::Text(line) => {
6321                    fragment_origin.x += line.width;
6322                }
6323                LineFragment::Element { element, size, .. } => {
6324                    let mut element = element
6325                        .take()
6326                        .expect("you can't prepaint LineWithInvisibles twice");
6327
6328                    // Center the element vertically within the line.
6329                    let mut element_origin = fragment_origin;
6330                    element_origin.y += (line_height - size.height) / 2.;
6331                    element.prepaint_at(element_origin, window, cx);
6332                    line_elements.push(element);
6333
6334                    fragment_origin.x += size.width;
6335                }
6336            }
6337        }
6338    }
6339
6340    fn draw(
6341        &self,
6342        layout: &EditorLayout,
6343        row: DisplayRow,
6344        content_origin: gpui::Point<Pixels>,
6345        whitespace_setting: ShowWhitespaceSetting,
6346        selection_ranges: &[Range<DisplayPoint>],
6347        window: &mut Window,
6348        cx: &mut App,
6349    ) {
6350        let line_height = layout.position_map.line_height;
6351        let line_y = line_height
6352            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6353
6354        let mut fragment_origin =
6355            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6356
6357        for fragment in &self.fragments {
6358            match fragment {
6359                LineFragment::Text(line) => {
6360                    line.paint(fragment_origin, line_height, window, cx)
6361                        .log_err();
6362                    fragment_origin.x += line.width;
6363                }
6364                LineFragment::Element { size, .. } => {
6365                    fragment_origin.x += size.width;
6366                }
6367            }
6368        }
6369
6370        self.draw_invisibles(
6371            selection_ranges,
6372            layout,
6373            content_origin,
6374            line_y,
6375            row,
6376            line_height,
6377            whitespace_setting,
6378            window,
6379            cx,
6380        );
6381    }
6382
6383    fn draw_background(
6384        &self,
6385        layout: &EditorLayout,
6386        row: DisplayRow,
6387        content_origin: gpui::Point<Pixels>,
6388        window: &mut Window,
6389        cx: &mut App,
6390    ) {
6391        let line_height = layout.position_map.line_height;
6392        let line_y = line_height
6393            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6394
6395        let mut fragment_origin =
6396            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6397
6398        for fragment in &self.fragments {
6399            match fragment {
6400                LineFragment::Text(line) => {
6401                    line.paint_background(fragment_origin, line_height, window, cx)
6402                        .log_err();
6403                    fragment_origin.x += line.width;
6404                }
6405                LineFragment::Element { size, .. } => {
6406                    fragment_origin.x += size.width;
6407                }
6408            }
6409        }
6410    }
6411
6412    fn draw_invisibles(
6413        &self,
6414        selection_ranges: &[Range<DisplayPoint>],
6415        layout: &EditorLayout,
6416        content_origin: gpui::Point<Pixels>,
6417        line_y: Pixels,
6418        row: DisplayRow,
6419        line_height: Pixels,
6420        whitespace_setting: ShowWhitespaceSetting,
6421        window: &mut Window,
6422        cx: &mut App,
6423    ) {
6424        let extract_whitespace_info = |invisible: &Invisible| {
6425            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
6426                Invisible::Tab {
6427                    line_start_offset,
6428                    line_end_offset,
6429                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
6430                Invisible::Whitespace { line_offset } => {
6431                    (*line_offset, line_offset + 1, &layout.space_invisible)
6432                }
6433            };
6434
6435            let x_offset = self.x_for_index(token_offset);
6436            let invisible_offset =
6437                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
6438            let origin = content_origin
6439                + gpui::point(
6440                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
6441                    line_y,
6442                );
6443
6444            (
6445                [token_offset, token_end_offset],
6446                Box::new(move |window: &mut Window, cx: &mut App| {
6447                    invisible_symbol
6448                        .paint(origin, line_height, window, cx)
6449                        .log_err();
6450                }),
6451            )
6452        };
6453
6454        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
6455        match whitespace_setting {
6456            ShowWhitespaceSetting::None => (),
6457            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
6458            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
6459                let invisible_point = DisplayPoint::new(row, start as u32);
6460                if !selection_ranges
6461                    .iter()
6462                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
6463                {
6464                    return;
6465                }
6466
6467                paint(window, cx);
6468            }),
6469
6470            // For a whitespace to be on a boundary, any of the following conditions need to be met:
6471            // - It is a tab
6472            // - It is adjacent to an edge (start or end)
6473            // - It is adjacent to a whitespace (left or right)
6474            ShowWhitespaceSetting::Boundary => {
6475                // 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
6476                // the above cases.
6477                // Note: We zip in the original `invisibles` to check for tab equality
6478                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
6479                for (([start, end], paint), invisible) in
6480                    invisible_iter.zip_eq(self.invisibles.iter())
6481                {
6482                    let should_render = match (&last_seen, invisible) {
6483                        (_, Invisible::Tab { .. }) => true,
6484                        (Some((_, last_end, _)), _) => *last_end == start,
6485                        _ => false,
6486                    };
6487
6488                    if should_render || start == 0 || end == self.len {
6489                        paint(window, cx);
6490
6491                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
6492                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
6493                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
6494                            // Note that we need to make sure that the last one is actually adjacent
6495                            if !should_render_last && last_end == start {
6496                                paint_last(window, cx);
6497                            }
6498                        }
6499                    }
6500
6501                    // Manually render anything within a selection
6502                    let invisible_point = DisplayPoint::new(row, start as u32);
6503                    if selection_ranges.iter().any(|region| {
6504                        region.start <= invisible_point && invisible_point < region.end
6505                    }) {
6506                        paint(window, cx);
6507                    }
6508
6509                    last_seen = Some((should_render, end, paint));
6510                }
6511            }
6512        }
6513    }
6514
6515    pub fn x_for_index(&self, index: usize) -> Pixels {
6516        let mut fragment_start_x = Pixels::ZERO;
6517        let mut fragment_start_index = 0;
6518
6519        for fragment in &self.fragments {
6520            match fragment {
6521                LineFragment::Text(shaped_line) => {
6522                    let fragment_end_index = fragment_start_index + shaped_line.len;
6523                    if index < fragment_end_index {
6524                        return fragment_start_x
6525                            + shaped_line.x_for_index(index - fragment_start_index);
6526                    }
6527                    fragment_start_x += shaped_line.width;
6528                    fragment_start_index = fragment_end_index;
6529                }
6530                LineFragment::Element { len, size, .. } => {
6531                    let fragment_end_index = fragment_start_index + len;
6532                    if index < fragment_end_index {
6533                        return fragment_start_x;
6534                    }
6535                    fragment_start_x += size.width;
6536                    fragment_start_index = fragment_end_index;
6537                }
6538            }
6539        }
6540
6541        fragment_start_x
6542    }
6543
6544    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
6545        let mut fragment_start_x = Pixels::ZERO;
6546        let mut fragment_start_index = 0;
6547
6548        for fragment in &self.fragments {
6549            match fragment {
6550                LineFragment::Text(shaped_line) => {
6551                    let fragment_end_x = fragment_start_x + shaped_line.width;
6552                    if x < fragment_end_x {
6553                        return Some(
6554                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
6555                        );
6556                    }
6557                    fragment_start_x = fragment_end_x;
6558                    fragment_start_index += shaped_line.len;
6559                }
6560                LineFragment::Element { len, size, .. } => {
6561                    let fragment_end_x = fragment_start_x + size.width;
6562                    if x < fragment_end_x {
6563                        return Some(fragment_start_index);
6564                    }
6565                    fragment_start_index += len;
6566                    fragment_start_x = fragment_end_x;
6567                }
6568            }
6569        }
6570
6571        None
6572    }
6573
6574    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
6575        let mut fragment_start_index = 0;
6576
6577        for fragment in &self.fragments {
6578            match fragment {
6579                LineFragment::Text(shaped_line) => {
6580                    let fragment_end_index = fragment_start_index + shaped_line.len;
6581                    if index < fragment_end_index {
6582                        return shaped_line.font_id_for_index(index - fragment_start_index);
6583                    }
6584                    fragment_start_index = fragment_end_index;
6585                }
6586                LineFragment::Element { len, .. } => {
6587                    let fragment_end_index = fragment_start_index + len;
6588                    if index < fragment_end_index {
6589                        return None;
6590                    }
6591                    fragment_start_index = fragment_end_index;
6592                }
6593            }
6594        }
6595
6596        None
6597    }
6598}
6599
6600#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6601enum Invisible {
6602    /// A tab character
6603    ///
6604    /// A tab character is internally represented by spaces (configured by the user's tab width)
6605    /// aligned to the nearest column, so it's necessary to store the start and end offset for
6606    /// adjacency checks.
6607    Tab {
6608        line_start_offset: usize,
6609        line_end_offset: usize,
6610    },
6611    Whitespace {
6612        line_offset: usize,
6613    },
6614}
6615
6616impl EditorElement {
6617    /// Returns the rem size to use when rendering the [`EditorElement`].
6618    ///
6619    /// This allows UI elements to scale based on the `buffer_font_size`.
6620    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
6621        match self.editor.read(cx).mode {
6622            EditorMode::Full {
6623                scale_ui_elements_with_buffer_font_size,
6624                ..
6625            } => {
6626                if !scale_ui_elements_with_buffer_font_size {
6627                    return None;
6628                }
6629                let buffer_font_size = self.style.text.font_size;
6630                match buffer_font_size {
6631                    AbsoluteLength::Pixels(pixels) => {
6632                        let rem_size_scale = {
6633                            // Our default UI font size is 14px on a 16px base scale.
6634                            // This means the default UI font size is 0.875rems.
6635                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
6636
6637                            // We then determine the delta between a single rem and the default font
6638                            // size scale.
6639                            let default_font_size_delta = 1. - default_font_size_scale;
6640
6641                            // Finally, we add this delta to 1rem to get the scale factor that
6642                            // should be used to scale up the UI.
6643                            1. + default_font_size_delta
6644                        };
6645
6646                        Some(pixels * rem_size_scale)
6647                    }
6648                    AbsoluteLength::Rems(rems) => {
6649                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
6650                    }
6651                }
6652            }
6653            // We currently use single-line and auto-height editors in UI contexts,
6654            // so we don't want to scale everything with the buffer font size, as it
6655            // ends up looking off.
6656            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
6657        }
6658    }
6659}
6660
6661impl Element for EditorElement {
6662    type RequestLayoutState = ();
6663    type PrepaintState = EditorLayout;
6664
6665    fn id(&self) -> Option<ElementId> {
6666        None
6667    }
6668
6669    fn request_layout(
6670        &mut self,
6671        _: Option<&GlobalElementId>,
6672        window: &mut Window,
6673        cx: &mut App,
6674    ) -> (gpui::LayoutId, ()) {
6675        let rem_size = self.rem_size(cx);
6676        window.with_rem_size(rem_size, |window| {
6677            self.editor.update(cx, |editor, cx| {
6678                editor.set_style(self.style.clone(), window, cx);
6679
6680                let layout_id = match editor.mode {
6681                    EditorMode::SingleLine { auto_width } => {
6682                        let rem_size = window.rem_size();
6683
6684                        let height = self.style.text.line_height_in_pixels(rem_size);
6685                        if auto_width {
6686                            let editor_handle = cx.entity().clone();
6687                            let style = self.style.clone();
6688                            window.request_measured_layout(
6689                                Style::default(),
6690                                move |_, _, window, cx| {
6691                                    let editor_snapshot = editor_handle
6692                                        .update(cx, |editor, cx| editor.snapshot(window, cx));
6693                                    let line = Self::layout_lines(
6694                                        DisplayRow(0)..DisplayRow(1),
6695                                        &editor_snapshot,
6696                                        &style,
6697                                        px(f32::MAX),
6698                                        |_| false, // Single lines never soft wrap
6699                                        window,
6700                                        cx,
6701                                    )
6702                                    .pop()
6703                                    .unwrap();
6704
6705                                    let font_id =
6706                                        window.text_system().resolve_font(&style.text.font());
6707                                    let font_size =
6708                                        style.text.font_size.to_pixels(window.rem_size());
6709                                    let em_width =
6710                                        window.text_system().em_width(font_id, font_size).unwrap();
6711
6712                                    size(line.width + em_width, height)
6713                                },
6714                            )
6715                        } else {
6716                            let mut style = Style::default();
6717                            style.size.height = height.into();
6718                            style.size.width = relative(1.).into();
6719                            window.request_layout(style, None, cx)
6720                        }
6721                    }
6722                    EditorMode::AutoHeight { max_lines } => {
6723                        let editor_handle = cx.entity().clone();
6724                        let max_line_number_width =
6725                            self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
6726                        window.request_measured_layout(
6727                            Style::default(),
6728                            move |known_dimensions, available_space, window, cx| {
6729                                editor_handle
6730                                    .update(cx, |editor, cx| {
6731                                        compute_auto_height_layout(
6732                                            editor,
6733                                            max_lines,
6734                                            max_line_number_width,
6735                                            known_dimensions,
6736                                            available_space.width,
6737                                            window,
6738                                            cx,
6739                                        )
6740                                    })
6741                                    .unwrap_or_default()
6742                            },
6743                        )
6744                    }
6745                    EditorMode::Full {
6746                        sized_by_content, ..
6747                    } => {
6748                        let mut style = Style::default();
6749                        style.size.width = relative(1.).into();
6750                        if sized_by_content {
6751                            let snapshot = editor.snapshot(window, cx);
6752                            let line_height =
6753                                self.style.text.line_height_in_pixels(window.rem_size());
6754                            let scroll_height =
6755                                (snapshot.max_point().row().next_row().0 as f32) * line_height;
6756                            style.size.height = scroll_height.into();
6757                        } else {
6758                            style.size.height = relative(1.).into();
6759                        }
6760                        window.request_layout(style, None, cx)
6761                    }
6762                };
6763
6764                (layout_id, ())
6765            })
6766        })
6767    }
6768
6769    fn prepaint(
6770        &mut self,
6771        _: Option<&GlobalElementId>,
6772        bounds: Bounds<Pixels>,
6773        _: &mut Self::RequestLayoutState,
6774        window: &mut Window,
6775        cx: &mut App,
6776    ) -> Self::PrepaintState {
6777        let text_style = TextStyleRefinement {
6778            font_size: Some(self.style.text.font_size),
6779            line_height: Some(self.style.text.line_height),
6780            ..Default::default()
6781        };
6782        let focus_handle = self.editor.focus_handle(cx);
6783        window.set_view_id(self.editor.entity_id());
6784        window.set_focus_handle(&focus_handle, cx);
6785
6786        let rem_size = self.rem_size(cx);
6787        window.with_rem_size(rem_size, |window| {
6788            window.with_text_style(Some(text_style), |window| {
6789                window.with_content_mask(Some(ContentMask { bounds }), |window| {
6790                    let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
6791                        (editor.snapshot(window, cx), editor.read_only(cx))
6792                    });
6793                    let style = self.style.clone();
6794
6795                    let font_id = window.text_system().resolve_font(&style.text.font());
6796                    let font_size = style.text.font_size.to_pixels(window.rem_size());
6797                    let line_height = style.text.line_height_in_pixels(window.rem_size());
6798                    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
6799                    let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
6800
6801                    let glyph_grid_cell = size(em_width, line_height);
6802
6803                    let gutter_dimensions = snapshot
6804                        .gutter_dimensions(
6805                            font_id,
6806                            font_size,
6807                            self.max_line_number_width(&snapshot, window, cx),
6808                            cx,
6809                        )
6810                        .unwrap_or_default();
6811                    let text_width = bounds.size.width - gutter_dimensions.width;
6812
6813                    let editor_width =
6814                        text_width - gutter_dimensions.margin - em_width - style.scrollbar_width;
6815
6816                    snapshot = self.editor.update(cx, |editor, cx| {
6817                        editor.last_bounds = Some(bounds);
6818                        editor.gutter_dimensions = gutter_dimensions;
6819                        editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
6820
6821                        if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
6822                            snapshot
6823                        } else {
6824                            let wrap_width = match editor.soft_wrap_mode(cx) {
6825                                SoftWrap::GitDiff => None,
6826                                SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
6827                                SoftWrap::EditorWidth => Some(editor_width),
6828                                SoftWrap::Column(column) => Some(column as f32 * em_advance),
6829                                SoftWrap::Bounded(column) => {
6830                                    Some(editor_width.min(column as f32 * em_advance))
6831                                }
6832                            };
6833
6834                            if editor.set_wrap_width(wrap_width.map(|w| w.ceil()), cx) {
6835                                editor.snapshot(window, cx)
6836                            } else {
6837                                snapshot
6838                            }
6839                        }
6840                    });
6841
6842                    let wrap_guides = self
6843                        .editor
6844                        .read(cx)
6845                        .wrap_guides(cx)
6846                        .iter()
6847                        .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
6848                        .collect::<SmallVec<[_; 2]>>();
6849
6850                    let hitbox = window.insert_hitbox(bounds, false);
6851                    let gutter_hitbox =
6852                        window.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
6853                    let text_hitbox = window.insert_hitbox(
6854                        Bounds {
6855                            origin: gutter_hitbox.top_right(),
6856                            size: size(text_width, bounds.size.height),
6857                        },
6858                        false,
6859                    );
6860
6861                    // Offset the content_bounds from the text_bounds by the gutter margin (which
6862                    // is roughly half a character wide) to make hit testing work more like how we want.
6863                    let content_offset = point(gutter_dimensions.margin, Pixels::ZERO);
6864                    let content_origin = text_hitbox.origin + content_offset;
6865
6866                    let editor_text_bounds =
6867                        Bounds::from_corners(content_origin, bounds.bottom_right());
6868
6869                    let height_in_lines = editor_text_bounds.size.height / line_height;
6870
6871                    let max_row = snapshot.max_point().row().as_f32();
6872
6873                    // The max scroll position for the top of the window
6874                    let max_scroll_top = if matches!(
6875                        snapshot.mode,
6876                        EditorMode::AutoHeight { .. } | EditorMode::SingleLine { .. }
6877                    ) {
6878                        (max_row - height_in_lines + 1.).max(0.)
6879                    } else {
6880                        let settings = EditorSettings::get_global(cx);
6881                        match settings.scroll_beyond_last_line {
6882                            ScrollBeyondLastLine::OnePage => max_row,
6883                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
6884                            ScrollBeyondLastLine::VerticalScrollMargin => {
6885                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
6886                                    .max(0.)
6887                            }
6888                        }
6889                    };
6890
6891                    // TODO: Autoscrolling for both axes
6892                    let mut autoscroll_request = None;
6893                    let mut autoscroll_containing_element = false;
6894                    let mut autoscroll_horizontally = false;
6895                    self.editor.update(cx, |editor, cx| {
6896                        autoscroll_request = editor.autoscroll_request();
6897                        autoscroll_containing_element =
6898                            autoscroll_request.is_some() || editor.has_pending_selection();
6899                        // TODO: Is this horizontal or vertical?!
6900                        autoscroll_horizontally = editor.autoscroll_vertically(
6901                            bounds,
6902                            line_height,
6903                            max_scroll_top,
6904                            window,
6905                            cx,
6906                        );
6907                        snapshot = editor.snapshot(window, cx);
6908                    });
6909
6910                    let mut scroll_position = snapshot.scroll_position();
6911                    // The scroll position is a fractional point, the whole number of which represents
6912                    // the top of the window in terms of display rows.
6913                    let start_row = DisplayRow(scroll_position.y as u32);
6914                    let max_row = snapshot.max_point().row();
6915                    let end_row = cmp::min(
6916                        (scroll_position.y + height_in_lines).ceil() as u32,
6917                        max_row.next_row().0,
6918                    );
6919                    let end_row = DisplayRow(end_row);
6920
6921                    let row_infos = snapshot
6922                        .row_infos(start_row)
6923                        .take((start_row..end_row).len())
6924                        .collect::<Vec<RowInfo>>();
6925                    let is_row_soft_wrapped = |row: usize| {
6926                        row_infos
6927                            .get(row)
6928                            .map_or(true, |info| info.buffer_row.is_none())
6929                    };
6930
6931                    let start_anchor = if start_row == Default::default() {
6932                        Anchor::min()
6933                    } else {
6934                        snapshot.buffer_snapshot.anchor_before(
6935                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
6936                        )
6937                    };
6938                    let end_anchor = if end_row > max_row {
6939                        Anchor::max()
6940                    } else {
6941                        snapshot.buffer_snapshot.anchor_before(
6942                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
6943                        )
6944                    };
6945
6946                    let mut highlighted_rows = self
6947                        .editor
6948                        .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
6949
6950                    let is_light = cx.theme().appearance().is_light();
6951
6952                    for (ix, row_info) in row_infos.iter().enumerate() {
6953                        let Some(diff_status) = row_info.diff_status else {
6954                            continue;
6955                        };
6956
6957                        let background_color = match diff_status.kind {
6958                            DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
6959                            DiffHunkStatusKind::Deleted => {
6960                                cx.theme().colors().version_control_deleted
6961                            }
6962                            DiffHunkStatusKind::Modified => {
6963                                debug_panic!("modified diff status for row info");
6964                                continue;
6965                            }
6966                        };
6967
6968                        let hunk_opacity = if is_light { 0.16 } else { 0.12 };
6969
6970                        let hollow_highlight = LineHighlight {
6971                            background: (background_color.opacity(if is_light {
6972                                0.08
6973                            } else {
6974                                0.06
6975                            }))
6976                            .into(),
6977                            border: Some(if is_light {
6978                                background_color.opacity(0.48)
6979                            } else {
6980                                background_color.opacity(0.36)
6981                            }),
6982                            include_gutter: true,
6983                            type_id: None,
6984                        };
6985
6986                        let filled_highlight = LineHighlight {
6987                            background: solid_background(background_color.opacity(hunk_opacity)),
6988                            border: None,
6989                            include_gutter: true,
6990                            type_id: None,
6991                        };
6992
6993                        let background = if Self::diff_hunk_hollow(diff_status, cx) {
6994                            hollow_highlight
6995                        } else {
6996                            filled_highlight
6997                        };
6998
6999                        highlighted_rows
7000                            .entry(start_row + DisplayRow(ix as u32))
7001                            .or_insert(background);
7002                    }
7003
7004                    let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
7005                        start_anchor..end_anchor,
7006                        &snapshot.display_snapshot,
7007                        cx.theme().colors(),
7008                    );
7009                    let highlighted_gutter_ranges =
7010                        self.editor.read(cx).gutter_highlights_in_range(
7011                            start_anchor..end_anchor,
7012                            &snapshot.display_snapshot,
7013                            cx,
7014                        );
7015
7016                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
7017                        start_anchor..end_anchor,
7018                        &snapshot.display_snapshot,
7019                        cx,
7020                    );
7021
7022                    let (local_selections, selected_buffer_ids): (
7023                        Vec<Selection<Point>>,
7024                        Vec<BufferId>,
7025                    ) = self.editor.update(cx, |editor, cx| {
7026                        let all_selections = editor.selections.all::<Point>(cx);
7027                        let selected_buffer_ids = if editor.is_singleton(cx) {
7028                            Vec::new()
7029                        } else {
7030                            let mut selected_buffer_ids = Vec::with_capacity(all_selections.len());
7031
7032                            for selection in all_selections {
7033                                for buffer_id in snapshot
7034                                    .buffer_snapshot
7035                                    .buffer_ids_for_range(selection.range())
7036                                {
7037                                    if selected_buffer_ids.last() != Some(&buffer_id) {
7038                                        selected_buffer_ids.push(buffer_id);
7039                                    }
7040                                }
7041                            }
7042
7043                            selected_buffer_ids
7044                        };
7045
7046                        let mut selections = editor
7047                            .selections
7048                            .disjoint_in_range(start_anchor..end_anchor, cx);
7049                        selections.extend(editor.selections.pending(cx));
7050
7051                        (selections, selected_buffer_ids)
7052                    });
7053
7054                    let (selections, mut active_rows, newest_selection_head) = self
7055                        .layout_selections(
7056                            start_anchor,
7057                            end_anchor,
7058                            &local_selections,
7059                            &snapshot,
7060                            start_row,
7061                            end_row,
7062                            window,
7063                            cx,
7064                        );
7065                    let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
7066                        editor.active_breakpoints(start_row..end_row, window, cx)
7067                    });
7068                    if cx.has_flag::<DebuggerFeatureFlag>() {
7069                        for display_row in breakpoint_rows.keys() {
7070                            active_rows.entry(*display_row).or_default().breakpoint = true;
7071                        }
7072                    }
7073
7074                    let line_numbers = self.layout_line_numbers(
7075                        Some(&gutter_hitbox),
7076                        gutter_dimensions,
7077                        line_height,
7078                        scroll_position,
7079                        start_row..end_row,
7080                        &row_infos,
7081                        &active_rows,
7082                        newest_selection_head,
7083                        &snapshot,
7084                        window,
7085                        cx,
7086                    );
7087
7088                    // We add the gutter breakpoint indicator to breakpoint_rows after painting
7089                    // line numbers so we don't paint a line number debug accent color if a user
7090                    // has their mouse over that line when a breakpoint isn't there
7091                    if cx.has_flag::<DebuggerFeatureFlag>() {
7092                        self.editor.update(cx, |editor, _| {
7093                            if let Some(phantom_breakpoint) = &mut editor
7094                                .gutter_breakpoint_indicator
7095                                .0
7096                                .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
7097                            {
7098                                // Is there a non-phantom breakpoint on this line?
7099                                phantom_breakpoint.collides_with_existing_breakpoint = true;
7100                                breakpoint_rows
7101                                    .entry(phantom_breakpoint.display_row)
7102                                    .or_insert_with(|| {
7103                                        let position = snapshot.display_point_to_anchor(
7104                                            DisplayPoint::new(phantom_breakpoint.display_row, 0),
7105                                            Bias::Right,
7106                                        );
7107                                        let breakpoint = Breakpoint::new_standard();
7108                                        phantom_breakpoint.collides_with_existing_breakpoint =
7109                                            false;
7110                                        (position, breakpoint)
7111                                    });
7112                            }
7113                        })
7114                    }
7115
7116                    let mut expand_toggles =
7117                        window.with_element_namespace("expand_toggles", |window| {
7118                            self.layout_expand_toggles(
7119                                &gutter_hitbox,
7120                                gutter_dimensions,
7121                                em_width,
7122                                line_height,
7123                                scroll_position,
7124                                &row_infos,
7125                                window,
7126                                cx,
7127                            )
7128                        });
7129
7130                    let mut crease_toggles =
7131                        window.with_element_namespace("crease_toggles", |window| {
7132                            self.layout_crease_toggles(
7133                                start_row..end_row,
7134                                &row_infos,
7135                                &active_rows,
7136                                &snapshot,
7137                                window,
7138                                cx,
7139                            )
7140                        });
7141                    let crease_trailers =
7142                        window.with_element_namespace("crease_trailers", |window| {
7143                            self.layout_crease_trailers(
7144                                row_infos.iter().copied(),
7145                                &snapshot,
7146                                window,
7147                                cx,
7148                            )
7149                        });
7150
7151                    let display_hunks = self.layout_gutter_diff_hunks(
7152                        line_height,
7153                        &gutter_hitbox,
7154                        start_row..end_row,
7155                        &snapshot,
7156                        window,
7157                        cx,
7158                    );
7159
7160                    let mut line_layouts = Self::layout_lines(
7161                        start_row..end_row,
7162                        &snapshot,
7163                        &self.style,
7164                        editor_width,
7165                        is_row_soft_wrapped,
7166                        window,
7167                        cx,
7168                    );
7169                    let new_fold_widths = line_layouts
7170                        .iter()
7171                        .flat_map(|layout| &layout.fragments)
7172                        .filter_map(|fragment| {
7173                            if let LineFragment::Element { id, size, .. } = fragment {
7174                                Some((*id, size.width))
7175                            } else {
7176                                None
7177                            }
7178                        });
7179                    if self.editor.update(cx, |editor, cx| {
7180                        editor.update_fold_widths(new_fold_widths, cx)
7181                    }) {
7182                        // If the fold widths have changed, we need to prepaint
7183                        // the element again to account for any changes in
7184                        // wrapping.
7185                        return self.prepaint(None, bounds, &mut (), window, cx);
7186                    }
7187
7188                    let longest_line_blame_width = self
7189                        .editor
7190                        .update(cx, |editor, cx| {
7191                            if !editor.show_git_blame_inline {
7192                                return None;
7193                            }
7194                            let blame = editor.blame.as_ref()?;
7195                            let blame_entry = blame
7196                                .update(cx, |blame, cx| {
7197                                    let row_infos =
7198                                        snapshot.row_infos(snapshot.longest_row()).next()?;
7199                                    blame.blame_for_rows(&[row_infos], cx).next()
7200                                })
7201                                .flatten()?;
7202                            let mut element = render_inline_blame_entry(blame_entry, &style, cx)?;
7203                            let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
7204                            Some(
7205                                element
7206                                    .layout_as_root(AvailableSpace::min_size(), window, cx)
7207                                    .width
7208                                    + inline_blame_padding,
7209                            )
7210                        })
7211                        .unwrap_or(Pixels::ZERO);
7212
7213                    let longest_line_width = layout_line(
7214                        snapshot.longest_row(),
7215                        &snapshot,
7216                        &style,
7217                        editor_width,
7218                        is_row_soft_wrapped,
7219                        window,
7220                        cx,
7221                    )
7222                    .width;
7223
7224                    let scrollbar_layout_information = ScrollbarLayoutInformation::new(
7225                        text_hitbox.bounds,
7226                        glyph_grid_cell,
7227                        size(longest_line_width, max_row.as_f32() * line_height),
7228                        longest_line_blame_width,
7229                        style.scrollbar_width,
7230                        editor_width,
7231                        EditorSettings::get_global(cx),
7232                    );
7233
7234                    let mut scroll_width = scrollbar_layout_information.scroll_range.width;
7235
7236                    let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
7237                        snapshot.sticky_header_excerpt(scroll_position.y)
7238                    } else {
7239                        None
7240                    };
7241                    let sticky_header_excerpt_id =
7242                        sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
7243
7244                    let blocks = window.with_element_namespace("blocks", |window| {
7245                        self.render_blocks(
7246                            start_row..end_row,
7247                            &snapshot,
7248                            &hitbox,
7249                            &text_hitbox,
7250                            editor_width,
7251                            &mut scroll_width,
7252                            &gutter_dimensions,
7253                            em_width,
7254                            gutter_dimensions.full_width(),
7255                            line_height,
7256                            &mut line_layouts,
7257                            &local_selections,
7258                            &selected_buffer_ids,
7259                            is_row_soft_wrapped,
7260                            sticky_header_excerpt_id,
7261                            window,
7262                            cx,
7263                        )
7264                    });
7265                    let (mut blocks, row_block_types) = match blocks {
7266                        Ok(blocks) => blocks,
7267                        Err(resized_blocks) => {
7268                            self.editor.update(cx, |editor, cx| {
7269                                editor.resize_blocks(resized_blocks, autoscroll_request, cx)
7270                            });
7271                            return self.prepaint(None, bounds, &mut (), window, cx);
7272                        }
7273                    };
7274
7275                    let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
7276                        window.with_element_namespace("blocks", |window| {
7277                            self.layout_sticky_buffer_header(
7278                                sticky_header_excerpt,
7279                                scroll_position.y,
7280                                line_height,
7281                                &snapshot,
7282                                &hitbox,
7283                                &selected_buffer_ids,
7284                                &blocks,
7285                                window,
7286                                cx,
7287                            )
7288                        })
7289                    });
7290
7291                    let start_buffer_row =
7292                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
7293                    let end_buffer_row =
7294                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
7295
7296                    let scroll_max = point(
7297                        ((scroll_width - editor_text_bounds.size.width) / em_width).max(0.0),
7298                        max_scroll_top,
7299                    );
7300
7301                    self.editor.update(cx, |editor, cx| {
7302                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7303
7304                        let autoscrolled = if autoscroll_horizontally {
7305                            editor.autoscroll_horizontally(
7306                                start_row,
7307                                editor_width - (glyph_grid_cell.width / 2.0)
7308                                    + style.scrollbar_width,
7309                                scroll_width,
7310                                em_width,
7311                                &line_layouts,
7312                                cx,
7313                            )
7314                        } else {
7315                            false
7316                        };
7317
7318                        if clamped || autoscrolled {
7319                            snapshot = editor.snapshot(window, cx);
7320                            scroll_position = snapshot.scroll_position();
7321                        }
7322                    });
7323
7324                    let scroll_pixel_position = point(
7325                        scroll_position.x * em_width,
7326                        scroll_position.y * line_height,
7327                    );
7328
7329                    let indent_guides = self.layout_indent_guides(
7330                        content_origin,
7331                        text_hitbox.origin,
7332                        start_buffer_row..end_buffer_row,
7333                        scroll_pixel_position,
7334                        line_height,
7335                        &snapshot,
7336                        window,
7337                        cx,
7338                    );
7339
7340                    let crease_trailers =
7341                        window.with_element_namespace("crease_trailers", |window| {
7342                            self.prepaint_crease_trailers(
7343                                crease_trailers,
7344                                &line_layouts,
7345                                line_height,
7346                                content_origin,
7347                                scroll_pixel_position,
7348                                em_width,
7349                                window,
7350                                cx,
7351                            )
7352                        });
7353
7354                    let (inline_completion_popover, inline_completion_popover_origin) = self
7355                        .editor
7356                        .update(cx, |editor, cx| {
7357                            editor.render_edit_prediction_popover(
7358                                &text_hitbox.bounds,
7359                                content_origin,
7360                                &snapshot,
7361                                start_row..end_row,
7362                                scroll_position.y,
7363                                scroll_position.y + height_in_lines,
7364                                &line_layouts,
7365                                line_height,
7366                                scroll_pixel_position,
7367                                newest_selection_head,
7368                                editor_width,
7369                                &style,
7370                                window,
7371                                cx,
7372                            )
7373                        })
7374                        .unzip();
7375
7376                    let mut inline_diagnostics = self.layout_inline_diagnostics(
7377                        &line_layouts,
7378                        &crease_trailers,
7379                        &row_block_types,
7380                        content_origin,
7381                        scroll_pixel_position,
7382                        inline_completion_popover_origin,
7383                        start_row,
7384                        end_row,
7385                        line_height,
7386                        em_width,
7387                        &style,
7388                        window,
7389                        cx,
7390                    );
7391
7392                    let mut inline_blame = None;
7393                    if let Some(newest_selection_head) = newest_selection_head {
7394                        let display_row = newest_selection_head.row();
7395                        if (start_row..end_row).contains(&display_row)
7396                            && !row_block_types.contains_key(&display_row)
7397                        {
7398                            let line_ix = display_row.minus(start_row) as usize;
7399                            let row_info = &row_infos[line_ix];
7400                            let line_layout = &line_layouts[line_ix];
7401                            let crease_trailer_layout = crease_trailers[line_ix].as_ref();
7402                            inline_blame = self.layout_inline_blame(
7403                                display_row,
7404                                row_info,
7405                                line_layout,
7406                                crease_trailer_layout,
7407                                em_width,
7408                                content_origin,
7409                                scroll_pixel_position,
7410                                line_height,
7411                                &text_hitbox,
7412                                window,
7413                                cx,
7414                            );
7415                            if inline_blame.is_some() {
7416                                // Blame overrides inline diagnostics
7417                                inline_diagnostics.remove(&display_row);
7418                            }
7419                        }
7420                    }
7421
7422                    let blamed_display_rows = self.layout_blame_entries(
7423                        &row_infos,
7424                        em_width,
7425                        scroll_position,
7426                        line_height,
7427                        &gutter_hitbox,
7428                        gutter_dimensions.git_blame_entries_width,
7429                        window,
7430                        cx,
7431                    );
7432
7433                    self.editor.update(cx, |editor, cx| {
7434                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7435
7436                        let autoscrolled = if autoscroll_horizontally {
7437                            editor.autoscroll_horizontally(
7438                                start_row,
7439                                editor_width - (glyph_grid_cell.width / 2.0)
7440                                    + style.scrollbar_width,
7441                                scroll_width,
7442                                em_width,
7443                                &line_layouts,
7444                                cx,
7445                            )
7446                        } else {
7447                            false
7448                        };
7449
7450                        if clamped || autoscrolled {
7451                            snapshot = editor.snapshot(window, cx);
7452                            scroll_position = snapshot.scroll_position();
7453                        }
7454                    });
7455
7456                    let line_elements = self.prepaint_lines(
7457                        start_row,
7458                        &mut line_layouts,
7459                        line_height,
7460                        scroll_pixel_position,
7461                        content_origin,
7462                        window,
7463                        cx,
7464                    );
7465
7466                    window.with_element_namespace("blocks", |window| {
7467                        self.layout_blocks(
7468                            &mut blocks,
7469                            &hitbox,
7470                            line_height,
7471                            scroll_pixel_position,
7472                            window,
7473                            cx,
7474                        );
7475                    });
7476
7477                    let cursors = self.collect_cursors(&snapshot, cx);
7478                    let visible_row_range = start_row..end_row;
7479                    let non_visible_cursors = cursors
7480                        .iter()
7481                        .any(|c| !visible_row_range.contains(&c.0.row()));
7482
7483                    let visible_cursors = self.layout_visible_cursors(
7484                        &snapshot,
7485                        &selections,
7486                        &row_block_types,
7487                        start_row..end_row,
7488                        &line_layouts,
7489                        &text_hitbox,
7490                        content_origin,
7491                        scroll_position,
7492                        scroll_pixel_position,
7493                        line_height,
7494                        em_width,
7495                        em_advance,
7496                        autoscroll_containing_element,
7497                        window,
7498                        cx,
7499                    );
7500
7501                    let scrollbars_layout = self.layout_scrollbars(
7502                        &snapshot,
7503                        scrollbar_layout_information,
7504                        content_offset,
7505                        scroll_position,
7506                        non_visible_cursors,
7507                        window,
7508                        cx,
7509                    );
7510
7511                    let gutter_settings = EditorSettings::get_global(cx).gutter;
7512
7513                    let mut code_actions_indicator = None;
7514                    if let Some(newest_selection_head) = newest_selection_head {
7515                        let newest_selection_point =
7516                            newest_selection_head.to_point(&snapshot.display_snapshot);
7517
7518                        if (start_row..end_row).contains(&newest_selection_head.row()) {
7519                            self.layout_cursor_popovers(
7520                                line_height,
7521                                &text_hitbox,
7522                                content_origin,
7523                                start_row,
7524                                scroll_pixel_position,
7525                                &line_layouts,
7526                                newest_selection_head,
7527                                newest_selection_point,
7528                                &style,
7529                                window,
7530                                cx,
7531                            );
7532
7533                            let show_code_actions = snapshot
7534                                .show_code_actions
7535                                .unwrap_or(gutter_settings.code_actions);
7536                            if show_code_actions {
7537                                let newest_selection_point =
7538                                    newest_selection_head.to_point(&snapshot.display_snapshot);
7539                                if !snapshot
7540                                    .is_line_folded(MultiBufferRow(newest_selection_point.row))
7541                                {
7542                                    let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
7543                                        MultiBufferRow(newest_selection_point.row),
7544                                    );
7545                                    if let Some((buffer, range)) = buffer {
7546                                        let buffer_id = buffer.remote_id();
7547                                        let row = range.start.row;
7548                                        let has_test_indicator = self
7549                                            .editor
7550                                            .read(cx)
7551                                            .tasks
7552                                            .contains_key(&(buffer_id, row));
7553
7554                                        let has_expand_indicator = row_infos
7555                                            .get(
7556                                                (newest_selection_head.row() - start_row).0
7557                                                    as usize,
7558                                            )
7559                                            .is_some_and(|row_info| row_info.expand_info.is_some());
7560
7561                                        if !has_test_indicator && !has_expand_indicator {
7562                                            code_actions_indicator = self
7563                                                .layout_code_actions_indicator(
7564                                                    line_height,
7565                                                    newest_selection_head,
7566                                                    scroll_pixel_position,
7567                                                    &gutter_dimensions,
7568                                                    &gutter_hitbox,
7569                                                    &mut breakpoint_rows,
7570                                                    &display_hunks,
7571                                                    window,
7572                                                    cx,
7573                                                );
7574                                        }
7575                                    }
7576                                }
7577                            }
7578                        }
7579                    }
7580
7581                    self.layout_gutter_menu(
7582                        line_height,
7583                        &text_hitbox,
7584                        content_origin,
7585                        scroll_pixel_position,
7586                        gutter_dimensions.width - gutter_dimensions.left_padding,
7587                        window,
7588                        cx,
7589                    );
7590
7591                    let test_indicators = if gutter_settings.runnables {
7592                        self.layout_run_indicators(
7593                            line_height,
7594                            start_row..end_row,
7595                            &row_infos,
7596                            scroll_pixel_position,
7597                            &gutter_dimensions,
7598                            &gutter_hitbox,
7599                            &display_hunks,
7600                            &snapshot,
7601                            &mut breakpoint_rows,
7602                            window,
7603                            cx,
7604                        )
7605                    } else {
7606                        Vec::new()
7607                    };
7608
7609                    let show_breakpoints = snapshot
7610                        .show_breakpoints
7611                        .unwrap_or(gutter_settings.breakpoints);
7612                    let breakpoints = if cx.has_flag::<DebuggerFeatureFlag>() && show_breakpoints {
7613                        self.layout_breakpoints(
7614                            line_height,
7615                            start_row..end_row,
7616                            scroll_pixel_position,
7617                            &gutter_dimensions,
7618                            &gutter_hitbox,
7619                            &display_hunks,
7620                            &snapshot,
7621                            breakpoint_rows,
7622                            &row_infos,
7623                            window,
7624                            cx,
7625                        )
7626                    } else {
7627                        vec![]
7628                    };
7629
7630                    self.layout_signature_help(
7631                        &hitbox,
7632                        &text_hitbox,
7633                        content_origin,
7634                        scroll_pixel_position,
7635                        newest_selection_head,
7636                        start_row,
7637                        &line_layouts,
7638                        line_height,
7639                        em_width,
7640                        window,
7641                        cx,
7642                    );
7643
7644                    if !cx.has_active_drag() {
7645                        self.layout_hover_popovers(
7646                            &snapshot,
7647                            &hitbox,
7648                            &text_hitbox,
7649                            start_row..end_row,
7650                            content_origin,
7651                            scroll_pixel_position,
7652                            &line_layouts,
7653                            line_height,
7654                            em_width,
7655                            window,
7656                            cx,
7657                        );
7658                    }
7659
7660                    let mouse_context_menu = self.layout_mouse_context_menu(
7661                        &snapshot,
7662                        start_row..end_row,
7663                        content_origin,
7664                        window,
7665                        cx,
7666                    );
7667
7668                    window.with_element_namespace("crease_toggles", |window| {
7669                        self.prepaint_crease_toggles(
7670                            &mut crease_toggles,
7671                            line_height,
7672                            &gutter_dimensions,
7673                            gutter_settings,
7674                            scroll_pixel_position,
7675                            &gutter_hitbox,
7676                            window,
7677                            cx,
7678                        )
7679                    });
7680
7681                    window.with_element_namespace("expand_toggles", |window| {
7682                        self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
7683                    });
7684
7685                    let invisible_symbol_font_size = font_size / 2.;
7686                    let tab_invisible = window
7687                        .text_system()
7688                        .shape_line(
7689                            "".into(),
7690                            invisible_symbol_font_size,
7691                            &[TextRun {
7692                                len: "".len(),
7693                                font: self.style.text.font(),
7694                                color: cx.theme().colors().editor_invisible,
7695                                background_color: None,
7696                                underline: None,
7697                                strikethrough: None,
7698                            }],
7699                        )
7700                        .unwrap();
7701                    let space_invisible = window
7702                        .text_system()
7703                        .shape_line(
7704                            "".into(),
7705                            invisible_symbol_font_size,
7706                            &[TextRun {
7707                                len: "".len(),
7708                                font: self.style.text.font(),
7709                                color: cx.theme().colors().editor_invisible,
7710                                background_color: None,
7711                                underline: None,
7712                                strikethrough: None,
7713                            }],
7714                        )
7715                        .unwrap();
7716
7717                    let mode = snapshot.mode;
7718
7719                    let position_map = Rc::new(PositionMap {
7720                        size: bounds.size,
7721                        visible_row_range,
7722                        scroll_pixel_position,
7723                        scroll_max,
7724                        line_layouts,
7725                        line_height,
7726                        em_width,
7727                        em_advance,
7728                        snapshot,
7729                        gutter_hitbox: gutter_hitbox.clone(),
7730                        text_hitbox: text_hitbox.clone(),
7731                    });
7732
7733                    self.editor.update(cx, |editor, _| {
7734                        editor.last_position_map = Some(position_map.clone())
7735                    });
7736
7737                    let diff_hunk_controls = if is_read_only {
7738                        vec![]
7739                    } else {
7740                        self.layout_diff_hunk_controls(
7741                            start_row..end_row,
7742                            &row_infos,
7743                            &text_hitbox,
7744                            &position_map,
7745                            newest_selection_head,
7746                            line_height,
7747                            scroll_pixel_position,
7748                            &display_hunks,
7749                            &highlighted_rows,
7750                            self.editor.clone(),
7751                            window,
7752                            cx,
7753                        )
7754                    };
7755
7756                    EditorLayout {
7757                        mode,
7758                        position_map,
7759                        visible_display_row_range: start_row..end_row,
7760                        wrap_guides,
7761                        indent_guides,
7762                        hitbox,
7763                        gutter_hitbox,
7764                        display_hunks,
7765                        content_origin,
7766                        scrollbars_layout,
7767                        active_rows,
7768                        highlighted_rows,
7769                        highlighted_ranges,
7770                        highlighted_gutter_ranges,
7771                        redacted_ranges,
7772                        line_elements,
7773                        line_numbers,
7774                        blamed_display_rows,
7775                        inline_diagnostics,
7776                        inline_blame,
7777                        blocks,
7778                        cursors,
7779                        visible_cursors,
7780                        selections,
7781                        inline_completion_popover,
7782                        diff_hunk_controls,
7783                        mouse_context_menu,
7784                        test_indicators,
7785                        breakpoints,
7786                        code_actions_indicator,
7787                        crease_toggles,
7788                        crease_trailers,
7789                        tab_invisible,
7790                        space_invisible,
7791                        sticky_buffer_header,
7792                        expand_toggles,
7793                    }
7794                })
7795            })
7796        })
7797    }
7798
7799    fn paint(
7800        &mut self,
7801        _: Option<&GlobalElementId>,
7802        bounds: Bounds<gpui::Pixels>,
7803        _: &mut Self::RequestLayoutState,
7804        layout: &mut Self::PrepaintState,
7805        window: &mut Window,
7806        cx: &mut App,
7807    ) {
7808        let focus_handle = self.editor.focus_handle(cx);
7809        let key_context = self
7810            .editor
7811            .update(cx, |editor, cx| editor.key_context(window, cx));
7812
7813        window.set_key_context(key_context);
7814        window.handle_input(
7815            &focus_handle,
7816            ElementInputHandler::new(bounds, self.editor.clone()),
7817            cx,
7818        );
7819        self.register_actions(window, cx);
7820        self.register_key_listeners(window, cx, layout);
7821
7822        let text_style = TextStyleRefinement {
7823            font_size: Some(self.style.text.font_size),
7824            line_height: Some(self.style.text.line_height),
7825            ..Default::default()
7826        };
7827        let rem_size = self.rem_size(cx);
7828        window.with_rem_size(rem_size, |window| {
7829            window.with_text_style(Some(text_style), |window| {
7830                window.with_content_mask(Some(ContentMask { bounds }), |window| {
7831                    self.paint_mouse_listeners(layout, window, cx);
7832                    self.paint_background(layout, window, cx);
7833                    self.paint_indent_guides(layout, window, cx);
7834
7835                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
7836                        self.paint_blamed_display_rows(layout, window, cx);
7837                        self.paint_line_numbers(layout, window, cx);
7838                    }
7839
7840                    self.paint_text(layout, window, cx);
7841
7842                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
7843                        self.paint_gutter_highlights(layout, window, cx);
7844                        self.paint_gutter_indicators(layout, window, cx);
7845                    }
7846
7847                    if !layout.blocks.is_empty() {
7848                        window.with_element_namespace("blocks", |window| {
7849                            self.paint_blocks(layout, window, cx);
7850                        });
7851                    }
7852
7853                    window.with_element_namespace("blocks", |window| {
7854                        if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
7855                            sticky_header.paint(window, cx)
7856                        }
7857                    });
7858
7859                    self.paint_scrollbars(layout, window, cx);
7860                    self.paint_inline_completion_popover(layout, window, cx);
7861                    self.paint_mouse_context_menu(layout, window, cx);
7862                });
7863            })
7864        })
7865    }
7866}
7867
7868pub(super) fn gutter_bounds(
7869    editor_bounds: Bounds<Pixels>,
7870    gutter_dimensions: GutterDimensions,
7871) -> Bounds<Pixels> {
7872    Bounds {
7873        origin: editor_bounds.origin,
7874        size: size(gutter_dimensions.width, editor_bounds.size.height),
7875    }
7876}
7877
7878/// Holds information required for layouting the editor scrollbars.
7879struct ScrollbarLayoutInformation {
7880    /// The bounds of the editor area (excluding the content offset).
7881    editor_bounds: Bounds<Pixels>,
7882    /// The available range to scroll within the document.
7883    scroll_range: Size<Pixels>,
7884    /// The space available for one glyph in the editor.
7885    glyph_grid_cell: Size<Pixels>,
7886}
7887
7888impl ScrollbarLayoutInformation {
7889    pub fn new(
7890        editor_bounds: Bounds<Pixels>,
7891        glyph_grid_cell: Size<Pixels>,
7892        document_size: Size<Pixels>,
7893        longest_line_blame_width: Pixels,
7894        scrollbar_width: Pixels,
7895        editor_width: Pixels,
7896        settings: &EditorSettings,
7897    ) -> Self {
7898        let vertical_overscroll = match settings.scroll_beyond_last_line {
7899            ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
7900            ScrollBeyondLastLine::Off => glyph_grid_cell.height,
7901            ScrollBeyondLastLine::VerticalScrollMargin => {
7902                (1.0 + settings.vertical_scroll_margin) * glyph_grid_cell.height
7903            }
7904        };
7905
7906        let right_margin = if document_size.width + longest_line_blame_width >= editor_width {
7907            glyph_grid_cell.width + scrollbar_width
7908        } else {
7909            px(0.0)
7910        };
7911
7912        let overscroll = size(right_margin + longest_line_blame_width, vertical_overscroll);
7913
7914        let scroll_range = document_size + overscroll;
7915
7916        ScrollbarLayoutInformation {
7917            editor_bounds,
7918            scroll_range,
7919            glyph_grid_cell,
7920        }
7921    }
7922}
7923
7924impl IntoElement for EditorElement {
7925    type Element = Self;
7926
7927    fn into_element(self) -> Self::Element {
7928        self
7929    }
7930}
7931
7932pub struct EditorLayout {
7933    position_map: Rc<PositionMap>,
7934    hitbox: Hitbox,
7935    gutter_hitbox: Hitbox,
7936    content_origin: gpui::Point<Pixels>,
7937    scrollbars_layout: Option<EditorScrollbars>,
7938    mode: EditorMode,
7939    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
7940    indent_guides: Option<Vec<IndentGuideLayout>>,
7941    visible_display_row_range: Range<DisplayRow>,
7942    active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
7943    highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
7944    line_elements: SmallVec<[AnyElement; 1]>,
7945    line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
7946    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
7947    blamed_display_rows: Option<Vec<AnyElement>>,
7948    inline_diagnostics: HashMap<DisplayRow, AnyElement>,
7949    inline_blame: Option<AnyElement>,
7950    blocks: Vec<BlockLayout>,
7951    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7952    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7953    redacted_ranges: Vec<Range<DisplayPoint>>,
7954    cursors: Vec<(DisplayPoint, Hsla)>,
7955    visible_cursors: Vec<CursorLayout>,
7956    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
7957    code_actions_indicator: Option<AnyElement>,
7958    test_indicators: Vec<AnyElement>,
7959    breakpoints: Vec<AnyElement>,
7960    crease_toggles: Vec<Option<AnyElement>>,
7961    expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
7962    diff_hunk_controls: Vec<AnyElement>,
7963    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
7964    inline_completion_popover: Option<AnyElement>,
7965    mouse_context_menu: Option<AnyElement>,
7966    tab_invisible: ShapedLine,
7967    space_invisible: ShapedLine,
7968    sticky_buffer_header: Option<AnyElement>,
7969}
7970
7971impl EditorLayout {
7972    fn line_end_overshoot(&self) -> Pixels {
7973        0.15 * self.position_map.line_height
7974    }
7975}
7976
7977struct LineNumberLayout {
7978    shaped_line: ShapedLine,
7979    hitbox: Option<Hitbox>,
7980}
7981
7982struct ColoredRange<T> {
7983    start: T,
7984    end: T,
7985    color: Hsla,
7986}
7987
7988impl Along for ScrollbarAxes {
7989    type Unit = bool;
7990
7991    fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
7992        match axis {
7993            ScrollbarAxis::Horizontal => self.horizontal,
7994            ScrollbarAxis::Vertical => self.vertical,
7995        }
7996    }
7997
7998    fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
7999        match axis {
8000            ScrollbarAxis::Horizontal => ScrollbarAxes {
8001                horizontal: f(self.horizontal),
8002                vertical: self.vertical,
8003            },
8004            ScrollbarAxis::Vertical => ScrollbarAxes {
8005                horizontal: self.horizontal,
8006                vertical: f(self.vertical),
8007            },
8008        }
8009    }
8010}
8011
8012#[derive(Clone)]
8013struct EditorScrollbars {
8014    pub vertical: Option<ScrollbarLayout>,
8015    pub horizontal: Option<ScrollbarLayout>,
8016    pub visible: bool,
8017}
8018
8019impl EditorScrollbars {
8020    pub fn from_scrollbar_axes(
8021        settings_visibility: ScrollbarAxes,
8022        layout_information: &ScrollbarLayoutInformation,
8023        content_offset: gpui::Point<Pixels>,
8024        scroll_position: gpui::Point<f32>,
8025        scrollbar_width: Pixels,
8026        show_scrollbars: bool,
8027        window: &mut Window,
8028    ) -> Self {
8029        let ScrollbarLayoutInformation {
8030            editor_bounds,
8031            scroll_range,
8032            glyph_grid_cell,
8033        } = layout_information;
8034
8035        let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
8036            ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
8037                Corner::BottomLeft,
8038                editor_bounds.bottom_left(),
8039                size(
8040                    if settings_visibility.vertical {
8041                        editor_bounds.size.width - scrollbar_width
8042                    } else {
8043                        editor_bounds.size.width
8044                    },
8045                    scrollbar_width,
8046                ),
8047            ),
8048            ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
8049                Corner::TopRight,
8050                editor_bounds.top_right(),
8051                size(scrollbar_width, editor_bounds.size.height),
8052            ),
8053        };
8054
8055        let mut create_scrollbar_layout = |axis| {
8056            settings_visibility
8057                .along(axis)
8058                .then(|| {
8059                    (
8060                        editor_bounds.size.along(axis) - content_offset.along(axis),
8061                        scroll_range.along(axis),
8062                    )
8063                })
8064                .filter(|(editor_content_size, scroll_range)| {
8065                    // The scrollbar should only be rendered if the content does
8066                    // not entirely fit into the editor
8067                    // However, this only applies to the horizontal scrollbar, as information about the
8068                    // vertical scrollbar layout is always needed for scrollbar diagnostics.
8069                    axis != ScrollbarAxis::Horizontal || editor_content_size < scroll_range
8070                })
8071                .map(|(editor_content_size, scroll_range)| {
8072                    ScrollbarLayout::new(
8073                        window.insert_hitbox(scrollbar_bounds_for(axis), false),
8074                        editor_content_size,
8075                        scroll_range,
8076                        glyph_grid_cell.along(axis),
8077                        content_offset.along(axis),
8078                        scroll_position.along(axis),
8079                        axis,
8080                    )
8081                })
8082        };
8083
8084        Self {
8085            vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
8086            horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
8087            visible: show_scrollbars,
8088        }
8089    }
8090
8091    pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
8092        [
8093            (&self.vertical, ScrollbarAxis::Vertical),
8094            (&self.horizontal, ScrollbarAxis::Horizontal),
8095        ]
8096        .into_iter()
8097        .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
8098    }
8099
8100    /// Returns the currently hovered scrollbar axis, if any.
8101    pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
8102        self.iter_scrollbars()
8103            .find(|s| s.0.hitbox.is_hovered(window))
8104    }
8105}
8106
8107#[derive(Clone)]
8108struct ScrollbarLayout {
8109    hitbox: Hitbox,
8110    visible_range: Range<f32>,
8111    text_unit_size: Pixels,
8112    content_offset: Pixels,
8113    thumb_size: Pixels,
8114    axis: ScrollbarAxis,
8115}
8116
8117impl ScrollbarLayout {
8118    const BORDER_WIDTH: Pixels = px(1.0);
8119    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
8120    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
8121    const MIN_THUMB_SIZE: Pixels = px(25.0);
8122
8123    fn new(
8124        scrollbar_track_hitbox: Hitbox,
8125        editor_content_size: Pixels,
8126        scroll_range: Pixels,
8127        glyph_space: Pixels,
8128        content_offset: Pixels,
8129        scroll_position: f32,
8130        axis: ScrollbarAxis,
8131    ) -> Self {
8132        let track_bounds = scrollbar_track_hitbox.bounds;
8133        // The length of the track available to the scrollbar thumb. We deliberately
8134        // exclude the content size here so that the thumb aligns with the content.
8135        let track_length = track_bounds.size.along(axis) - content_offset;
8136
8137        let text_units_per_page = editor_content_size / glyph_space;
8138        let visible_range = scroll_position..scroll_position + text_units_per_page;
8139        let total_text_units = scroll_range / glyph_space;
8140
8141        let thumb_percentage = text_units_per_page / total_text_units;
8142        let thumb_size = (track_length * thumb_percentage)
8143            .max(ScrollbarLayout::MIN_THUMB_SIZE)
8144            .min(track_length);
8145        let text_unit_size =
8146            (track_length - thumb_size) / (total_text_units - text_units_per_page).max(0.);
8147
8148        ScrollbarLayout {
8149            hitbox: scrollbar_track_hitbox,
8150            visible_range,
8151            text_unit_size,
8152            content_offset,
8153            thumb_size,
8154            axis,
8155        }
8156    }
8157
8158    fn thumb_bounds(&self) -> Bounds<Pixels> {
8159        let scrollbar_track = &self.hitbox.bounds;
8160        Bounds::new(
8161            scrollbar_track
8162                .origin
8163                .apply_along(self.axis, |origin| self.thumb_origin(origin)),
8164            scrollbar_track
8165                .size
8166                .apply_along(self.axis, |_| self.thumb_size),
8167        )
8168    }
8169
8170    fn thumb_origin(&self, origin: Pixels) -> Pixels {
8171        origin + self.content_offset + self.visible_range.start * self.text_unit_size
8172    }
8173
8174    fn marker_quads_for_ranges(
8175        &self,
8176        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
8177        column: Option<usize>,
8178    ) -> Vec<PaintQuad> {
8179        struct MinMax {
8180            min: Pixels,
8181            max: Pixels,
8182        }
8183        let (x_range, height_limit) = if let Some(column) = column {
8184            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
8185            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
8186            let end = start + column_width;
8187            (
8188                Range { start, end },
8189                MinMax {
8190                    min: Self::MIN_MARKER_HEIGHT,
8191                    max: px(f32::MAX),
8192                },
8193            )
8194        } else {
8195            (
8196                Range {
8197                    start: Self::BORDER_WIDTH,
8198                    end: self.hitbox.size.width,
8199                },
8200                MinMax {
8201                    min: Self::LINE_MARKER_HEIGHT,
8202                    max: Self::LINE_MARKER_HEIGHT,
8203                },
8204            )
8205        };
8206
8207        let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
8208        let mut pixel_ranges = row_ranges
8209            .into_iter()
8210            .map(|range| {
8211                let start_y = row_to_y(range.start);
8212                let end_y = row_to_y(range.end)
8213                    + self
8214                        .text_unit_size
8215                        .max(height_limit.min)
8216                        .min(height_limit.max);
8217                ColoredRange {
8218                    start: start_y,
8219                    end: end_y,
8220                    color: range.color,
8221                }
8222            })
8223            .peekable();
8224
8225        let mut quads = Vec::new();
8226        while let Some(mut pixel_range) = pixel_ranges.next() {
8227            while let Some(next_pixel_range) = pixel_ranges.peek() {
8228                if pixel_range.end >= next_pixel_range.start - px(1.0)
8229                    && pixel_range.color == next_pixel_range.color
8230                {
8231                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
8232                    pixel_ranges.next();
8233                } else {
8234                    break;
8235                }
8236            }
8237
8238            let bounds = Bounds::from_corners(
8239                point(x_range.start, pixel_range.start),
8240                point(x_range.end, pixel_range.end),
8241            );
8242            quads.push(quad(
8243                bounds,
8244                Corners::default(),
8245                pixel_range.color,
8246                Edges::default(),
8247                Hsla::transparent_black(),
8248                BorderStyle::default(),
8249            ));
8250        }
8251
8252        quads
8253    }
8254}
8255
8256struct CreaseTrailerLayout {
8257    element: AnyElement,
8258    bounds: Bounds<Pixels>,
8259}
8260
8261pub(crate) struct PositionMap {
8262    pub size: Size<Pixels>,
8263    pub line_height: Pixels,
8264    pub scroll_pixel_position: gpui::Point<Pixels>,
8265    pub scroll_max: gpui::Point<f32>,
8266    pub em_width: Pixels,
8267    pub em_advance: Pixels,
8268    pub visible_row_range: Range<DisplayRow>,
8269    pub line_layouts: Vec<LineWithInvisibles>,
8270    pub snapshot: EditorSnapshot,
8271    pub text_hitbox: Hitbox,
8272    pub gutter_hitbox: Hitbox,
8273}
8274
8275#[derive(Debug, Copy, Clone)]
8276pub struct PointForPosition {
8277    pub previous_valid: DisplayPoint,
8278    pub next_valid: DisplayPoint,
8279    pub exact_unclipped: DisplayPoint,
8280    pub column_overshoot_after_line_end: u32,
8281}
8282
8283impl PointForPosition {
8284    pub fn as_valid(&self) -> Option<DisplayPoint> {
8285        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
8286            Some(self.previous_valid)
8287        } else {
8288            None
8289        }
8290    }
8291}
8292
8293impl PositionMap {
8294    pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
8295        let text_bounds = self.text_hitbox.bounds;
8296        let scroll_position = self.snapshot.scroll_position();
8297        let position = position - text_bounds.origin;
8298        let y = position.y.max(px(0.)).min(self.size.height);
8299        let x = position.x + (scroll_position.x * self.em_width);
8300        let row = ((y / self.line_height) + scroll_position.y) as u32;
8301
8302        let (column, x_overshoot_after_line_end) = if let Some(line) = self
8303            .line_layouts
8304            .get(row as usize - scroll_position.y as usize)
8305        {
8306            if let Some(ix) = line.index_for_x(x) {
8307                (ix as u32, px(0.))
8308            } else {
8309                (line.len as u32, px(0.).max(x - line.width))
8310            }
8311        } else {
8312            (0, x)
8313        };
8314
8315        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
8316        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
8317        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
8318
8319        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
8320        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
8321        PointForPosition {
8322            previous_valid,
8323            next_valid,
8324            exact_unclipped,
8325            column_overshoot_after_line_end,
8326        }
8327    }
8328}
8329
8330struct BlockLayout {
8331    id: BlockId,
8332    x_offset: Pixels,
8333    row: Option<DisplayRow>,
8334    element: AnyElement,
8335    available_space: Size<AvailableSpace>,
8336    style: BlockStyle,
8337    overlaps_gutter: bool,
8338    is_buffer_header: bool,
8339}
8340
8341pub fn layout_line(
8342    row: DisplayRow,
8343    snapshot: &EditorSnapshot,
8344    style: &EditorStyle,
8345    text_width: Pixels,
8346    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
8347    window: &mut Window,
8348    cx: &mut App,
8349) -> LineWithInvisibles {
8350    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
8351    LineWithInvisibles::from_chunks(
8352        chunks,
8353        &style,
8354        MAX_LINE_LEN,
8355        1,
8356        snapshot.mode,
8357        text_width,
8358        is_row_soft_wrapped,
8359        window,
8360        cx,
8361    )
8362    .pop()
8363    .unwrap()
8364}
8365
8366#[derive(Debug)]
8367pub struct IndentGuideLayout {
8368    origin: gpui::Point<Pixels>,
8369    length: Pixels,
8370    single_indent_width: Pixels,
8371    depth: u32,
8372    active: bool,
8373    settings: IndentGuideSettings,
8374}
8375
8376pub struct CursorLayout {
8377    origin: gpui::Point<Pixels>,
8378    block_width: Pixels,
8379    line_height: Pixels,
8380    color: Hsla,
8381    shape: CursorShape,
8382    block_text: Option<ShapedLine>,
8383    cursor_name: Option<AnyElement>,
8384}
8385
8386#[derive(Debug)]
8387pub struct CursorName {
8388    string: SharedString,
8389    color: Hsla,
8390    is_top_row: bool,
8391}
8392
8393impl CursorLayout {
8394    pub fn new(
8395        origin: gpui::Point<Pixels>,
8396        block_width: Pixels,
8397        line_height: Pixels,
8398        color: Hsla,
8399        shape: CursorShape,
8400        block_text: Option<ShapedLine>,
8401    ) -> CursorLayout {
8402        CursorLayout {
8403            origin,
8404            block_width,
8405            line_height,
8406            color,
8407            shape,
8408            block_text,
8409            cursor_name: None,
8410        }
8411    }
8412
8413    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8414        Bounds {
8415            origin: self.origin + origin,
8416            size: size(self.block_width, self.line_height),
8417        }
8418    }
8419
8420    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8421        match self.shape {
8422            CursorShape::Bar => Bounds {
8423                origin: self.origin + origin,
8424                size: size(px(2.0), self.line_height),
8425            },
8426            CursorShape::Block | CursorShape::Hollow => Bounds {
8427                origin: self.origin + origin,
8428                size: size(self.block_width, self.line_height),
8429            },
8430            CursorShape::Underline => Bounds {
8431                origin: self.origin
8432                    + origin
8433                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
8434                size: size(self.block_width, px(2.0)),
8435            },
8436        }
8437    }
8438
8439    pub fn layout(
8440        &mut self,
8441        origin: gpui::Point<Pixels>,
8442        cursor_name: Option<CursorName>,
8443        window: &mut Window,
8444        cx: &mut App,
8445    ) {
8446        if let Some(cursor_name) = cursor_name {
8447            let bounds = self.bounds(origin);
8448            let text_size = self.line_height / 1.5;
8449
8450            let name_origin = if cursor_name.is_top_row {
8451                point(bounds.right() - px(1.), bounds.top())
8452            } else {
8453                match self.shape {
8454                    CursorShape::Bar => point(
8455                        bounds.right() - px(2.),
8456                        bounds.top() - text_size / 2. - px(1.),
8457                    ),
8458                    _ => point(
8459                        bounds.right() - px(1.),
8460                        bounds.top() - text_size / 2. - px(1.),
8461                    ),
8462                }
8463            };
8464            let mut name_element = div()
8465                .bg(self.color)
8466                .text_size(text_size)
8467                .px_0p5()
8468                .line_height(text_size + px(2.))
8469                .text_color(cursor_name.color)
8470                .child(cursor_name.string.clone())
8471                .into_any_element();
8472
8473            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
8474
8475            self.cursor_name = Some(name_element);
8476        }
8477    }
8478
8479    pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
8480        let bounds = self.bounds(origin);
8481
8482        //Draw background or border quad
8483        let cursor = if matches!(self.shape, CursorShape::Hollow) {
8484            outline(bounds, self.color, BorderStyle::Solid)
8485        } else {
8486            fill(bounds, self.color)
8487        };
8488
8489        if let Some(name) = &mut self.cursor_name {
8490            name.paint(window, cx);
8491        }
8492
8493        window.paint_quad(cursor);
8494
8495        if let Some(block_text) = &self.block_text {
8496            block_text
8497                .paint(self.origin + origin, self.line_height, window, cx)
8498                .log_err();
8499        }
8500    }
8501
8502    pub fn shape(&self) -> CursorShape {
8503        self.shape
8504    }
8505}
8506
8507#[derive(Debug)]
8508pub struct HighlightedRange {
8509    pub start_y: Pixels,
8510    pub line_height: Pixels,
8511    pub lines: Vec<HighlightedRangeLine>,
8512    pub color: Hsla,
8513    pub corner_radius: Pixels,
8514}
8515
8516#[derive(Debug)]
8517pub struct HighlightedRangeLine {
8518    pub start_x: Pixels,
8519    pub end_x: Pixels,
8520}
8521
8522impl HighlightedRange {
8523    pub fn paint(&self, bounds: Bounds<Pixels>, window: &mut Window) {
8524        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
8525            self.paint_lines(self.start_y, &self.lines[0..1], bounds, window);
8526            self.paint_lines(
8527                self.start_y + self.line_height,
8528                &self.lines[1..],
8529                bounds,
8530                window,
8531            );
8532        } else {
8533            self.paint_lines(self.start_y, &self.lines, bounds, window);
8534        }
8535    }
8536
8537    fn paint_lines(
8538        &self,
8539        start_y: Pixels,
8540        lines: &[HighlightedRangeLine],
8541        _bounds: Bounds<Pixels>,
8542        window: &mut Window,
8543    ) {
8544        if lines.is_empty() {
8545            return;
8546        }
8547
8548        let first_line = lines.first().unwrap();
8549        let last_line = lines.last().unwrap();
8550
8551        let first_top_left = point(first_line.start_x, start_y);
8552        let first_top_right = point(first_line.end_x, start_y);
8553
8554        let curve_height = point(Pixels::ZERO, self.corner_radius);
8555        let curve_width = |start_x: Pixels, end_x: Pixels| {
8556            let max = (end_x - start_x) / 2.;
8557            let width = if max < self.corner_radius {
8558                max
8559            } else {
8560                self.corner_radius
8561            };
8562
8563            point(width, Pixels::ZERO)
8564        };
8565
8566        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
8567        let mut builder = gpui::PathBuilder::fill();
8568        builder.move_to(first_top_right - top_curve_width);
8569        builder.curve_to(first_top_right + curve_height, first_top_right);
8570
8571        let mut iter = lines.iter().enumerate().peekable();
8572        while let Some((ix, line)) = iter.next() {
8573            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
8574
8575            if let Some((_, next_line)) = iter.peek() {
8576                let next_top_right = point(next_line.end_x, bottom_right.y);
8577
8578                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
8579                    Ordering::Equal => {
8580                        builder.line_to(bottom_right);
8581                    }
8582                    Ordering::Less => {
8583                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
8584                        builder.line_to(bottom_right - curve_height);
8585                        if self.corner_radius > Pixels::ZERO {
8586                            builder.curve_to(bottom_right - curve_width, bottom_right);
8587                        }
8588                        builder.line_to(next_top_right + curve_width);
8589                        if self.corner_radius > Pixels::ZERO {
8590                            builder.curve_to(next_top_right + curve_height, next_top_right);
8591                        }
8592                    }
8593                    Ordering::Greater => {
8594                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
8595                        builder.line_to(bottom_right - curve_height);
8596                        if self.corner_radius > Pixels::ZERO {
8597                            builder.curve_to(bottom_right + curve_width, bottom_right);
8598                        }
8599                        builder.line_to(next_top_right - curve_width);
8600                        if self.corner_radius > Pixels::ZERO {
8601                            builder.curve_to(next_top_right + curve_height, next_top_right);
8602                        }
8603                    }
8604                }
8605            } else {
8606                let curve_width = curve_width(line.start_x, line.end_x);
8607                builder.line_to(bottom_right - curve_height);
8608                if self.corner_radius > Pixels::ZERO {
8609                    builder.curve_to(bottom_right - curve_width, bottom_right);
8610                }
8611
8612                let bottom_left = point(line.start_x, bottom_right.y);
8613                builder.line_to(bottom_left + curve_width);
8614                if self.corner_radius > Pixels::ZERO {
8615                    builder.curve_to(bottom_left - curve_height, bottom_left);
8616                }
8617            }
8618        }
8619
8620        if first_line.start_x > last_line.start_x {
8621            let curve_width = curve_width(last_line.start_x, first_line.start_x);
8622            let second_top_left = point(last_line.start_x, start_y + self.line_height);
8623            builder.line_to(second_top_left + curve_height);
8624            if self.corner_radius > Pixels::ZERO {
8625                builder.curve_to(second_top_left + curve_width, second_top_left);
8626            }
8627            let first_bottom_left = point(first_line.start_x, second_top_left.y);
8628            builder.line_to(first_bottom_left - curve_width);
8629            if self.corner_radius > Pixels::ZERO {
8630                builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
8631            }
8632        }
8633
8634        builder.line_to(first_top_left + curve_height);
8635        if self.corner_radius > Pixels::ZERO {
8636            builder.curve_to(first_top_left + top_curve_width, first_top_left);
8637        }
8638        builder.line_to(first_top_right - top_curve_width);
8639
8640        if let Ok(path) = builder.build() {
8641            window.paint_path(path, self.color);
8642        }
8643    }
8644}
8645
8646enum CursorPopoverType {
8647    CodeContextMenu,
8648    EditPrediction,
8649}
8650
8651pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8652    (delta.pow(1.2) / 100.0).min(px(3.0)).into()
8653}
8654
8655fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8656    (delta.pow(1.2) / 300.0).into()
8657}
8658
8659pub fn register_action<T: Action>(
8660    editor: &Entity<Editor>,
8661    window: &mut Window,
8662    listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
8663) {
8664    let editor = editor.clone();
8665    window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
8666        let action = action.downcast_ref().unwrap();
8667        if phase == DispatchPhase::Bubble {
8668            editor.update(cx, |editor, cx| {
8669                listener(editor, action, window, cx);
8670            })
8671        }
8672    })
8673}
8674
8675fn compute_auto_height_layout(
8676    editor: &mut Editor,
8677    max_lines: usize,
8678    max_line_number_width: Pixels,
8679    known_dimensions: Size<Option<Pixels>>,
8680    available_width: AvailableSpace,
8681    window: &mut Window,
8682    cx: &mut Context<Editor>,
8683) -> Option<Size<Pixels>> {
8684    let width = known_dimensions.width.or({
8685        if let AvailableSpace::Definite(available_width) = available_width {
8686            Some(available_width)
8687        } else {
8688            None
8689        }
8690    })?;
8691    if let Some(height) = known_dimensions.height {
8692        return Some(size(width, height));
8693    }
8694
8695    let style = editor.style.as_ref().unwrap();
8696    let font_id = window.text_system().resolve_font(&style.text.font());
8697    let font_size = style.text.font_size.to_pixels(window.rem_size());
8698    let line_height = style.text.line_height_in_pixels(window.rem_size());
8699    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8700
8701    let mut snapshot = editor.snapshot(window, cx);
8702    let gutter_dimensions = snapshot
8703        .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
8704        .unwrap_or_default();
8705
8706    editor.gutter_dimensions = gutter_dimensions;
8707    let text_width = width - gutter_dimensions.width;
8708    let overscroll = size(em_width, px(0.));
8709
8710    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
8711    if editor.set_wrap_width(Some(editor_width), cx) {
8712        snapshot = editor.snapshot(window, cx);
8713    }
8714
8715    let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
8716    let height = scroll_height
8717        .max(line_height)
8718        .min(line_height * max_lines as f32);
8719
8720    Some(size(width, height))
8721}
8722
8723#[cfg(test)]
8724mod tests {
8725    use super::*;
8726    use crate::{
8727        Editor, MultiBuffer,
8728        display_map::{BlockPlacement, BlockProperties},
8729        editor_tests::{init_test, update_test_language_settings},
8730    };
8731    use gpui::{TestAppContext, VisualTestContext};
8732    use language::language_settings;
8733    use log::info;
8734    use std::num::NonZeroU32;
8735    use util::test::sample_text;
8736
8737    #[gpui::test]
8738    fn test_shape_line_numbers(cx: &mut TestAppContext) {
8739        init_test(cx, |_| {});
8740        let window = cx.add_window(|window, cx| {
8741            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
8742            Editor::new(EditorMode::full(), buffer, None, window, cx)
8743        });
8744
8745        let editor = window.root(cx).unwrap();
8746        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
8747        let line_height = window
8748            .update(cx, |_, window, _| {
8749                style.text.line_height_in_pixels(window.rem_size())
8750            })
8751            .unwrap();
8752        let element = EditorElement::new(&editor, style);
8753        let snapshot = window
8754            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
8755            .unwrap();
8756
8757        let layouts = cx
8758            .update_window(*window, |_, window, cx| {
8759                element.layout_line_numbers(
8760                    None,
8761                    GutterDimensions {
8762                        left_padding: Pixels::ZERO,
8763                        right_padding: Pixels::ZERO,
8764                        width: px(30.0),
8765                        margin: Pixels::ZERO,
8766                        git_blame_entries_width: None,
8767                    },
8768                    line_height,
8769                    gpui::Point::default(),
8770                    DisplayRow(0)..DisplayRow(6),
8771                    &(0..6)
8772                        .map(|row| RowInfo {
8773                            buffer_row: Some(row),
8774                            ..Default::default()
8775                        })
8776                        .collect::<Vec<_>>(),
8777                    &BTreeMap::default(),
8778                    Some(DisplayPoint::new(DisplayRow(0), 0)),
8779                    &snapshot,
8780                    window,
8781                    cx,
8782                )
8783            })
8784            .unwrap();
8785        assert_eq!(layouts.len(), 6);
8786
8787        let relative_rows = window
8788            .update(cx, |editor, window, cx| {
8789                let snapshot = editor.snapshot(window, cx);
8790                element.calculate_relative_line_numbers(
8791                    &snapshot,
8792                    &(DisplayRow(0)..DisplayRow(6)),
8793                    Some(DisplayRow(3)),
8794                )
8795            })
8796            .unwrap();
8797        assert_eq!(relative_rows[&DisplayRow(0)], 3);
8798        assert_eq!(relative_rows[&DisplayRow(1)], 2);
8799        assert_eq!(relative_rows[&DisplayRow(2)], 1);
8800        // current line has no relative number
8801        assert_eq!(relative_rows[&DisplayRow(4)], 1);
8802        assert_eq!(relative_rows[&DisplayRow(5)], 2);
8803
8804        // works if cursor is before screen
8805        let relative_rows = window
8806            .update(cx, |editor, window, cx| {
8807                let snapshot = editor.snapshot(window, cx);
8808                element.calculate_relative_line_numbers(
8809                    &snapshot,
8810                    &(DisplayRow(3)..DisplayRow(6)),
8811                    Some(DisplayRow(1)),
8812                )
8813            })
8814            .unwrap();
8815        assert_eq!(relative_rows.len(), 3);
8816        assert_eq!(relative_rows[&DisplayRow(3)], 2);
8817        assert_eq!(relative_rows[&DisplayRow(4)], 3);
8818        assert_eq!(relative_rows[&DisplayRow(5)], 4);
8819
8820        // works if cursor is after screen
8821        let relative_rows = window
8822            .update(cx, |editor, window, cx| {
8823                let snapshot = editor.snapshot(window, cx);
8824                element.calculate_relative_line_numbers(
8825                    &snapshot,
8826                    &(DisplayRow(0)..DisplayRow(3)),
8827                    Some(DisplayRow(6)),
8828                )
8829            })
8830            .unwrap();
8831        assert_eq!(relative_rows.len(), 3);
8832        assert_eq!(relative_rows[&DisplayRow(0)], 5);
8833        assert_eq!(relative_rows[&DisplayRow(1)], 4);
8834        assert_eq!(relative_rows[&DisplayRow(2)], 3);
8835    }
8836
8837    #[gpui::test]
8838    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
8839        init_test(cx, |_| {});
8840
8841        let window = cx.add_window(|window, cx| {
8842            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
8843            Editor::new(EditorMode::full(), buffer, None, window, cx)
8844        });
8845        let cx = &mut VisualTestContext::from_window(*window, cx);
8846        let editor = window.root(cx).unwrap();
8847        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8848
8849        window
8850            .update(cx, |editor, window, cx| {
8851                editor.cursor_shape = CursorShape::Block;
8852                editor.change_selections(None, window, cx, |s| {
8853                    s.select_ranges([
8854                        Point::new(0, 0)..Point::new(1, 0),
8855                        Point::new(3, 2)..Point::new(3, 3),
8856                        Point::new(5, 6)..Point::new(6, 0),
8857                    ]);
8858                });
8859            })
8860            .unwrap();
8861
8862        let (_, state) = cx.draw(
8863            point(px(500.), px(500.)),
8864            size(px(500.), px(500.)),
8865            |_, _| EditorElement::new(&editor, style),
8866        );
8867
8868        assert_eq!(state.selections.len(), 1);
8869        let local_selections = &state.selections[0].1;
8870        assert_eq!(local_selections.len(), 3);
8871        // moves cursor back one line
8872        assert_eq!(
8873            local_selections[0].head,
8874            DisplayPoint::new(DisplayRow(0), 6)
8875        );
8876        assert_eq!(
8877            local_selections[0].range,
8878            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
8879        );
8880
8881        // moves cursor back one column
8882        assert_eq!(
8883            local_selections[1].range,
8884            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
8885        );
8886        assert_eq!(
8887            local_selections[1].head,
8888            DisplayPoint::new(DisplayRow(3), 2)
8889        );
8890
8891        // leaves cursor on the max point
8892        assert_eq!(
8893            local_selections[2].range,
8894            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
8895        );
8896        assert_eq!(
8897            local_selections[2].head,
8898            DisplayPoint::new(DisplayRow(6), 0)
8899        );
8900
8901        // active lines does not include 1 (even though the range of the selection does)
8902        assert_eq!(
8903            state.active_rows.keys().cloned().collect::<Vec<_>>(),
8904            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
8905        );
8906    }
8907
8908    #[gpui::test]
8909    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
8910        init_test(cx, |_| {});
8911
8912        let window = cx.add_window(|window, cx| {
8913            let buffer = MultiBuffer::build_simple("", cx);
8914            Editor::new(EditorMode::full(), buffer, None, window, cx)
8915        });
8916        let cx = &mut VisualTestContext::from_window(*window, cx);
8917        let editor = window.root(cx).unwrap();
8918        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8919        window
8920            .update(cx, |editor, window, cx| {
8921                editor.set_placeholder_text("hello", cx);
8922                editor.insert_blocks(
8923                    [BlockProperties {
8924                        style: BlockStyle::Fixed,
8925                        placement: BlockPlacement::Above(Anchor::min()),
8926                        height: Some(3),
8927                        render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
8928                        priority: 0,
8929                    }],
8930                    None,
8931                    cx,
8932                );
8933
8934                // Blur the editor so that it displays placeholder text.
8935                window.blur();
8936            })
8937            .unwrap();
8938
8939        let (_, state) = cx.draw(
8940            point(px(500.), px(500.)),
8941            size(px(500.), px(500.)),
8942            |_, _| EditorElement::new(&editor, style),
8943        );
8944        assert_eq!(state.position_map.line_layouts.len(), 4);
8945        assert_eq!(state.line_numbers.len(), 1);
8946        assert_eq!(
8947            state
8948                .line_numbers
8949                .get(&MultiBufferRow(0))
8950                .map(|line_number| line_number.shaped_line.text.as_ref()),
8951            Some("1")
8952        );
8953    }
8954
8955    #[gpui::test]
8956    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
8957        const TAB_SIZE: u32 = 4;
8958
8959        let input_text = "\t \t|\t| a b";
8960        let expected_invisibles = vec![
8961            Invisible::Tab {
8962                line_start_offset: 0,
8963                line_end_offset: TAB_SIZE as usize,
8964            },
8965            Invisible::Whitespace {
8966                line_offset: TAB_SIZE as usize,
8967            },
8968            Invisible::Tab {
8969                line_start_offset: TAB_SIZE as usize + 1,
8970                line_end_offset: TAB_SIZE as usize * 2,
8971            },
8972            Invisible::Tab {
8973                line_start_offset: TAB_SIZE as usize * 2 + 1,
8974                line_end_offset: TAB_SIZE as usize * 3,
8975            },
8976            Invisible::Whitespace {
8977                line_offset: TAB_SIZE as usize * 3 + 1,
8978            },
8979            Invisible::Whitespace {
8980                line_offset: TAB_SIZE as usize * 3 + 3,
8981            },
8982        ];
8983        assert_eq!(
8984            expected_invisibles.len(),
8985            input_text
8986                .chars()
8987                .filter(|initial_char| initial_char.is_whitespace())
8988                .count(),
8989            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8990        );
8991
8992        for show_line_numbers in [true, false] {
8993            init_test(cx, |s| {
8994                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8995                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
8996            });
8997
8998            let actual_invisibles = collect_invisibles_from_new_editor(
8999                cx,
9000                EditorMode::full(),
9001                input_text,
9002                px(500.0),
9003                show_line_numbers,
9004            );
9005
9006            assert_eq!(expected_invisibles, actual_invisibles);
9007        }
9008    }
9009
9010    #[gpui::test]
9011    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
9012        init_test(cx, |s| {
9013            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
9014            s.defaults.tab_size = NonZeroU32::new(4);
9015        });
9016
9017        for editor_mode_without_invisibles in [
9018            EditorMode::SingleLine { auto_width: false },
9019            EditorMode::AutoHeight { max_lines: 100 },
9020        ] {
9021            for show_line_numbers in [true, false] {
9022                let invisibles = collect_invisibles_from_new_editor(
9023                    cx,
9024                    editor_mode_without_invisibles,
9025                    "\t\t\t| | a b",
9026                    px(500.0),
9027                    show_line_numbers,
9028                );
9029                assert!(
9030                    invisibles.is_empty(),
9031                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
9032                );
9033            }
9034        }
9035    }
9036
9037    #[gpui::test]
9038    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
9039        let tab_size = 4;
9040        let input_text = "a\tbcd     ".repeat(9);
9041        let repeated_invisibles = [
9042            Invisible::Tab {
9043                line_start_offset: 1,
9044                line_end_offset: tab_size as usize,
9045            },
9046            Invisible::Whitespace {
9047                line_offset: tab_size as usize + 3,
9048            },
9049            Invisible::Whitespace {
9050                line_offset: tab_size as usize + 4,
9051            },
9052            Invisible::Whitespace {
9053                line_offset: tab_size as usize + 5,
9054            },
9055            Invisible::Whitespace {
9056                line_offset: tab_size as usize + 6,
9057            },
9058            Invisible::Whitespace {
9059                line_offset: tab_size as usize + 7,
9060            },
9061        ];
9062        let expected_invisibles = std::iter::once(repeated_invisibles)
9063            .cycle()
9064            .take(9)
9065            .flatten()
9066            .collect::<Vec<_>>();
9067        assert_eq!(
9068            expected_invisibles.len(),
9069            input_text
9070                .chars()
9071                .filter(|initial_char| initial_char.is_whitespace())
9072                .count(),
9073            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
9074        );
9075        info!("Expected invisibles: {expected_invisibles:?}");
9076
9077        init_test(cx, |_| {});
9078
9079        // Put the same string with repeating whitespace pattern into editors of various size,
9080        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
9081        let resize_step = 10.0;
9082        let mut editor_width = 200.0;
9083        while editor_width <= 1000.0 {
9084            for show_line_numbers in [true, false] {
9085                update_test_language_settings(cx, |s| {
9086                    s.defaults.tab_size = NonZeroU32::new(tab_size);
9087                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
9088                    s.defaults.preferred_line_length = Some(editor_width as u32);
9089                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
9090                });
9091
9092                let actual_invisibles = collect_invisibles_from_new_editor(
9093                    cx,
9094                    EditorMode::full(),
9095                    &input_text,
9096                    px(editor_width),
9097                    show_line_numbers,
9098                );
9099
9100                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
9101                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
9102                let mut i = 0;
9103                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
9104                    i = actual_index;
9105                    match expected_invisibles.get(i) {
9106                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
9107                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
9108                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
9109                            _ => {
9110                                panic!(
9111                                    "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
9112                                )
9113                            }
9114                        },
9115                        None => {
9116                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
9117                        }
9118                    }
9119                }
9120                let missing_expected_invisibles = &expected_invisibles[i + 1..];
9121                assert!(
9122                    missing_expected_invisibles.is_empty(),
9123                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
9124                );
9125
9126                editor_width += resize_step;
9127            }
9128        }
9129    }
9130
9131    fn collect_invisibles_from_new_editor(
9132        cx: &mut TestAppContext,
9133        editor_mode: EditorMode,
9134        input_text: &str,
9135        editor_width: Pixels,
9136        show_line_numbers: bool,
9137    ) -> Vec<Invisible> {
9138        info!(
9139            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
9140            editor_width.0
9141        );
9142        let window = cx.add_window(|window, cx| {
9143            let buffer = MultiBuffer::build_simple(input_text, cx);
9144            Editor::new(editor_mode, buffer, None, window, cx)
9145        });
9146        let cx = &mut VisualTestContext::from_window(*window, cx);
9147        let editor = window.root(cx).unwrap();
9148
9149        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
9150        window
9151            .update(cx, |editor, _, cx| {
9152                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
9153                editor.set_wrap_width(Some(editor_width), cx);
9154                editor.set_show_line_numbers(show_line_numbers, cx);
9155            })
9156            .unwrap();
9157        let (_, state) = cx.draw(
9158            point(px(500.), px(500.)),
9159            size(px(500.), px(500.)),
9160            |_, _| EditorElement::new(&editor, style),
9161        );
9162        state
9163            .position_map
9164            .line_layouts
9165            .iter()
9166            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
9167            .cloned()
9168            .collect()
9169    }
9170}