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