element.rs

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