element.rs

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