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