element.rs

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