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