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 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 !range.contains(&display_row) {
2289                        return None;
2290                    }
2291                    if row_infos
2292                        .get((display_row - range.start).0 as usize)
2293                        .is_some_and(|row_info| row_info.expand_info.is_some())
2294                    {
2295                        return None;
2296                    }
2297
2298                    let button = editor.render_run_indicator(
2299                        &self.style,
2300                        Some(display_row) == active_task_indicator_row,
2301                        display_row,
2302                        breakpoints.remove(&display_row),
2303                        cx,
2304                    );
2305
2306                    let button = prepaint_gutter_button(
2307                        button,
2308                        display_row,
2309                        line_height,
2310                        gutter_dimensions,
2311                        scroll_pixel_position,
2312                        gutter_hitbox,
2313                        display_hunks,
2314                        window,
2315                        cx,
2316                    );
2317                    Some(button)
2318                })
2319                .collect_vec()
2320        })
2321    }
2322
2323    fn layout_expand_toggles(
2324        &self,
2325        gutter_hitbox: &Hitbox,
2326        gutter_dimensions: GutterDimensions,
2327        em_width: Pixels,
2328        line_height: Pixels,
2329        scroll_position: gpui::Point<f32>,
2330        buffer_rows: &[RowInfo],
2331        window: &mut Window,
2332        cx: &mut App,
2333    ) -> Vec<Option<(AnyElement, gpui::Point<Pixels>)>> {
2334        if self.editor.read(cx).disable_expand_excerpt_buttons {
2335            return vec![];
2336        }
2337
2338        let editor_font_size = self.style.text.font_size.to_pixels(window.rem_size()) * 1.2;
2339
2340        let scroll_top = scroll_position.y * line_height;
2341
2342        let max_line_number_length = self
2343            .editor
2344            .read(cx)
2345            .buffer()
2346            .read(cx)
2347            .snapshot(cx)
2348            .widest_line_number()
2349            .ilog10()
2350            + 1;
2351
2352        let elements = buffer_rows
2353            .into_iter()
2354            .enumerate()
2355            .map(|(ix, row_info)| {
2356                let ExpandInfo {
2357                    excerpt_id,
2358                    direction,
2359                } = row_info.expand_info?;
2360
2361                let icon_name = match direction {
2362                    ExpandExcerptDirection::Up => IconName::ExpandUp,
2363                    ExpandExcerptDirection::Down => IconName::ExpandDown,
2364                    ExpandExcerptDirection::UpAndDown => IconName::ExpandVertical,
2365                };
2366
2367                let git_gutter_width = Self::gutter_strip_width(line_height);
2368                let available_width = gutter_dimensions.left_padding - git_gutter_width;
2369
2370                let editor = self.editor.clone();
2371                let is_wide = max_line_number_length >= MIN_LINE_NUMBER_DIGITS
2372                    && row_info
2373                        .buffer_row
2374                        .is_some_and(|row| (row + 1).ilog10() + 1 == max_line_number_length)
2375                    || gutter_dimensions.right_padding == px(0.);
2376
2377                let width = if is_wide {
2378                    available_width - px(2.)
2379                } else {
2380                    available_width + em_width - px(2.)
2381                };
2382
2383                let toggle = IconButton::new(("expand", ix), icon_name)
2384                    .icon_color(Color::Custom(cx.theme().colors().editor_line_number))
2385                    .selected_icon_color(Color::Custom(cx.theme().colors().editor_foreground))
2386                    .icon_size(IconSize::Custom(rems(editor_font_size / window.rem_size())))
2387                    .width(width.into())
2388                    .on_click(move |_, window, cx| {
2389                        editor.update(cx, |editor, cx| {
2390                            editor.expand_excerpt(excerpt_id, direction, window, cx);
2391                        });
2392                    })
2393                    .tooltip(Tooltip::for_action_title(
2394                        "Expand Excerpt",
2395                        &crate::actions::ExpandExcerpts::default(),
2396                    ))
2397                    .into_any_element();
2398
2399                let position = point(
2400                    git_gutter_width + px(1.),
2401                    ix as f32 * line_height - (scroll_top % line_height) + px(1.),
2402                );
2403                let origin = gutter_hitbox.origin + position;
2404
2405                Some((toggle, origin))
2406            })
2407            .collect();
2408
2409        elements
2410    }
2411
2412    fn layout_code_actions_indicator(
2413        &self,
2414        line_height: Pixels,
2415        newest_selection_head: DisplayPoint,
2416        scroll_pixel_position: gpui::Point<Pixels>,
2417        gutter_dimensions: &GutterDimensions,
2418        gutter_hitbox: &Hitbox,
2419        breakpoint_points: &mut HashMap<DisplayRow, (Anchor, Breakpoint)>,
2420        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
2421        window: &mut Window,
2422        cx: &mut App,
2423    ) -> Option<AnyElement> {
2424        let mut active = false;
2425        let mut button = None;
2426        let row = newest_selection_head.row();
2427        self.editor.update(cx, |editor, cx| {
2428            if let Some(crate::CodeContextMenu::CodeActions(CodeActionsMenu {
2429                deployed_from_indicator,
2430                ..
2431            })) = editor.context_menu.borrow().as_ref()
2432            {
2433                active = deployed_from_indicator.map_or(true, |indicator_row| indicator_row == row);
2434            };
2435
2436            let breakpoint = breakpoint_points.get(&row);
2437            button = editor.render_code_actions_indicator(&self.style, row, active, breakpoint, cx);
2438        });
2439
2440        let button = button?;
2441        breakpoint_points.remove(&row);
2442
2443        let button = prepaint_gutter_button(
2444            button,
2445            row,
2446            line_height,
2447            gutter_dimensions,
2448            scroll_pixel_position,
2449            gutter_hitbox,
2450            display_hunks,
2451            window,
2452            cx,
2453        );
2454
2455        Some(button)
2456    }
2457
2458    fn calculate_relative_line_numbers(
2459        &self,
2460        snapshot: &EditorSnapshot,
2461        rows: &Range<DisplayRow>,
2462        relative_to: Option<DisplayRow>,
2463    ) -> HashMap<DisplayRow, DisplayRowDelta> {
2464        let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
2465        let Some(relative_to) = relative_to else {
2466            return relative_rows;
2467        };
2468
2469        let start = rows.start.min(relative_to);
2470        let end = rows.end.max(relative_to);
2471
2472        let buffer_rows = snapshot
2473            .row_infos(start)
2474            .take(1 + end.minus(start) as usize)
2475            .collect::<Vec<_>>();
2476
2477        let head_idx = relative_to.minus(start);
2478        let mut delta = 1;
2479        let mut i = head_idx + 1;
2480        while i < buffer_rows.len() as u32 {
2481            if buffer_rows[i as usize].buffer_row.is_some() {
2482                if rows.contains(&DisplayRow(i + start.0)) {
2483                    relative_rows.insert(DisplayRow(i + start.0), delta);
2484                }
2485                delta += 1;
2486            }
2487            i += 1;
2488        }
2489        delta = 1;
2490        i = head_idx.min(buffer_rows.len() as u32 - 1);
2491        while i > 0 && buffer_rows[i as usize].buffer_row.is_none() {
2492            i -= 1;
2493        }
2494
2495        while i > 0 {
2496            i -= 1;
2497            if buffer_rows[i as usize].buffer_row.is_some() {
2498                if rows.contains(&DisplayRow(i + start.0)) {
2499                    relative_rows.insert(DisplayRow(i + start.0), delta);
2500                }
2501                delta += 1;
2502            }
2503        }
2504
2505        relative_rows
2506    }
2507
2508    fn layout_line_numbers(
2509        &self,
2510        gutter_hitbox: Option<&Hitbox>,
2511        gutter_dimensions: GutterDimensions,
2512        line_height: Pixels,
2513        scroll_position: gpui::Point<f32>,
2514        rows: Range<DisplayRow>,
2515        buffer_rows: &[RowInfo],
2516        active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
2517        newest_selection_head: Option<DisplayPoint>,
2518        snapshot: &EditorSnapshot,
2519        window: &mut Window,
2520        cx: &mut App,
2521    ) -> Arc<HashMap<MultiBufferRow, LineNumberLayout>> {
2522        let include_line_numbers = snapshot.show_line_numbers.unwrap_or_else(|| {
2523            EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode.is_full()
2524        });
2525        if !include_line_numbers {
2526            return Arc::default();
2527        }
2528
2529        let (newest_selection_head, is_relative) = self.editor.update(cx, |editor, cx| {
2530            let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
2531                let newest = editor.selections.newest::<Point>(cx);
2532                SelectionLayout::new(
2533                    newest,
2534                    editor.selections.line_mode,
2535                    editor.cursor_shape,
2536                    &snapshot.display_snapshot,
2537                    true,
2538                    true,
2539                    None,
2540                )
2541                .head
2542            });
2543            let is_relative = editor.should_use_relative_line_numbers(cx);
2544            (newest_selection_head, is_relative)
2545        });
2546
2547        let relative_to = if is_relative {
2548            Some(newest_selection_head.row())
2549        } else {
2550            None
2551        };
2552        let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
2553        let mut line_number = String::new();
2554        let line_numbers = buffer_rows
2555            .into_iter()
2556            .enumerate()
2557            .flat_map(|(ix, row_info)| {
2558                let display_row = DisplayRow(rows.start.0 + ix as u32);
2559                line_number.clear();
2560                let non_relative_number = row_info.buffer_row? + 1;
2561                let number = relative_rows
2562                    .get(&display_row)
2563                    .unwrap_or(&non_relative_number);
2564                write!(&mut line_number, "{number}").unwrap();
2565                if row_info
2566                    .diff_status
2567                    .is_some_and(|status| status.is_deleted())
2568                {
2569                    return None;
2570                }
2571
2572                let color = active_rows
2573                    .get(&display_row)
2574                    .map(|spec| {
2575                        if spec.breakpoint {
2576                            cx.theme().colors().debugger_accent
2577                        } else {
2578                            cx.theme().colors().editor_active_line_number
2579                        }
2580                    })
2581                    .unwrap_or_else(|| cx.theme().colors().editor_line_number);
2582                let shaped_line = self
2583                    .shape_line_number(SharedString::from(&line_number), color, window)
2584                    .log_err()?;
2585                let scroll_top = scroll_position.y * line_height;
2586                let line_origin = gutter_hitbox.map(|hitbox| {
2587                    hitbox.origin
2588                        + point(
2589                            hitbox.size.width - shaped_line.width - gutter_dimensions.right_padding,
2590                            ix as f32 * line_height - (scroll_top % line_height),
2591                        )
2592                });
2593
2594                #[cfg(not(test))]
2595                let hitbox = line_origin.map(|line_origin| {
2596                    window.insert_hitbox(
2597                        Bounds::new(line_origin, size(shaped_line.width, line_height)),
2598                        false,
2599                    )
2600                });
2601                #[cfg(test)]
2602                let hitbox = {
2603                    let _ = line_origin;
2604                    None
2605                };
2606
2607                let multi_buffer_row = DisplayPoint::new(display_row, 0).to_point(snapshot).row;
2608                let multi_buffer_row = MultiBufferRow(multi_buffer_row);
2609                let line_number = LineNumberLayout {
2610                    shaped_line,
2611                    hitbox,
2612                };
2613                Some((multi_buffer_row, line_number))
2614            })
2615            .collect();
2616        Arc::new(line_numbers)
2617    }
2618
2619    fn layout_crease_toggles(
2620        &self,
2621        rows: Range<DisplayRow>,
2622        row_infos: &[RowInfo],
2623        active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
2624        snapshot: &EditorSnapshot,
2625        window: &mut Window,
2626        cx: &mut App,
2627    ) -> Vec<Option<AnyElement>> {
2628        let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
2629            && snapshot.mode.is_full()
2630            && self.editor.read(cx).is_singleton(cx);
2631        if include_fold_statuses {
2632            row_infos
2633                .into_iter()
2634                .enumerate()
2635                .map(|(ix, info)| {
2636                    if info.expand_info.is_some() {
2637                        return None;
2638                    }
2639                    let row = info.multibuffer_row?;
2640                    let display_row = DisplayRow(rows.start.0 + ix as u32);
2641                    let active = active_rows.contains_key(&display_row);
2642
2643                    snapshot.render_crease_toggle(row, active, self.editor.clone(), window, cx)
2644                })
2645                .collect()
2646        } else {
2647            Vec::new()
2648        }
2649    }
2650
2651    fn layout_crease_trailers(
2652        &self,
2653        buffer_rows: impl IntoIterator<Item = RowInfo>,
2654        snapshot: &EditorSnapshot,
2655        window: &mut Window,
2656        cx: &mut App,
2657    ) -> Vec<Option<AnyElement>> {
2658        buffer_rows
2659            .into_iter()
2660            .map(|row_info| {
2661                if row_info.expand_info.is_some() {
2662                    return None;
2663                }
2664                if let Some(row) = row_info.multibuffer_row {
2665                    snapshot.render_crease_trailer(row, window, cx)
2666                } else {
2667                    None
2668                }
2669            })
2670            .collect()
2671    }
2672
2673    fn layout_lines(
2674        rows: Range<DisplayRow>,
2675        snapshot: &EditorSnapshot,
2676        style: &EditorStyle,
2677        editor_width: Pixels,
2678        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2679        window: &mut Window,
2680        cx: &mut App,
2681    ) -> Vec<LineWithInvisibles> {
2682        if rows.start >= rows.end {
2683            return Vec::new();
2684        }
2685
2686        // Show the placeholder when the editor is empty
2687        if snapshot.is_empty() {
2688            let font_size = style.text.font_size.to_pixels(window.rem_size());
2689            let placeholder_color = cx.theme().colors().text_placeholder;
2690            let placeholder_text = snapshot.placeholder_text();
2691
2692            let placeholder_lines = placeholder_text
2693                .as_ref()
2694                .map_or("", AsRef::as_ref)
2695                .split('\n')
2696                .skip(rows.start.0 as usize)
2697                .chain(iter::repeat(""))
2698                .take(rows.len());
2699            placeholder_lines
2700                .filter_map(move |line| {
2701                    let run = TextRun {
2702                        len: line.len(),
2703                        font: style.text.font(),
2704                        color: placeholder_color,
2705                        background_color: None,
2706                        underline: Default::default(),
2707                        strikethrough: None,
2708                    };
2709                    window
2710                        .text_system()
2711                        .shape_line(line.to_string().into(), font_size, &[run])
2712                        .log_err()
2713                })
2714                .map(|line| LineWithInvisibles {
2715                    width: line.width,
2716                    len: line.len,
2717                    fragments: smallvec![LineFragment::Text(line)],
2718                    invisibles: Vec::new(),
2719                    font_size,
2720                })
2721                .collect()
2722        } else {
2723            let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
2724            LineWithInvisibles::from_chunks(
2725                chunks,
2726                &style,
2727                MAX_LINE_LEN,
2728                rows.len(),
2729                snapshot.mode,
2730                editor_width,
2731                is_row_soft_wrapped,
2732                window,
2733                cx,
2734            )
2735        }
2736    }
2737
2738    fn prepaint_lines(
2739        &self,
2740        start_row: DisplayRow,
2741        line_layouts: &mut [LineWithInvisibles],
2742        line_height: Pixels,
2743        scroll_pixel_position: gpui::Point<Pixels>,
2744        content_origin: gpui::Point<Pixels>,
2745        window: &mut Window,
2746        cx: &mut App,
2747    ) -> SmallVec<[AnyElement; 1]> {
2748        let mut line_elements = SmallVec::new();
2749        for (ix, line) in line_layouts.iter_mut().enumerate() {
2750            let row = start_row + DisplayRow(ix as u32);
2751            line.prepaint(
2752                line_height,
2753                scroll_pixel_position,
2754                row,
2755                content_origin,
2756                &mut line_elements,
2757                window,
2758                cx,
2759            );
2760        }
2761        line_elements
2762    }
2763
2764    fn render_block(
2765        &self,
2766        block: &Block,
2767        available_width: AvailableSpace,
2768        block_id: BlockId,
2769        block_row_start: DisplayRow,
2770        snapshot: &EditorSnapshot,
2771        text_x: Pixels,
2772        rows: &Range<DisplayRow>,
2773        line_layouts: &[LineWithInvisibles],
2774        gutter_dimensions: &GutterDimensions,
2775        line_height: Pixels,
2776        em_width: Pixels,
2777        text_hitbox: &Hitbox,
2778        editor_width: Pixels,
2779        scroll_width: &mut Pixels,
2780        resized_blocks: &mut HashMap<CustomBlockId, u32>,
2781        row_block_types: &mut HashMap<DisplayRow, bool>,
2782        selections: &[Selection<Point>],
2783        selected_buffer_ids: &Vec<BufferId>,
2784        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2785        sticky_header_excerpt_id: Option<ExcerptId>,
2786        window: &mut Window,
2787        cx: &mut App,
2788    ) -> Option<(AnyElement, Size<Pixels>, DisplayRow, Pixels)> {
2789        let mut x_position = None;
2790        let mut element = match block {
2791            Block::Custom(custom) => {
2792                let block_start = custom.start().to_point(&snapshot.buffer_snapshot);
2793                let block_end = custom.end().to_point(&snapshot.buffer_snapshot);
2794                if block.place_near() && snapshot.is_line_folded(MultiBufferRow(block_start.row)) {
2795                    return None;
2796                }
2797                let align_to = block_start.to_display_point(snapshot);
2798                let x_and_width = |layout: &LineWithInvisibles| {
2799                    Some((
2800                        text_x + layout.x_for_index(align_to.column() as usize),
2801                        text_x + layout.width,
2802                    ))
2803                };
2804                let line_ix = align_to.row().0.checked_sub(rows.start.0);
2805                x_position =
2806                    if let Some(layout) = line_ix.and_then(|ix| line_layouts.get(ix as usize)) {
2807                        x_and_width(&layout)
2808                    } else {
2809                        x_and_width(&layout_line(
2810                            align_to.row(),
2811                            snapshot,
2812                            &self.style,
2813                            editor_width,
2814                            is_row_soft_wrapped,
2815                            window,
2816                            cx,
2817                        ))
2818                    };
2819
2820                let anchor_x = x_position.unwrap().0;
2821
2822                let selected = selections
2823                    .binary_search_by(|selection| {
2824                        if selection.end <= block_start {
2825                            Ordering::Less
2826                        } else if selection.start >= block_end {
2827                            Ordering::Greater
2828                        } else {
2829                            Ordering::Equal
2830                        }
2831                    })
2832                    .is_ok();
2833
2834                div()
2835                    .size_full()
2836                    .child(custom.render(&mut BlockContext {
2837                        window,
2838                        app: cx,
2839                        anchor_x,
2840                        gutter_dimensions,
2841                        line_height,
2842                        em_width,
2843                        block_id,
2844                        selected,
2845                        max_width: text_hitbox.size.width.max(*scroll_width),
2846                        editor_style: &self.style,
2847                    }))
2848                    .into_any()
2849            }
2850
2851            Block::FoldedBuffer {
2852                first_excerpt,
2853                height,
2854                ..
2855            } => {
2856                let selected = selected_buffer_ids.contains(&first_excerpt.buffer_id);
2857                let result = v_flex().id(block_id).w_full();
2858
2859                let jump_data = header_jump_data(snapshot, block_row_start, *height, first_excerpt);
2860                result
2861                    .child(self.render_buffer_header(
2862                        first_excerpt,
2863                        true,
2864                        selected,
2865                        false,
2866                        jump_data,
2867                        window,
2868                        cx,
2869                    ))
2870                    .into_any_element()
2871            }
2872
2873            Block::ExcerptBoundary {
2874                excerpt,
2875                height,
2876                starts_new_buffer,
2877                ..
2878            } => {
2879                let color = cx.theme().colors().clone();
2880                let mut result = v_flex().id(block_id).w_full();
2881
2882                let jump_data = header_jump_data(snapshot, block_row_start, *height, excerpt);
2883
2884                if *starts_new_buffer {
2885                    if sticky_header_excerpt_id != Some(excerpt.id) {
2886                        let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
2887
2888                        result = result.child(self.render_buffer_header(
2889                            excerpt, false, selected, false, jump_data, window, cx,
2890                        ));
2891                    } else {
2892                        result =
2893                            result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
2894                    }
2895                } else {
2896                    result = result.child(
2897                        h_flex().relative().child(
2898                            div()
2899                                .top(line_height / 2.)
2900                                .absolute()
2901                                .w_full()
2902                                .h_px()
2903                                .bg(color.border_variant),
2904                        ),
2905                    );
2906                };
2907
2908                result.into_any()
2909            }
2910        };
2911
2912        // Discover the element's content height, then round up to the nearest multiple of line height.
2913        let preliminary_size = element.layout_as_root(
2914            size(available_width, AvailableSpace::MinContent),
2915            window,
2916            cx,
2917        );
2918        let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
2919        let final_size = if preliminary_size.height == quantized_height {
2920            preliminary_size
2921        } else {
2922            element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
2923        };
2924        let mut element_height_in_lines = ((final_size.height / line_height).ceil() as u32).max(1);
2925
2926        let mut row = block_row_start;
2927        let mut x_offset = px(0.);
2928        let mut is_block = true;
2929
2930        if let BlockId::Custom(custom_block_id) = block_id {
2931            if block.has_height() {
2932                if block.place_near() {
2933                    if let Some((x_target, line_width)) = x_position {
2934                        let margin = em_width * 2;
2935                        if line_width + final_size.width + margin
2936                            < editor_width + gutter_dimensions.full_width()
2937                            && !row_block_types.contains_key(&(row - 1))
2938                            && element_height_in_lines == 1
2939                        {
2940                            x_offset = line_width + margin;
2941                            row = row - 1;
2942                            is_block = false;
2943                            element_height_in_lines = 0;
2944                            row_block_types.insert(row, is_block);
2945                        } else {
2946                            let max_offset =
2947                                editor_width + gutter_dimensions.full_width() - final_size.width;
2948                            let min_offset = (x_target + em_width - final_size.width)
2949                                .max(gutter_dimensions.full_width());
2950                            x_offset = x_target.min(max_offset).max(min_offset);
2951                        }
2952                    }
2953                };
2954                if element_height_in_lines != block.height() {
2955                    resized_blocks.insert(custom_block_id, element_height_in_lines);
2956                }
2957            }
2958        }
2959        for i in 0..element_height_in_lines {
2960            row_block_types.insert(row + i, is_block);
2961        }
2962
2963        Some((element, final_size, row, x_offset))
2964    }
2965
2966    fn render_buffer_header(
2967        &self,
2968        for_excerpt: &ExcerptInfo,
2969        is_folded: bool,
2970        is_selected: bool,
2971        is_sticky: bool,
2972        jump_data: JumpData,
2973        window: &mut Window,
2974        cx: &mut App,
2975    ) -> Div {
2976        let editor = self.editor.read(cx);
2977        let file_status = editor
2978            .buffer
2979            .read(cx)
2980            .all_diff_hunks_expanded()
2981            .then(|| {
2982                editor
2983                    .project
2984                    .as_ref()?
2985                    .read(cx)
2986                    .status_for_buffer_id(for_excerpt.buffer_id, cx)
2987            })
2988            .flatten();
2989
2990        let include_root = editor
2991            .project
2992            .as_ref()
2993            .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2994            .unwrap_or_default();
2995        let can_open_excerpts = Editor::can_open_excerpts_in_file(for_excerpt.buffer.file());
2996        let path = for_excerpt.buffer.resolve_file_path(cx, include_root);
2997        let filename = path
2998            .as_ref()
2999            .and_then(|path| Some(path.file_name()?.to_string_lossy().to_string()));
3000        let parent_path = path.as_ref().and_then(|path| {
3001            Some(path.parent()?.to_string_lossy().to_string() + std::path::MAIN_SEPARATOR_STR)
3002        });
3003        let focus_handle = editor.focus_handle(cx);
3004        let colors = cx.theme().colors();
3005
3006        div()
3007            .p_1()
3008            .w_full()
3009            .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
3010            .child(
3011                h_flex()
3012                    .size_full()
3013                    .gap_2()
3014                    .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
3015                    .pl_0p5()
3016                    .pr_5()
3017                    .rounded_sm()
3018                    .when(is_sticky, |el| el.shadow_md())
3019                    .border_1()
3020                    .map(|div| {
3021                        let border_color = if is_selected
3022                            && is_folded
3023                            && focus_handle.contains_focused(window, cx)
3024                        {
3025                            colors.border_focused
3026                        } else {
3027                            colors.border
3028                        };
3029                        div.border_color(border_color)
3030                    })
3031                    .bg(colors.editor_subheader_background)
3032                    .hover(|style| style.bg(colors.element_hover))
3033                    .map(|header| {
3034                        let editor = self.editor.clone();
3035                        let buffer_id = for_excerpt.buffer_id;
3036                        let toggle_chevron_icon =
3037                            FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
3038                        header.child(
3039                            div()
3040                                .hover(|style| style.bg(colors.element_selected))
3041                                .rounded_xs()
3042                                .child(
3043                                    ButtonLike::new("toggle-buffer-fold")
3044                                        .style(ui::ButtonStyle::Transparent)
3045                                        .height(px(28.).into())
3046                                        .width(px(28.).into())
3047                                        .children(toggle_chevron_icon)
3048                                        .tooltip({
3049                                            let focus_handle = focus_handle.clone();
3050                                            move |window, cx| {
3051                                                Tooltip::for_action_in(
3052                                                    "Toggle Excerpt Fold",
3053                                                    &ToggleFold,
3054                                                    &focus_handle,
3055                                                    window,
3056                                                    cx,
3057                                                )
3058                                            }
3059                                        })
3060                                        .on_click(move |_, _, cx| {
3061                                            if is_folded {
3062                                                editor.update(cx, |editor, cx| {
3063                                                    editor.unfold_buffer(buffer_id, cx);
3064                                                });
3065                                            } else {
3066                                                editor.update(cx, |editor, cx| {
3067                                                    editor.fold_buffer(buffer_id, cx);
3068                                                });
3069                                            }
3070                                        }),
3071                                ),
3072                        )
3073                    })
3074                    .children(
3075                        editor
3076                            .addons
3077                            .values()
3078                            .filter_map(|addon| {
3079                                addon.render_buffer_header_controls(for_excerpt, window, cx)
3080                            })
3081                            .take(1),
3082                    )
3083                    .child(
3084                        h_flex()
3085                            .cursor_pointer()
3086                            .id("path header block")
3087                            .size_full()
3088                            .justify_between()
3089                            .child(
3090                                h_flex()
3091                                    .gap_2()
3092                                    .child(
3093                                        Label::new(
3094                                            filename
3095                                                .map(SharedString::from)
3096                                                .unwrap_or_else(|| "untitled".into()),
3097                                        )
3098                                        .single_line()
3099                                        .when_some(
3100                                            file_status,
3101                                            |el, status| {
3102                                                el.color(if status.is_conflicted() {
3103                                                    Color::Conflict
3104                                                } else if status.is_modified() {
3105                                                    Color::Modified
3106                                                } else if status.is_deleted() {
3107                                                    Color::Disabled
3108                                                } else {
3109                                                    Color::Created
3110                                                })
3111                                                .when(status.is_deleted(), |el| el.strikethrough())
3112                                            },
3113                                        ),
3114                                    )
3115                                    .when_some(parent_path, |then, path| {
3116                                        then.child(div().child(path).text_color(
3117                                            if file_status.is_some_and(FileStatus::is_deleted) {
3118                                                colors.text_disabled
3119                                            } else {
3120                                                colors.text_muted
3121                                            },
3122                                        ))
3123                                    }),
3124                            )
3125                            .when(can_open_excerpts && is_selected && path.is_some(), |el| {
3126                                el.child(
3127                                    h_flex()
3128                                        .id("jump-to-file-button")
3129                                        .gap_2p5()
3130                                        .child(Label::new("Jump To File"))
3131                                        .children(
3132                                            KeyBinding::for_action_in(
3133                                                &OpenExcerpts,
3134                                                &focus_handle,
3135                                                window,
3136                                                cx,
3137                                            )
3138                                            .map(|binding| binding.into_any_element()),
3139                                        ),
3140                                )
3141                            })
3142                            .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
3143                            .on_click(window.listener_for(&self.editor, {
3144                                move |editor, e: &ClickEvent, window, cx| {
3145                                    editor.open_excerpts_common(
3146                                        Some(jump_data.clone()),
3147                                        e.down.modifiers.secondary(),
3148                                        window,
3149                                        cx,
3150                                    );
3151                                }
3152                            })),
3153                    ),
3154            )
3155    }
3156
3157    fn render_blocks(
3158        &self,
3159        rows: Range<DisplayRow>,
3160        snapshot: &EditorSnapshot,
3161        hitbox: &Hitbox,
3162        text_hitbox: &Hitbox,
3163        editor_width: Pixels,
3164        scroll_width: &mut Pixels,
3165        gutter_dimensions: &GutterDimensions,
3166        em_width: Pixels,
3167        text_x: Pixels,
3168        line_height: Pixels,
3169        line_layouts: &mut [LineWithInvisibles],
3170        selections: &[Selection<Point>],
3171        selected_buffer_ids: &Vec<BufferId>,
3172        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
3173        sticky_header_excerpt_id: Option<ExcerptId>,
3174        window: &mut Window,
3175        cx: &mut App,
3176    ) -> Result<(Vec<BlockLayout>, HashMap<DisplayRow, bool>), HashMap<CustomBlockId, u32>> {
3177        let (fixed_blocks, non_fixed_blocks) = snapshot
3178            .blocks_in_range(rows.clone())
3179            .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
3180
3181        let mut focused_block = self
3182            .editor
3183            .update(cx, |editor, _| editor.take_focused_block());
3184        let mut fixed_block_max_width = Pixels::ZERO;
3185        let mut blocks = Vec::new();
3186        let mut resized_blocks = HashMap::default();
3187        let mut row_block_types = HashMap::default();
3188
3189        for (row, block) in fixed_blocks {
3190            let block_id = block.id();
3191
3192            if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
3193                focused_block = None;
3194            }
3195
3196            if let Some((element, element_size, row, x_offset)) = self.render_block(
3197                block,
3198                AvailableSpace::MinContent,
3199                block_id,
3200                row,
3201                snapshot,
3202                text_x,
3203                &rows,
3204                line_layouts,
3205                gutter_dimensions,
3206                line_height,
3207                em_width,
3208                text_hitbox,
3209                editor_width,
3210                scroll_width,
3211                &mut resized_blocks,
3212                &mut row_block_types,
3213                selections,
3214                selected_buffer_ids,
3215                is_row_soft_wrapped,
3216                sticky_header_excerpt_id,
3217                window,
3218                cx,
3219            ) {
3220                fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
3221                blocks.push(BlockLayout {
3222                    id: block_id,
3223                    x_offset,
3224                    row: Some(row),
3225                    element,
3226                    available_space: size(AvailableSpace::MinContent, element_size.height.into()),
3227                    style: BlockStyle::Fixed,
3228                    overlaps_gutter: true,
3229                    is_buffer_header: block.is_buffer_header(),
3230                });
3231            }
3232        }
3233
3234        for (row, block) in non_fixed_blocks {
3235            let style = block.style();
3236            let width = match (style, block.place_near()) {
3237                (_, true) => AvailableSpace::MinContent,
3238                (BlockStyle::Sticky, _) => hitbox.size.width.into(),
3239                (BlockStyle::Flex, _) => hitbox
3240                    .size
3241                    .width
3242                    .max(fixed_block_max_width)
3243                    .max(gutter_dimensions.width + *scroll_width)
3244                    .into(),
3245                (BlockStyle::Fixed, _) => unreachable!(),
3246            };
3247            let block_id = block.id();
3248
3249            if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
3250                focused_block = None;
3251            }
3252
3253            if let Some((element, element_size, row, x_offset)) = self.render_block(
3254                block,
3255                width,
3256                block_id,
3257                row,
3258                snapshot,
3259                text_x,
3260                &rows,
3261                line_layouts,
3262                gutter_dimensions,
3263                line_height,
3264                em_width,
3265                text_hitbox,
3266                editor_width,
3267                scroll_width,
3268                &mut resized_blocks,
3269                &mut row_block_types,
3270                selections,
3271                selected_buffer_ids,
3272                is_row_soft_wrapped,
3273                sticky_header_excerpt_id,
3274                window,
3275                cx,
3276            ) {
3277                blocks.push(BlockLayout {
3278                    id: block_id,
3279                    x_offset,
3280                    row: Some(row),
3281                    element,
3282                    available_space: size(width, element_size.height.into()),
3283                    style,
3284                    overlaps_gutter: !block.place_near(),
3285                    is_buffer_header: block.is_buffer_header(),
3286                });
3287            }
3288        }
3289
3290        if let Some(focused_block) = focused_block {
3291            if let Some(focus_handle) = focused_block.focus_handle.upgrade() {
3292                if focus_handle.is_focused(window) {
3293                    if let Some(block) = snapshot.block_for_id(focused_block.id) {
3294                        let style = block.style();
3295                        let width = match style {
3296                            BlockStyle::Fixed => AvailableSpace::MinContent,
3297                            BlockStyle::Flex => AvailableSpace::Definite(
3298                                hitbox
3299                                    .size
3300                                    .width
3301                                    .max(fixed_block_max_width)
3302                                    .max(gutter_dimensions.width + *scroll_width),
3303                            ),
3304                            BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
3305                        };
3306
3307                        if let Some((element, element_size, _, x_offset)) = self.render_block(
3308                            &block,
3309                            width,
3310                            focused_block.id,
3311                            rows.end,
3312                            snapshot,
3313                            text_x,
3314                            &rows,
3315                            line_layouts,
3316                            gutter_dimensions,
3317                            line_height,
3318                            em_width,
3319                            text_hitbox,
3320                            editor_width,
3321                            scroll_width,
3322                            &mut resized_blocks,
3323                            &mut row_block_types,
3324                            selections,
3325                            selected_buffer_ids,
3326                            is_row_soft_wrapped,
3327                            sticky_header_excerpt_id,
3328                            window,
3329                            cx,
3330                        ) {
3331                            blocks.push(BlockLayout {
3332                                id: block.id(),
3333                                x_offset,
3334                                row: None,
3335                                element,
3336                                available_space: size(width, element_size.height.into()),
3337                                style,
3338                                overlaps_gutter: true,
3339                                is_buffer_header: block.is_buffer_header(),
3340                            });
3341                        }
3342                    }
3343                }
3344            }
3345        }
3346
3347        if resized_blocks.is_empty() {
3348            *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
3349            Ok((blocks, row_block_types))
3350        } else {
3351            Err(resized_blocks)
3352        }
3353    }
3354
3355    fn layout_blocks(
3356        &self,
3357        blocks: &mut Vec<BlockLayout>,
3358        hitbox: &Hitbox,
3359        line_height: Pixels,
3360        scroll_pixel_position: gpui::Point<Pixels>,
3361        window: &mut Window,
3362        cx: &mut App,
3363    ) {
3364        for block in blocks {
3365            let mut origin = if let Some(row) = block.row {
3366                hitbox.origin
3367                    + point(
3368                        block.x_offset,
3369                        row.as_f32() * line_height - scroll_pixel_position.y,
3370                    )
3371            } else {
3372                // Position the block outside the visible area
3373                hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
3374            };
3375
3376            if !matches!(block.style, BlockStyle::Sticky) {
3377                origin += point(-scroll_pixel_position.x, Pixels::ZERO);
3378            }
3379
3380            let focus_handle =
3381                block
3382                    .element
3383                    .prepaint_as_root(origin, block.available_space, window, cx);
3384
3385            if let Some(focus_handle) = focus_handle {
3386                self.editor.update(cx, |editor, _cx| {
3387                    editor.set_focused_block(FocusedBlock {
3388                        id: block.id,
3389                        focus_handle: focus_handle.downgrade(),
3390                    });
3391                });
3392            }
3393        }
3394    }
3395
3396    fn layout_sticky_buffer_header(
3397        &self,
3398        StickyHeaderExcerpt { excerpt }: StickyHeaderExcerpt<'_>,
3399        scroll_position: f32,
3400        line_height: Pixels,
3401        snapshot: &EditorSnapshot,
3402        hitbox: &Hitbox,
3403        selected_buffer_ids: &Vec<BufferId>,
3404        blocks: &[BlockLayout],
3405        window: &mut Window,
3406        cx: &mut App,
3407    ) -> AnyElement {
3408        let jump_data = header_jump_data(
3409            snapshot,
3410            DisplayRow(scroll_position as u32),
3411            FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
3412            excerpt,
3413        );
3414
3415        let editor_bg_color = cx.theme().colors().editor_background;
3416
3417        let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
3418
3419        let mut header = v_flex()
3420            .relative()
3421            .child(
3422                div()
3423                    .w(hitbox.bounds.size.width)
3424                    .h(FILE_HEADER_HEIGHT as f32 * line_height)
3425                    .bg(linear_gradient(
3426                        0.,
3427                        linear_color_stop(editor_bg_color.opacity(0.), 0.),
3428                        linear_color_stop(editor_bg_color, 0.6),
3429                    ))
3430                    .absolute()
3431                    .top_0(),
3432            )
3433            .child(
3434                self.render_buffer_header(excerpt, false, selected, true, jump_data, window, cx)
3435                    .into_any_element(),
3436            )
3437            .into_any_element();
3438
3439        let mut origin = hitbox.origin;
3440        // Move floating header up to avoid colliding with the next buffer header.
3441        for block in blocks.iter() {
3442            if !block.is_buffer_header {
3443                continue;
3444            }
3445
3446            let Some(display_row) = block.row.filter(|row| row.0 > scroll_position as u32) else {
3447                continue;
3448            };
3449
3450            let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
3451            let offset = scroll_position - max_row as f32;
3452
3453            if offset > 0.0 {
3454                origin.y -= offset * line_height;
3455            }
3456            break;
3457        }
3458
3459        let size = size(
3460            AvailableSpace::Definite(hitbox.size.width),
3461            AvailableSpace::MinContent,
3462        );
3463
3464        header.prepaint_as_root(origin, size, window, cx);
3465
3466        header
3467    }
3468
3469    fn layout_cursor_popovers(
3470        &self,
3471        line_height: Pixels,
3472        text_hitbox: &Hitbox,
3473        content_origin: gpui::Point<Pixels>,
3474        start_row: DisplayRow,
3475        scroll_pixel_position: gpui::Point<Pixels>,
3476        line_layouts: &[LineWithInvisibles],
3477        cursor: DisplayPoint,
3478        cursor_point: Point,
3479        style: &EditorStyle,
3480        window: &mut Window,
3481        cx: &mut App,
3482    ) {
3483        let mut min_menu_height = Pixels::ZERO;
3484        let mut max_menu_height = Pixels::ZERO;
3485        let mut height_above_menu = Pixels::ZERO;
3486        let height_below_menu = Pixels::ZERO;
3487        let mut edit_prediction_popover_visible = false;
3488        let mut context_menu_visible = false;
3489        let context_menu_placement;
3490
3491        {
3492            let editor = self.editor.read(cx);
3493            if editor
3494                .edit_prediction_visible_in_cursor_popover(editor.has_active_inline_completion())
3495            {
3496                height_above_menu +=
3497                    editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
3498                edit_prediction_popover_visible = true;
3499            }
3500
3501            if editor.context_menu_visible() {
3502                if let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin() {
3503                    let (min_height_in_lines, max_height_in_lines) = editor
3504                        .context_menu_options
3505                        .as_ref()
3506                        .map_or((3, 12), |options| {
3507                            (options.min_entries_visible, options.max_entries_visible)
3508                        });
3509
3510                    min_menu_height += line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
3511                    max_menu_height += line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
3512                    context_menu_visible = true;
3513                }
3514            }
3515            context_menu_placement = editor
3516                .context_menu_options
3517                .as_ref()
3518                .and_then(|options| options.placement.clone());
3519        }
3520
3521        let visible = edit_prediction_popover_visible || context_menu_visible;
3522        if !visible {
3523            return;
3524        }
3525
3526        let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
3527        let target_position = content_origin
3528            + gpui::Point {
3529                x: cmp::max(
3530                    px(0.),
3531                    cursor_row_layout.x_for_index(cursor.column() as usize)
3532                        - scroll_pixel_position.x,
3533                ),
3534                y: cmp::max(
3535                    px(0.),
3536                    cursor.row().next_row().as_f32() * line_height - scroll_pixel_position.y,
3537                ),
3538            };
3539
3540        let viewport_bounds =
3541            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3542                right: -Self::SCROLLBAR_WIDTH - MENU_GAP,
3543                ..Default::default()
3544            });
3545
3546        let min_height = height_above_menu + min_menu_height + height_below_menu;
3547        let max_height = height_above_menu + max_menu_height + height_below_menu;
3548        let Some((laid_out_popovers, y_flipped)) = self.layout_popovers_above_or_below_line(
3549            target_position,
3550            line_height,
3551            min_height,
3552            max_height,
3553            context_menu_placement,
3554            text_hitbox,
3555            viewport_bounds,
3556            window,
3557            cx,
3558            |height, max_width_for_stable_x, y_flipped, window, cx| {
3559                // First layout the menu to get its size - others can be at least this wide.
3560                let context_menu = if context_menu_visible {
3561                    let menu_height = if y_flipped {
3562                        height - height_below_menu
3563                    } else {
3564                        height - height_above_menu
3565                    };
3566                    let mut element = self
3567                        .render_context_menu(line_height, menu_height, window, cx)
3568                        .expect("Visible context menu should always render.");
3569                    let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3570                    Some((CursorPopoverType::CodeContextMenu, element, size))
3571                } else {
3572                    None
3573                };
3574                let min_width = context_menu
3575                    .as_ref()
3576                    .map_or(px(0.), |(_, _, size)| size.width);
3577                let max_width = max_width_for_stable_x.max(
3578                    context_menu
3579                        .as_ref()
3580                        .map_or(px(0.), |(_, _, size)| size.width),
3581                );
3582
3583                let edit_prediction = if edit_prediction_popover_visible {
3584                    self.editor.update(cx, move |editor, cx| {
3585                        let accept_binding = editor.accept_edit_prediction_keybind(window, cx);
3586                        let mut element = editor.render_edit_prediction_cursor_popover(
3587                            min_width,
3588                            max_width,
3589                            cursor_point,
3590                            style,
3591                            accept_binding.keystroke(),
3592                            window,
3593                            cx,
3594                        )?;
3595                        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3596                        Some((CursorPopoverType::EditPrediction, element, size))
3597                    })
3598                } else {
3599                    None
3600                };
3601                vec![edit_prediction, context_menu]
3602                    .into_iter()
3603                    .flatten()
3604                    .collect::<Vec<_>>()
3605            },
3606        ) else {
3607            return;
3608        };
3609
3610        let Some((menu_ix, (_, menu_bounds))) = laid_out_popovers
3611            .iter()
3612            .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))
3613        else {
3614            return;
3615        };
3616        let last_ix = laid_out_popovers.len() - 1;
3617        let menu_is_last = menu_ix == last_ix;
3618        let first_popover_bounds = laid_out_popovers[0].1;
3619        let last_popover_bounds = laid_out_popovers[last_ix].1;
3620
3621        // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
3622        // right, and otherwise it goes below or to the right.
3623        let mut target_bounds = Bounds::from_corners(
3624            first_popover_bounds.origin,
3625            last_popover_bounds.bottom_right(),
3626        );
3627        target_bounds.size.width = menu_bounds.size.width;
3628
3629        // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
3630        // based on this is preferred for layout stability.
3631        let mut max_target_bounds = target_bounds;
3632        max_target_bounds.size.height = max_height;
3633        if y_flipped {
3634            max_target_bounds.origin.y -= max_height - target_bounds.size.height;
3635        }
3636
3637        // Add spacing around `target_bounds` and `max_target_bounds`.
3638        let mut extend_amount = Edges::all(MENU_GAP);
3639        if y_flipped {
3640            extend_amount.bottom = line_height;
3641        } else {
3642            extend_amount.top = line_height;
3643        }
3644        let target_bounds = target_bounds.extend(extend_amount);
3645        let max_target_bounds = max_target_bounds.extend(extend_amount);
3646
3647        let must_place_above_or_below =
3648            if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
3649                laid_out_popovers[menu_ix + 1..]
3650                    .iter()
3651                    .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
3652            } else {
3653                false
3654            };
3655
3656        self.layout_context_menu_aside(
3657            y_flipped,
3658            *menu_bounds,
3659            target_bounds,
3660            max_target_bounds,
3661            max_menu_height,
3662            must_place_above_or_below,
3663            text_hitbox,
3664            viewport_bounds,
3665            window,
3666            cx,
3667        );
3668    }
3669
3670    fn layout_gutter_menu(
3671        &self,
3672        line_height: Pixels,
3673        text_hitbox: &Hitbox,
3674        content_origin: gpui::Point<Pixels>,
3675        scroll_pixel_position: gpui::Point<Pixels>,
3676        gutter_overshoot: Pixels,
3677        window: &mut Window,
3678        cx: &mut App,
3679    ) {
3680        let editor = self.editor.read(cx);
3681        if !editor.context_menu_visible() {
3682            return;
3683        }
3684        let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
3685            editor.context_menu_origin()
3686        else {
3687            return;
3688        };
3689        // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
3690        // indicator than just a plain first column of the text field.
3691        let target_position = content_origin
3692            + gpui::Point {
3693                x: -gutter_overshoot,
3694                y: gutter_row.next_row().as_f32() * line_height - scroll_pixel_position.y,
3695            };
3696
3697        let (min_height_in_lines, max_height_in_lines) = editor
3698            .context_menu_options
3699            .as_ref()
3700            .map_or((3, 12), |options| {
3701                (options.min_entries_visible, options.max_entries_visible)
3702            });
3703
3704        let min_height = line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
3705        let max_height = line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
3706        let viewport_bounds =
3707            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3708                right: -Self::SCROLLBAR_WIDTH - MENU_GAP,
3709                ..Default::default()
3710            });
3711        self.layout_popovers_above_or_below_line(
3712            target_position,
3713            line_height,
3714            min_height,
3715            max_height,
3716            editor
3717                .context_menu_options
3718                .as_ref()
3719                .and_then(|options| options.placement.clone()),
3720            text_hitbox,
3721            viewport_bounds,
3722            window,
3723            cx,
3724            move |height, _max_width_for_stable_x, _, window, cx| {
3725                let mut element = self
3726                    .render_context_menu(line_height, height, window, cx)
3727                    .expect("Visible context menu should always render.");
3728                let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3729                vec![(CursorPopoverType::CodeContextMenu, element, size)]
3730            },
3731        );
3732    }
3733
3734    fn layout_popovers_above_or_below_line(
3735        &self,
3736        target_position: gpui::Point<Pixels>,
3737        line_height: Pixels,
3738        min_height: Pixels,
3739        max_height: Pixels,
3740        placement: Option<ContextMenuPlacement>,
3741        text_hitbox: &Hitbox,
3742        viewport_bounds: Bounds<Pixels>,
3743        window: &mut Window,
3744        cx: &mut App,
3745        make_sized_popovers: impl FnOnce(
3746            Pixels,
3747            Pixels,
3748            bool,
3749            &mut Window,
3750            &mut App,
3751        ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
3752    ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
3753        let text_style = TextStyleRefinement {
3754            line_height: Some(DefiniteLength::Fraction(
3755                BufferLineHeight::Comfortable.value(),
3756            )),
3757            ..Default::default()
3758        };
3759        window.with_text_style(Some(text_style), |window| {
3760            // If the max height won't fit below and there is more space above, put it above the line.
3761            let bottom_y_when_flipped = target_position.y - line_height;
3762            let available_above = bottom_y_when_flipped - text_hitbox.top();
3763            let available_below = text_hitbox.bottom() - target_position.y;
3764            let y_overflows_below = max_height > available_below;
3765            let mut y_flipped = match placement {
3766                Some(ContextMenuPlacement::Above) => true,
3767                Some(ContextMenuPlacement::Below) => false,
3768                None => y_overflows_below && available_above > available_below,
3769            };
3770            let mut height = cmp::min(
3771                max_height,
3772                if y_flipped {
3773                    available_above
3774                } else {
3775                    available_below
3776                },
3777            );
3778
3779            // If the min height doesn't fit within text bounds, instead fit within the window.
3780            if height < min_height {
3781                let available_above = bottom_y_when_flipped;
3782                let available_below = viewport_bounds.bottom() - target_position.y;
3783                let (y_flipped_override, height_override) = match placement {
3784                    Some(ContextMenuPlacement::Above) => {
3785                        (true, cmp::min(available_above, min_height))
3786                    }
3787                    Some(ContextMenuPlacement::Below) => {
3788                        (false, cmp::min(available_below, min_height))
3789                    }
3790                    None => {
3791                        if available_below > min_height {
3792                            (false, min_height)
3793                        } else if available_above > min_height {
3794                            (true, min_height)
3795                        } else if available_above > available_below {
3796                            (true, available_above)
3797                        } else {
3798                            (false, available_below)
3799                        }
3800                    }
3801                };
3802                y_flipped = y_flipped_override;
3803                height = height_override;
3804            }
3805
3806            let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
3807
3808            // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
3809            // for very narrow windows.
3810            let popovers =
3811                make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
3812            if popovers.is_empty() {
3813                return None;
3814            }
3815
3816            let max_width = popovers
3817                .iter()
3818                .map(|(_, _, size)| size.width)
3819                .max()
3820                .unwrap_or_default();
3821
3822            let mut current_position = gpui::Point {
3823                // Snap the right edge of the list to the right edge of the window if its horizontal bounds
3824                // overflow. Include space for the scrollbar.
3825                x: target_position
3826                    .x
3827                    .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
3828                y: if y_flipped {
3829                    bottom_y_when_flipped
3830                } else {
3831                    target_position.y
3832                },
3833            };
3834
3835            let mut laid_out_popovers = popovers
3836                .into_iter()
3837                .map(|(popover_type, element, size)| {
3838                    if y_flipped {
3839                        current_position.y -= size.height;
3840                    }
3841                    let position = current_position;
3842                    window.defer_draw(element, current_position, 1);
3843                    if !y_flipped {
3844                        current_position.y += size.height + MENU_GAP;
3845                    } else {
3846                        current_position.y -= MENU_GAP;
3847                    }
3848                    (popover_type, Bounds::new(position, size))
3849                })
3850                .collect::<Vec<_>>();
3851
3852            if y_flipped {
3853                laid_out_popovers.reverse();
3854            }
3855
3856            Some((laid_out_popovers, y_flipped))
3857        })
3858    }
3859
3860    fn layout_context_menu_aside(
3861        &self,
3862        y_flipped: bool,
3863        menu_bounds: Bounds<Pixels>,
3864        target_bounds: Bounds<Pixels>,
3865        max_target_bounds: Bounds<Pixels>,
3866        max_height: Pixels,
3867        must_place_above_or_below: bool,
3868        text_hitbox: &Hitbox,
3869        viewport_bounds: Bounds<Pixels>,
3870        window: &mut Window,
3871        cx: &mut App,
3872    ) {
3873        let available_within_viewport = target_bounds.space_within(&viewport_bounds);
3874        let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
3875            && !must_place_above_or_below
3876        {
3877            let max_width = cmp::min(
3878                available_within_viewport.right - px(1.),
3879                MENU_ASIDE_MAX_WIDTH,
3880            );
3881            let Some(mut aside) = self.render_context_menu_aside(
3882                size(max_width, max_height - POPOVER_Y_PADDING),
3883                window,
3884                cx,
3885            ) else {
3886                return;
3887            };
3888            aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3889            let right_position = point(target_bounds.right(), menu_bounds.origin.y);
3890            Some((aside, right_position))
3891        } else {
3892            let max_size = size(
3893                // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
3894                // won't be needed here.
3895                cmp::min(
3896                    cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
3897                    viewport_bounds.right(),
3898                ),
3899                cmp::min(
3900                    max_height,
3901                    cmp::max(
3902                        available_within_viewport.top,
3903                        available_within_viewport.bottom,
3904                    ),
3905                ) - POPOVER_Y_PADDING,
3906            );
3907            let Some(mut aside) = self.render_context_menu_aside(max_size, window, cx) else {
3908                return;
3909            };
3910            let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3911
3912            let top_position = point(
3913                menu_bounds.origin.x,
3914                target_bounds.top() - actual_size.height,
3915            );
3916            let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
3917
3918            let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
3919                // Prefer to fit on the same side of the line as the menu, then on the other side of
3920                // the line.
3921                if !y_flipped && wanted.height < available.bottom {
3922                    Some(bottom_position)
3923                } else if !y_flipped && wanted.height < available.top {
3924                    Some(top_position)
3925                } else if y_flipped && wanted.height < available.top {
3926                    Some(top_position)
3927                } else if y_flipped && wanted.height < available.bottom {
3928                    Some(bottom_position)
3929                } else {
3930                    None
3931                }
3932            };
3933
3934            // Prefer choosing a direction using max sizes rather than actual size for stability.
3935            let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
3936            let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
3937            let aside_position = fit_within(available_within_text, wanted)
3938                // Fallback: fit max size in window.
3939                .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
3940                // Fallback: fit actual size in window.
3941                .or_else(|| fit_within(available_within_viewport, actual_size));
3942
3943            aside_position.map(|position| (aside, position))
3944        };
3945
3946        // Skip drawing if it doesn't fit anywhere.
3947        if let Some((aside, position)) = positioned_aside {
3948            window.defer_draw(aside, position, 2);
3949        }
3950    }
3951
3952    fn render_context_menu(
3953        &self,
3954        line_height: Pixels,
3955        height: Pixels,
3956        window: &mut Window,
3957        cx: &mut App,
3958    ) -> Option<AnyElement> {
3959        let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
3960        self.editor.update(cx, |editor, cx| {
3961            editor.render_context_menu(&self.style, max_height_in_lines, window, cx)
3962        })
3963    }
3964
3965    fn render_context_menu_aside(
3966        &self,
3967        max_size: Size<Pixels>,
3968        window: &mut Window,
3969        cx: &mut App,
3970    ) -> Option<AnyElement> {
3971        if max_size.width < px(100.) || max_size.height < px(12.) {
3972            None
3973        } else {
3974            self.editor.update(cx, |editor, cx| {
3975                editor.render_context_menu_aside(max_size, window, cx)
3976            })
3977        }
3978    }
3979
3980    fn layout_mouse_context_menu(
3981        &self,
3982        editor_snapshot: &EditorSnapshot,
3983        visible_range: Range<DisplayRow>,
3984        content_origin: gpui::Point<Pixels>,
3985        window: &mut Window,
3986        cx: &mut App,
3987    ) -> Option<AnyElement> {
3988        let position = self.editor.update(cx, |editor, _cx| {
3989            let visible_start_point = editor.display_to_pixel_point(
3990                DisplayPoint::new(visible_range.start, 0),
3991                editor_snapshot,
3992                window,
3993            )?;
3994            let visible_end_point = editor.display_to_pixel_point(
3995                DisplayPoint::new(visible_range.end, 0),
3996                editor_snapshot,
3997                window,
3998            )?;
3999
4000            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
4001            let (source_display_point, position) = match mouse_context_menu.position {
4002                MenuPosition::PinnedToScreen(point) => (None, point),
4003                MenuPosition::PinnedToEditor { source, offset } => {
4004                    let source_display_point = source.to_display_point(editor_snapshot);
4005                    let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
4006                    let position = content_origin + source_point + offset;
4007                    (Some(source_display_point), position)
4008                }
4009            };
4010
4011            let source_included = source_display_point.map_or(true, |source_display_point| {
4012                visible_range
4013                    .to_inclusive()
4014                    .contains(&source_display_point.row())
4015            });
4016            let position_included =
4017                visible_start_point.y <= position.y && position.y <= visible_end_point.y;
4018            if !source_included && !position_included {
4019                None
4020            } else {
4021                Some(position)
4022            }
4023        })?;
4024
4025        let text_style = TextStyleRefinement {
4026            line_height: Some(DefiniteLength::Fraction(
4027                BufferLineHeight::Comfortable.value(),
4028            )),
4029            ..Default::default()
4030        };
4031        window.with_text_style(Some(text_style), |window| {
4032            let mut element = self.editor.update(cx, |editor, _| {
4033                let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
4034                let context_menu = mouse_context_menu.context_menu.clone();
4035
4036                Some(
4037                    deferred(
4038                        anchored()
4039                            .position(position)
4040                            .child(context_menu)
4041                            .anchor(Corner::TopLeft)
4042                            .snap_to_window_with_margin(px(8.)),
4043                    )
4044                    .with_priority(1)
4045                    .into_any(),
4046                )
4047            })?;
4048
4049            element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
4050            Some(element)
4051        })
4052    }
4053
4054    fn layout_hover_popovers(
4055        &self,
4056        snapshot: &EditorSnapshot,
4057        hitbox: &Hitbox,
4058        text_hitbox: &Hitbox,
4059        visible_display_row_range: Range<DisplayRow>,
4060        content_origin: gpui::Point<Pixels>,
4061        scroll_pixel_position: gpui::Point<Pixels>,
4062        line_layouts: &[LineWithInvisibles],
4063        line_height: Pixels,
4064        em_width: Pixels,
4065        window: &mut Window,
4066        cx: &mut App,
4067    ) {
4068        struct MeasuredHoverPopover {
4069            element: AnyElement,
4070            size: Size<Pixels>,
4071            horizontal_offset: Pixels,
4072        }
4073
4074        let max_size = size(
4075            (120. * em_width) // Default size
4076                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4077                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4078            (16. * line_height) // Default size
4079                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4080                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4081        );
4082
4083        let hover_popovers = self.editor.update(cx, |editor, cx| {
4084            editor.hover_state.render(
4085                snapshot,
4086                visible_display_row_range.clone(),
4087                max_size,
4088                window,
4089                cx,
4090            )
4091        });
4092        let Some((position, hover_popovers)) = hover_popovers else {
4093            return;
4094        };
4095
4096        // This is safe because we check on layout whether the required row is available
4097        let hovered_row_layout =
4098            &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
4099
4100        // Compute Hovered Point
4101        let x =
4102            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
4103        let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
4104        let hovered_point = content_origin + point(x, y);
4105
4106        let mut overall_height = Pixels::ZERO;
4107        let mut measured_hover_popovers = Vec::new();
4108        for mut hover_popover in hover_popovers {
4109            let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
4110            let horizontal_offset =
4111                (text_hitbox.top_right().x - POPOVER_RIGHT_OFFSET - (hovered_point.x + size.width))
4112                    .min(Pixels::ZERO);
4113
4114            overall_height += HOVER_POPOVER_GAP + size.height;
4115
4116            measured_hover_popovers.push(MeasuredHoverPopover {
4117                element: hover_popover,
4118                size,
4119                horizontal_offset,
4120            });
4121        }
4122        overall_height += HOVER_POPOVER_GAP;
4123
4124        fn draw_occluder(
4125            width: Pixels,
4126            origin: gpui::Point<Pixels>,
4127            window: &mut Window,
4128            cx: &mut App,
4129        ) {
4130            let mut occlusion = div()
4131                .size_full()
4132                .occlude()
4133                .on_mouse_move(|_, _, cx| cx.stop_propagation())
4134                .into_any_element();
4135            occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
4136            window.defer_draw(occlusion, origin, 2);
4137        }
4138
4139        if hovered_point.y > overall_height {
4140            // There is enough space above. Render popovers above the hovered point
4141            let mut current_y = hovered_point.y;
4142            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4143                let size = popover.size;
4144                let popover_origin = point(
4145                    hovered_point.x + popover.horizontal_offset,
4146                    current_y - size.height,
4147                );
4148
4149                window.defer_draw(popover.element, popover_origin, 2);
4150                if position != itertools::Position::Last {
4151                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
4152                    draw_occluder(size.width, origin, window, cx);
4153                }
4154
4155                current_y = popover_origin.y - HOVER_POPOVER_GAP;
4156            }
4157        } else {
4158            // There is not enough space above. Render popovers below the hovered point
4159            let mut current_y = hovered_point.y + line_height;
4160            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4161                let size = popover.size;
4162                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
4163
4164                window.defer_draw(popover.element, popover_origin, 2);
4165                if position != itertools::Position::Last {
4166                    let origin = point(popover_origin.x, popover_origin.y + size.height);
4167                    draw_occluder(size.width, origin, window, cx);
4168                }
4169
4170                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
4171            }
4172        }
4173    }
4174
4175    fn layout_diff_hunk_controls(
4176        &self,
4177        row_range: Range<DisplayRow>,
4178        row_infos: &[RowInfo],
4179        text_hitbox: &Hitbox,
4180        position_map: &PositionMap,
4181        newest_cursor_position: Option<DisplayPoint>,
4182        line_height: Pixels,
4183        scroll_pixel_position: gpui::Point<Pixels>,
4184        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
4185        highlighted_rows: &BTreeMap<DisplayRow, LineHighlight>,
4186        editor: Entity<Editor>,
4187        window: &mut Window,
4188        cx: &mut App,
4189    ) -> Vec<AnyElement> {
4190        let render_diff_hunk_controls = editor.read(cx).render_diff_hunk_controls.clone();
4191        let point_for_position = position_map.point_for_position(window.mouse_position());
4192
4193        let mut controls = vec![];
4194
4195        let active_positions = [
4196            Some(point_for_position.previous_valid),
4197            newest_cursor_position,
4198        ];
4199
4200        for (hunk, _) in display_hunks {
4201            if let DisplayDiffHunk::Unfolded {
4202                display_row_range,
4203                multi_buffer_range,
4204                status,
4205                is_created_file,
4206                ..
4207            } = &hunk
4208            {
4209                if display_row_range.start < row_range.start
4210                    || display_row_range.start >= row_range.end
4211                {
4212                    continue;
4213                }
4214                if highlighted_rows
4215                    .get(&display_row_range.start)
4216                    .and_then(|highlight| highlight.type_id)
4217                    .is_some_and(|type_id| {
4218                        [
4219                            TypeId::of::<ConflictsOuter>(),
4220                            TypeId::of::<ConflictsOursMarker>(),
4221                            TypeId::of::<ConflictsOurs>(),
4222                            TypeId::of::<ConflictsTheirs>(),
4223                            TypeId::of::<ConflictsTheirsMarker>(),
4224                        ]
4225                        .contains(&type_id)
4226                    })
4227                {
4228                    continue;
4229                }
4230                let row_ix = (display_row_range.start - row_range.start).0 as usize;
4231                if row_infos[row_ix].diff_status.is_none() {
4232                    continue;
4233                }
4234                if row_infos[row_ix]
4235                    .diff_status
4236                    .is_some_and(|status| status.is_added())
4237                    && !status.is_added()
4238                {
4239                    continue;
4240                }
4241                if active_positions
4242                    .iter()
4243                    .any(|p| p.map_or(false, |p| display_row_range.contains(&p.row())))
4244                {
4245                    let y = display_row_range.start.as_f32() * line_height
4246                        + text_hitbox.bounds.top()
4247                        - scroll_pixel_position.y;
4248
4249                    let mut element = render_diff_hunk_controls(
4250                        display_row_range.start.0,
4251                        status,
4252                        multi_buffer_range.clone(),
4253                        *is_created_file,
4254                        line_height,
4255                        &editor,
4256                        window,
4257                        cx,
4258                    );
4259                    let size =
4260                        element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
4261
4262                    let x = text_hitbox.bounds.right()
4263                        - self.style.scrollbar_width
4264                        - px(10.)
4265                        - size.width;
4266
4267                    window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
4268                        element.prepaint(window, cx)
4269                    });
4270                    controls.push(element);
4271                }
4272            }
4273        }
4274
4275        controls
4276    }
4277
4278    fn layout_signature_help(
4279        &self,
4280        hitbox: &Hitbox,
4281        text_hitbox: &Hitbox,
4282        content_origin: gpui::Point<Pixels>,
4283        scroll_pixel_position: gpui::Point<Pixels>,
4284        newest_selection_head: Option<DisplayPoint>,
4285        start_row: DisplayRow,
4286        line_layouts: &[LineWithInvisibles],
4287        line_height: Pixels,
4288        em_width: Pixels,
4289        window: &mut Window,
4290        cx: &mut App,
4291    ) {
4292        if !self.editor.focus_handle(cx).is_focused(window) {
4293            return;
4294        }
4295        let Some(newest_selection_head) = newest_selection_head else {
4296            return;
4297        };
4298
4299        let max_size = size(
4300            (120. * em_width) // Default size
4301                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4302                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4303            (16. * line_height) // Default size
4304                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4305                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4306        );
4307
4308        let maybe_element = self.editor.update(cx, |editor, cx| {
4309            if let Some(popover) = editor.signature_help_state.popover_mut() {
4310                let element = popover.render(max_size, cx);
4311                Some(element)
4312            } else {
4313                None
4314            }
4315        });
4316        let Some(mut element) = maybe_element else {
4317            return;
4318        };
4319
4320        let selection_row = newest_selection_head.row();
4321        let Some(cursor_row_layout) = (selection_row >= start_row)
4322            .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
4323            .flatten()
4324        else {
4325            return;
4326        };
4327
4328        let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
4329            - scroll_pixel_position.x;
4330        let target_y = selection_row.as_f32() * line_height - scroll_pixel_position.y;
4331        let target_point = content_origin + point(target_x, target_y);
4332
4333        let actual_size = element.layout_as_root(max_size.into(), window, cx);
4334        let overall_height = actual_size.height + HOVER_POPOVER_GAP;
4335
4336        let popover_origin = if target_point.y > overall_height {
4337            point(target_point.x, target_point.y - actual_size.height)
4338        } else {
4339            point(
4340                target_point.x,
4341                target_point.y + line_height + HOVER_POPOVER_GAP,
4342            )
4343        };
4344
4345        let horizontal_offset = (text_hitbox.top_right().x
4346            - POPOVER_RIGHT_OFFSET
4347            - (popover_origin.x + actual_size.width))
4348            .min(Pixels::ZERO);
4349        let final_origin = point(popover_origin.x + horizontal_offset, popover_origin.y);
4350
4351        window.defer_draw(element, final_origin, 2);
4352    }
4353
4354    fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
4355        window.paint_layer(layout.hitbox.bounds, |window| {
4356            let scroll_top = layout.position_map.snapshot.scroll_position().y;
4357            let gutter_bg = cx.theme().colors().editor_gutter_background;
4358            window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
4359            window.paint_quad(fill(
4360                layout.position_map.text_hitbox.bounds,
4361                self.style.background,
4362            ));
4363
4364            if let EditorMode::Full {
4365                show_active_line_background,
4366                ..
4367            } = layout.mode
4368            {
4369                let mut active_rows = layout.active_rows.iter().peekable();
4370                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
4371                    let mut end_row = start_row.0;
4372                    while active_rows
4373                        .peek()
4374                        .map_or(false, |(active_row, has_selection)| {
4375                            active_row.0 == end_row + 1
4376                                && has_selection.selection == contains_non_empty_selection.selection
4377                        })
4378                    {
4379                        active_rows.next().unwrap();
4380                        end_row += 1;
4381                    }
4382
4383                    if show_active_line_background && !contains_non_empty_selection.selection {
4384                        let highlight_h_range =
4385                            match layout.position_map.snapshot.current_line_highlight {
4386                                CurrentLineHighlight::Gutter => Some(Range {
4387                                    start: layout.hitbox.left(),
4388                                    end: layout.gutter_hitbox.right(),
4389                                }),
4390                                CurrentLineHighlight::Line => Some(Range {
4391                                    start: layout.position_map.text_hitbox.bounds.left(),
4392                                    end: layout.position_map.text_hitbox.bounds.right(),
4393                                }),
4394                                CurrentLineHighlight::All => Some(Range {
4395                                    start: layout.hitbox.left(),
4396                                    end: layout.hitbox.right(),
4397                                }),
4398                                CurrentLineHighlight::None => None,
4399                            };
4400                        if let Some(range) = highlight_h_range {
4401                            let active_line_bg = cx.theme().colors().editor_active_line_background;
4402                            let bounds = Bounds {
4403                                origin: point(
4404                                    range.start,
4405                                    layout.hitbox.origin.y
4406                                        + (start_row.as_f32() - scroll_top)
4407                                            * layout.position_map.line_height,
4408                                ),
4409                                size: size(
4410                                    range.end - range.start,
4411                                    layout.position_map.line_height
4412                                        * (end_row - start_row.0 + 1) as f32,
4413                                ),
4414                            };
4415                            window.paint_quad(fill(bounds, active_line_bg));
4416                        }
4417                    }
4418                }
4419
4420                let mut paint_highlight = |highlight_row_start: DisplayRow,
4421                                           highlight_row_end: DisplayRow,
4422                                           highlight: crate::LineHighlight,
4423                                           edges| {
4424                    let mut origin_x = layout.hitbox.left();
4425                    let mut width = layout.hitbox.size.width;
4426                    if !highlight.include_gutter {
4427                        origin_x += layout.gutter_hitbox.size.width;
4428                        width -= layout.gutter_hitbox.size.width;
4429                    }
4430
4431                    let origin = point(
4432                        origin_x,
4433                        layout.hitbox.origin.y
4434                            + (highlight_row_start.as_f32() - scroll_top)
4435                                * layout.position_map.line_height,
4436                    );
4437                    let size = size(
4438                        width,
4439                        layout.position_map.line_height
4440                            * highlight_row_end.next_row().minus(highlight_row_start) as f32,
4441                    );
4442                    let mut quad = fill(Bounds { origin, size }, highlight.background);
4443                    if let Some(border_color) = highlight.border {
4444                        quad.border_color = border_color;
4445                        quad.border_widths = edges
4446                    }
4447                    window.paint_quad(quad);
4448                };
4449
4450                let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
4451                    None;
4452                for (&new_row, &new_background) in &layout.highlighted_rows {
4453                    match &mut current_paint {
4454                        &mut Some((current_background, ref mut current_range, mut edges)) => {
4455                            let new_range_started = current_background != new_background
4456                                || current_range.end.next_row() != new_row;
4457                            if new_range_started {
4458                                if current_range.end.next_row() == new_row {
4459                                    edges.bottom = px(0.);
4460                                };
4461                                paint_highlight(
4462                                    current_range.start,
4463                                    current_range.end,
4464                                    current_background,
4465                                    edges,
4466                                );
4467                                let edges = Edges {
4468                                    top: if current_range.end.next_row() != new_row {
4469                                        px(1.)
4470                                    } else {
4471                                        px(0.)
4472                                    },
4473                                    bottom: px(1.),
4474                                    ..Default::default()
4475                                };
4476                                current_paint = Some((new_background, new_row..new_row, edges));
4477                                continue;
4478                            } else {
4479                                current_range.end = current_range.end.next_row();
4480                            }
4481                        }
4482                        None => {
4483                            let edges = Edges {
4484                                top: px(1.),
4485                                bottom: px(1.),
4486                                ..Default::default()
4487                            };
4488                            current_paint = Some((new_background, new_row..new_row, edges))
4489                        }
4490                    };
4491                }
4492                if let Some((color, range, edges)) = current_paint {
4493                    paint_highlight(range.start, range.end, color, edges);
4494                }
4495
4496                let scroll_left =
4497                    layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
4498
4499                for (wrap_position, active) in layout.wrap_guides.iter() {
4500                    let x = (layout.position_map.text_hitbox.origin.x
4501                        + *wrap_position
4502                        + layout.position_map.em_width / 2.)
4503                        - scroll_left;
4504
4505                    let show_scrollbars = layout
4506                        .scrollbars_layout
4507                        .as_ref()
4508                        .map_or(false, |layout| layout.visible);
4509
4510                    if x < layout.position_map.text_hitbox.origin.x
4511                        || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
4512                    {
4513                        continue;
4514                    }
4515
4516                    let color = if *active {
4517                        cx.theme().colors().editor_active_wrap_guide
4518                    } else {
4519                        cx.theme().colors().editor_wrap_guide
4520                    };
4521                    window.paint_quad(fill(
4522                        Bounds {
4523                            origin: point(x, layout.position_map.text_hitbox.origin.y),
4524                            size: size(px(1.), layout.position_map.text_hitbox.size.height),
4525                        },
4526                        color,
4527                    ));
4528                }
4529            }
4530        })
4531    }
4532
4533    fn paint_indent_guides(
4534        &mut self,
4535        layout: &mut EditorLayout,
4536        window: &mut Window,
4537        cx: &mut App,
4538    ) {
4539        let Some(indent_guides) = &layout.indent_guides else {
4540            return;
4541        };
4542
4543        let faded_color = |color: Hsla, alpha: f32| {
4544            let mut faded = color;
4545            faded.a = alpha;
4546            faded
4547        };
4548
4549        for indent_guide in indent_guides {
4550            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
4551            let settings = indent_guide.settings;
4552
4553            // TODO fixed for now, expose them through themes later
4554            const INDENT_AWARE_ALPHA: f32 = 0.2;
4555            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
4556            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
4557            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
4558
4559            let line_color = match (settings.coloring, indent_guide.active) {
4560                (IndentGuideColoring::Disabled, _) => None,
4561                (IndentGuideColoring::Fixed, false) => {
4562                    Some(cx.theme().colors().editor_indent_guide)
4563                }
4564                (IndentGuideColoring::Fixed, true) => {
4565                    Some(cx.theme().colors().editor_indent_guide_active)
4566                }
4567                (IndentGuideColoring::IndentAware, false) => {
4568                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
4569                }
4570                (IndentGuideColoring::IndentAware, true) => {
4571                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
4572                }
4573            };
4574
4575            let background_color = match (settings.background_coloring, indent_guide.active) {
4576                (IndentGuideBackgroundColoring::Disabled, _) => None,
4577                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
4578                    indent_accent_colors,
4579                    INDENT_AWARE_BACKGROUND_ALPHA,
4580                )),
4581                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
4582                    indent_accent_colors,
4583                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
4584                )),
4585            };
4586
4587            let requested_line_width = if indent_guide.active {
4588                settings.active_line_width
4589            } else {
4590                settings.line_width
4591            }
4592            .clamp(1, 10);
4593            let mut line_indicator_width = 0.;
4594            if let Some(color) = line_color {
4595                window.paint_quad(fill(
4596                    Bounds {
4597                        origin: indent_guide.origin,
4598                        size: size(px(requested_line_width as f32), indent_guide.length),
4599                    },
4600                    color,
4601                ));
4602                line_indicator_width = requested_line_width as f32;
4603            }
4604
4605            if let Some(color) = background_color {
4606                let width = indent_guide.single_indent_width - px(line_indicator_width);
4607                window.paint_quad(fill(
4608                    Bounds {
4609                        origin: point(
4610                            indent_guide.origin.x + px(line_indicator_width),
4611                            indent_guide.origin.y,
4612                        ),
4613                        size: size(width, indent_guide.length),
4614                    },
4615                    color,
4616                ));
4617            }
4618        }
4619    }
4620
4621    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4622        let is_singleton = self.editor.read(cx).is_singleton(cx);
4623
4624        let line_height = layout.position_map.line_height;
4625        window.set_cursor_style(CursorStyle::Arrow, Some(&layout.gutter_hitbox));
4626
4627        for LineNumberLayout {
4628            shaped_line,
4629            hitbox,
4630        } in layout.line_numbers.values()
4631        {
4632            let Some(hitbox) = hitbox else {
4633                continue;
4634            };
4635
4636            let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
4637                let color = cx.theme().colors().editor_hover_line_number;
4638
4639                let Some(line) = self
4640                    .shape_line_number(shaped_line.text.clone(), color, window)
4641                    .log_err()
4642                else {
4643                    continue;
4644                };
4645
4646                line.paint(hitbox.origin, line_height, window, cx).log_err()
4647            } else {
4648                shaped_line
4649                    .paint(hitbox.origin, line_height, window, cx)
4650                    .log_err()
4651            }) else {
4652                continue;
4653            };
4654
4655            // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
4656            // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
4657            if is_singleton {
4658                window.set_cursor_style(CursorStyle::IBeam, Some(&hitbox));
4659            } else {
4660                window.set_cursor_style(CursorStyle::PointingHand, Some(&hitbox));
4661            }
4662        }
4663    }
4664
4665    fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4666        if layout.display_hunks.is_empty() {
4667            return;
4668        }
4669
4670        let line_height = layout.position_map.line_height;
4671        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4672            for (hunk, hitbox) in &layout.display_hunks {
4673                let hunk_to_paint = match hunk {
4674                    DisplayDiffHunk::Folded { .. } => {
4675                        let hunk_bounds = Self::diff_hunk_bounds(
4676                            &layout.position_map.snapshot,
4677                            line_height,
4678                            layout.gutter_hitbox.bounds,
4679                            &hunk,
4680                        );
4681                        Some((
4682                            hunk_bounds,
4683                            cx.theme().colors().version_control_modified,
4684                            Corners::all(px(0.)),
4685                            DiffHunkStatus::modified_none(),
4686                        ))
4687                    }
4688                    DisplayDiffHunk::Unfolded {
4689                        status,
4690                        display_row_range,
4691                        ..
4692                    } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
4693                        DiffHunkStatusKind::Added => (
4694                            hunk_hitbox.bounds,
4695                            cx.theme().colors().version_control_added,
4696                            Corners::all(px(0.)),
4697                            *status,
4698                        ),
4699                        DiffHunkStatusKind::Modified => (
4700                            hunk_hitbox.bounds,
4701                            cx.theme().colors().version_control_modified,
4702                            Corners::all(px(0.)),
4703                            *status,
4704                        ),
4705                        DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
4706                            hunk_hitbox.bounds,
4707                            cx.theme().colors().version_control_deleted,
4708                            Corners::all(px(0.)),
4709                            *status,
4710                        ),
4711                        DiffHunkStatusKind::Deleted => (
4712                            Bounds::new(
4713                                point(
4714                                    hunk_hitbox.origin.x - hunk_hitbox.size.width,
4715                                    hunk_hitbox.origin.y,
4716                                ),
4717                                size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
4718                            ),
4719                            cx.theme().colors().version_control_deleted,
4720                            Corners::all(1. * line_height),
4721                            *status,
4722                        ),
4723                    }),
4724                };
4725
4726                if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
4727                    // Flatten the background color with the editor color to prevent
4728                    // elements below transparent hunks from showing through
4729                    let flattened_background_color = cx
4730                        .theme()
4731                        .colors()
4732                        .editor_background
4733                        .blend(background_color);
4734
4735                    if !Self::diff_hunk_hollow(status, cx) {
4736                        window.paint_quad(quad(
4737                            hunk_bounds,
4738                            corner_radii,
4739                            flattened_background_color,
4740                            Edges::default(),
4741                            transparent_black(),
4742                            BorderStyle::default(),
4743                        ));
4744                    } else {
4745                        let flattened_unstaged_background_color = cx
4746                            .theme()
4747                            .colors()
4748                            .editor_background
4749                            .blend(background_color.opacity(0.3));
4750
4751                        window.paint_quad(quad(
4752                            hunk_bounds,
4753                            corner_radii,
4754                            flattened_unstaged_background_color,
4755                            Edges::all(Pixels(1.0)),
4756                            flattened_background_color,
4757                            BorderStyle::Solid,
4758                        ));
4759                    }
4760                }
4761            }
4762        });
4763    }
4764
4765    fn gutter_strip_width(line_height: Pixels) -> Pixels {
4766        (0.275 * line_height).floor()
4767    }
4768
4769    fn diff_hunk_bounds(
4770        snapshot: &EditorSnapshot,
4771        line_height: Pixels,
4772        gutter_bounds: Bounds<Pixels>,
4773        hunk: &DisplayDiffHunk,
4774    ) -> Bounds<Pixels> {
4775        let scroll_position = snapshot.scroll_position();
4776        let scroll_top = scroll_position.y * line_height;
4777        let gutter_strip_width = Self::gutter_strip_width(line_height);
4778
4779        match hunk {
4780            DisplayDiffHunk::Folded { display_row, .. } => {
4781                let start_y = display_row.as_f32() * line_height - scroll_top;
4782                let end_y = start_y + line_height;
4783                let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4784                let highlight_size = size(gutter_strip_width, end_y - start_y);
4785                Bounds::new(highlight_origin, highlight_size)
4786            }
4787            DisplayDiffHunk::Unfolded {
4788                display_row_range,
4789                status,
4790                ..
4791            } => {
4792                if status.is_deleted() && display_row_range.is_empty() {
4793                    let row = display_row_range.start;
4794
4795                    let offset = line_height / 2.;
4796                    let start_y = row.as_f32() * line_height - offset - scroll_top;
4797                    let end_y = start_y + line_height;
4798
4799                    let width = (0.35 * line_height).floor();
4800                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4801                    let highlight_size = size(width, end_y - start_y);
4802                    Bounds::new(highlight_origin, highlight_size)
4803                } else {
4804                    let start_row = display_row_range.start;
4805                    let end_row = display_row_range.end;
4806                    // If we're in a multibuffer, row range span might include an
4807                    // excerpt header, so if we were to draw the marker straight away,
4808                    // the hunk might include the rows of that header.
4809                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
4810                    // Instead, we simply check whether the range we're dealing with includes
4811                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
4812                    let end_row_in_current_excerpt = snapshot
4813                        .blocks_in_range(start_row..end_row)
4814                        .find_map(|(start_row, block)| {
4815                            if matches!(block, Block::ExcerptBoundary { .. }) {
4816                                Some(start_row)
4817                            } else {
4818                                None
4819                            }
4820                        })
4821                        .unwrap_or(end_row);
4822
4823                    let start_y = start_row.as_f32() * line_height - scroll_top;
4824                    let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
4825
4826                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4827                    let highlight_size = size(gutter_strip_width, end_y - start_y);
4828                    Bounds::new(highlight_origin, highlight_size)
4829                }
4830            }
4831        }
4832    }
4833
4834    fn paint_gutter_indicators(
4835        &self,
4836        layout: &mut EditorLayout,
4837        window: &mut Window,
4838        cx: &mut App,
4839    ) {
4840        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4841            window.with_element_namespace("crease_toggles", |window| {
4842                for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
4843                    crease_toggle.paint(window, cx);
4844                }
4845            });
4846
4847            window.with_element_namespace("expand_toggles", |window| {
4848                for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
4849                    expand_toggle.paint(window, cx);
4850                }
4851            });
4852
4853            for breakpoint in layout.breakpoints.iter_mut() {
4854                breakpoint.paint(window, cx);
4855            }
4856
4857            for test_indicator in layout.test_indicators.iter_mut() {
4858                test_indicator.paint(window, cx);
4859            }
4860
4861            if let Some(indicator) = layout.code_actions_indicator.as_mut() {
4862                indicator.paint(window, cx);
4863            }
4864        });
4865    }
4866
4867    fn paint_gutter_highlights(
4868        &self,
4869        layout: &mut EditorLayout,
4870        window: &mut Window,
4871        cx: &mut App,
4872    ) {
4873        for (_, hunk_hitbox) in &layout.display_hunks {
4874            if let Some(hunk_hitbox) = hunk_hitbox {
4875                if !self
4876                    .editor
4877                    .read(cx)
4878                    .buffer()
4879                    .read(cx)
4880                    .all_diff_hunks_expanded()
4881                {
4882                    window.set_cursor_style(CursorStyle::PointingHand, Some(hunk_hitbox));
4883                }
4884            }
4885        }
4886
4887        let show_git_gutter = layout
4888            .position_map
4889            .snapshot
4890            .show_git_diff_gutter
4891            .unwrap_or_else(|| {
4892                matches!(
4893                    ProjectSettings::get_global(cx).git.git_gutter,
4894                    Some(GitGutterSetting::TrackedFiles)
4895                )
4896            });
4897        if show_git_gutter {
4898            Self::paint_gutter_diff_hunks(layout, window, cx)
4899        }
4900
4901        let highlight_width = 0.275 * layout.position_map.line_height;
4902        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
4903        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4904            for (range, color) in &layout.highlighted_gutter_ranges {
4905                let start_row = if range.start.row() < layout.visible_display_row_range.start {
4906                    layout.visible_display_row_range.start - DisplayRow(1)
4907                } else {
4908                    range.start.row()
4909                };
4910                let end_row = if range.end.row() > layout.visible_display_row_range.end {
4911                    layout.visible_display_row_range.end + DisplayRow(1)
4912                } else {
4913                    range.end.row()
4914                };
4915
4916                let start_y = layout.gutter_hitbox.top()
4917                    + start_row.0 as f32 * layout.position_map.line_height
4918                    - layout.position_map.scroll_pixel_position.y;
4919                let end_y = layout.gutter_hitbox.top()
4920                    + (end_row.0 + 1) as f32 * layout.position_map.line_height
4921                    - layout.position_map.scroll_pixel_position.y;
4922                let bounds = Bounds::from_corners(
4923                    point(layout.gutter_hitbox.left(), start_y),
4924                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
4925                );
4926                window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
4927            }
4928        });
4929    }
4930
4931    fn paint_blamed_display_rows(
4932        &self,
4933        layout: &mut EditorLayout,
4934        window: &mut Window,
4935        cx: &mut App,
4936    ) {
4937        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
4938            return;
4939        };
4940
4941        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4942            for mut blame_element in blamed_display_rows.into_iter() {
4943                blame_element.paint(window, cx);
4944            }
4945        })
4946    }
4947
4948    fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4949        window.with_content_mask(
4950            Some(ContentMask {
4951                bounds: layout.position_map.text_hitbox.bounds,
4952            }),
4953            |window| {
4954                let editor = self.editor.read(cx);
4955                if editor.mouse_cursor_hidden {
4956                    window.set_cursor_style(CursorStyle::None, None);
4957                } else if editor
4958                    .hovered_link_state
4959                    .as_ref()
4960                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
4961                {
4962                    window.set_cursor_style(
4963                        CursorStyle::PointingHand,
4964                        Some(&layout.position_map.text_hitbox),
4965                    );
4966                } else {
4967                    window.set_cursor_style(
4968                        CursorStyle::IBeam,
4969                        Some(&layout.position_map.text_hitbox),
4970                    );
4971                };
4972
4973                self.paint_lines_background(layout, window, cx);
4974                let invisible_display_ranges = self.paint_highlights(layout, window);
4975                self.paint_lines(&invisible_display_ranges, layout, window, cx);
4976                self.paint_redactions(layout, window);
4977                self.paint_cursors(layout, window, cx);
4978                self.paint_inline_diagnostics(layout, window, cx);
4979                self.paint_inline_blame(layout, window, cx);
4980                self.paint_diff_hunk_controls(layout, window, cx);
4981                window.with_element_namespace("crease_trailers", |window| {
4982                    for trailer in layout.crease_trailers.iter_mut().flatten() {
4983                        trailer.element.paint(window, cx);
4984                    }
4985                });
4986            },
4987        )
4988    }
4989
4990    fn paint_highlights(
4991        &mut self,
4992        layout: &mut EditorLayout,
4993        window: &mut Window,
4994    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
4995        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4996            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
4997            let line_end_overshoot = 0.15 * layout.position_map.line_height;
4998            for (range, color) in &layout.highlighted_ranges {
4999                self.paint_highlighted_range(
5000                    range.clone(),
5001                    *color,
5002                    Pixels::ZERO,
5003                    line_end_overshoot,
5004                    layout,
5005                    window,
5006                );
5007            }
5008
5009            let corner_radius = 0.15 * layout.position_map.line_height;
5010
5011            for (player_color, selections) in &layout.selections {
5012                for selection in selections.iter() {
5013                    self.paint_highlighted_range(
5014                        selection.range.clone(),
5015                        player_color.selection,
5016                        corner_radius,
5017                        corner_radius * 2.,
5018                        layout,
5019                        window,
5020                    );
5021
5022                    if selection.is_local && !selection.range.is_empty() {
5023                        invisible_display_ranges.push(selection.range.clone());
5024                    }
5025                }
5026            }
5027            invisible_display_ranges
5028        })
5029    }
5030
5031    fn paint_lines(
5032        &mut self,
5033        invisible_display_ranges: &[Range<DisplayPoint>],
5034        layout: &mut EditorLayout,
5035        window: &mut Window,
5036        cx: &mut App,
5037    ) {
5038        let whitespace_setting = self
5039            .editor
5040            .read(cx)
5041            .buffer
5042            .read(cx)
5043            .language_settings(cx)
5044            .show_whitespaces;
5045
5046        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
5047            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
5048            line_with_invisibles.draw(
5049                layout,
5050                row,
5051                layout.content_origin,
5052                whitespace_setting,
5053                invisible_display_ranges,
5054                window,
5055                cx,
5056            )
5057        }
5058
5059        for line_element in &mut layout.line_elements {
5060            line_element.paint(window, cx);
5061        }
5062    }
5063
5064    fn paint_lines_background(
5065        &mut self,
5066        layout: &mut EditorLayout,
5067        window: &mut Window,
5068        cx: &mut App,
5069    ) {
5070        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
5071            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
5072            line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
5073        }
5074    }
5075
5076    fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
5077        if layout.redacted_ranges.is_empty() {
5078            return;
5079        }
5080
5081        let line_end_overshoot = layout.line_end_overshoot();
5082
5083        // A softer than perfect black
5084        let redaction_color = gpui::rgb(0x0e1111);
5085
5086        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5087            for range in layout.redacted_ranges.iter() {
5088                self.paint_highlighted_range(
5089                    range.clone(),
5090                    redaction_color.into(),
5091                    Pixels::ZERO,
5092                    line_end_overshoot,
5093                    layout,
5094                    window,
5095                );
5096            }
5097        });
5098    }
5099
5100    fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5101        for cursor in &mut layout.visible_cursors {
5102            cursor.paint(layout.content_origin, window, cx);
5103        }
5104    }
5105
5106    fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5107        let Some(scrollbars_layout) = &layout.scrollbars_layout else {
5108            return;
5109        };
5110
5111        for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
5112            let hitbox = &scrollbar_layout.hitbox;
5113            let thumb_bounds = scrollbar_layout.thumb_bounds();
5114
5115            if scrollbars_layout.visible {
5116                let scrollbar_edges = match axis {
5117                    ScrollbarAxis::Horizontal => Edges {
5118                        top: Pixels::ZERO,
5119                        right: Pixels::ZERO,
5120                        bottom: Pixels::ZERO,
5121                        left: Pixels::ZERO,
5122                    },
5123                    ScrollbarAxis::Vertical => Edges {
5124                        top: Pixels::ZERO,
5125                        right: Pixels::ZERO,
5126                        bottom: Pixels::ZERO,
5127                        left: ScrollbarLayout::BORDER_WIDTH,
5128                    },
5129                };
5130
5131                window.paint_layer(hitbox.bounds, |window| {
5132                    window.paint_quad(quad(
5133                        hitbox.bounds,
5134                        Corners::default(),
5135                        cx.theme().colors().scrollbar_track_background,
5136                        scrollbar_edges,
5137                        cx.theme().colors().scrollbar_track_border,
5138                        BorderStyle::Solid,
5139                    ));
5140
5141                    if axis == ScrollbarAxis::Vertical {
5142                        let fast_markers =
5143                            self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
5144                        // Refresh slow scrollbar markers in the background. Below, we
5145                        // paint whatever markers have already been computed.
5146                        self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx);
5147
5148                        let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
5149                        for marker in markers.iter().chain(&fast_markers) {
5150                            let mut marker = marker.clone();
5151                            marker.bounds.origin += hitbox.origin;
5152                            window.paint_quad(marker);
5153                        }
5154                    }
5155
5156                    window.paint_quad(quad(
5157                        thumb_bounds,
5158                        Corners::default(),
5159                        cx.theme().colors().scrollbar_thumb_background,
5160                        scrollbar_edges,
5161                        cx.theme().colors().scrollbar_thumb_border,
5162                        BorderStyle::Solid,
5163                    ));
5164                })
5165            }
5166            window.set_cursor_style(CursorStyle::Arrow, Some(&hitbox));
5167        }
5168
5169        window.on_mouse_event({
5170            let editor = self.editor.clone();
5171            let scrollbars_layout = scrollbars_layout.clone();
5172
5173            let mut mouse_position = window.mouse_position();
5174            move |event: &MouseMoveEvent, phase, window, cx| {
5175                if phase == DispatchPhase::Capture {
5176                    return;
5177                }
5178
5179                editor.update(cx, |editor, cx| {
5180                    if let Some((scrollbar_layout, axis)) = event
5181                        .pressed_button
5182                        .filter(|button| *button == MouseButton::Left)
5183                        .and(editor.scroll_manager.dragging_scrollbar_axis())
5184                        .and_then(|axis| {
5185                            scrollbars_layout
5186                                .iter_scrollbars()
5187                                .find(|(_, a)| *a == axis)
5188                        })
5189                    {
5190                        let ScrollbarLayout {
5191                            hitbox,
5192                            text_unit_size,
5193                            ..
5194                        } = scrollbar_layout;
5195
5196                        let old_position = mouse_position.along(axis);
5197                        let new_position = event.position.along(axis);
5198                        if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
5199                            .contains(&old_position)
5200                        {
5201                            let position = editor.scroll_position(cx).apply_along(axis, |p| {
5202                                (p + (new_position - old_position) / *text_unit_size).max(0.)
5203                            });
5204                            editor.set_scroll_position(position, window, cx);
5205                        }
5206                        cx.stop_propagation();
5207                    } else {
5208                        editor.scroll_manager.reset_scrollbar_dragging_state(cx);
5209                    }
5210
5211                    if scrollbars_layout.get_hovered_axis(window).is_some() {
5212                        editor.scroll_manager.show_scrollbars(window, cx);
5213                    }
5214
5215                    mouse_position = event.position;
5216                })
5217            }
5218        });
5219
5220        if self.editor.read(cx).scroll_manager.any_scrollbar_dragged() {
5221            window.on_mouse_event({
5222                let editor = self.editor.clone();
5223                move |_: &MouseUpEvent, phase, _, cx| {
5224                    if phase == DispatchPhase::Capture {
5225                        return;
5226                    }
5227
5228                    editor.update(cx, |editor, cx| {
5229                        editor.scroll_manager.reset_scrollbar_dragging_state(cx);
5230                        cx.stop_propagation();
5231                    });
5232                }
5233            });
5234        } else {
5235            window.on_mouse_event({
5236                let editor = self.editor.clone();
5237                let scrollbars_layout = scrollbars_layout.clone();
5238
5239                move |event: &MouseDownEvent, phase, window, cx| {
5240                    if phase == DispatchPhase::Capture {
5241                        return;
5242                    }
5243                    let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
5244                    else {
5245                        return;
5246                    };
5247
5248                    let ScrollbarLayout {
5249                        hitbox,
5250                        visible_range,
5251                        text_unit_size,
5252                        ..
5253                    } = scrollbar_layout;
5254
5255                    let thumb_bounds = scrollbar_layout.thumb_bounds();
5256
5257                    editor.update(cx, |editor, cx| {
5258                        editor.scroll_manager.set_dragged_scrollbar_axis(axis, cx);
5259
5260                        let event_position = event.position.along(axis);
5261
5262                        if event_position < thumb_bounds.origin.along(axis)
5263                            || thumb_bounds.bottom_right().along(axis) < event_position
5264                        {
5265                            let center_position = ((event_position - hitbox.origin.along(axis))
5266                                / *text_unit_size)
5267                                .round() as u32;
5268                            let start_position = center_position.saturating_sub(
5269                                (visible_range.end - visible_range.start) as u32 / 2,
5270                            );
5271
5272                            let position = editor
5273                                .scroll_position(cx)
5274                                .apply_along(axis, |_| start_position as f32);
5275
5276                            editor.set_scroll_position(position, window, cx);
5277                        } else {
5278                            editor.scroll_manager.show_scrollbars(window, cx);
5279                        }
5280
5281                        cx.stop_propagation();
5282                    });
5283                }
5284            });
5285        }
5286    }
5287
5288    fn collect_fast_scrollbar_markers(
5289        &self,
5290        layout: &EditorLayout,
5291        scrollbar_layout: &ScrollbarLayout,
5292        cx: &mut App,
5293    ) -> Vec<PaintQuad> {
5294        const LIMIT: usize = 100;
5295        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
5296            return vec![];
5297        }
5298        let cursor_ranges = layout
5299            .cursors
5300            .iter()
5301            .map(|(point, color)| ColoredRange {
5302                start: point.row(),
5303                end: point.row(),
5304                color: *color,
5305            })
5306            .collect_vec();
5307        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
5308    }
5309
5310    fn refresh_slow_scrollbar_markers(
5311        &self,
5312        layout: &EditorLayout,
5313        scrollbar_layout: &ScrollbarLayout,
5314        window: &mut Window,
5315        cx: &mut App,
5316    ) {
5317        self.editor.update(cx, |editor, cx| {
5318            if !editor.is_singleton(cx)
5319                || !editor
5320                    .scrollbar_marker_state
5321                    .should_refresh(scrollbar_layout.hitbox.size)
5322            {
5323                return;
5324            }
5325
5326            let scrollbar_layout = scrollbar_layout.clone();
5327            let background_highlights = editor.background_highlights.clone();
5328            let snapshot = layout.position_map.snapshot.clone();
5329            let theme = cx.theme().clone();
5330            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
5331
5332            editor.scrollbar_marker_state.dirty = false;
5333            editor.scrollbar_marker_state.pending_refresh =
5334                Some(cx.spawn_in(window, async move |editor, cx| {
5335                    let scrollbar_size = scrollbar_layout.hitbox.size;
5336                    let scrollbar_markers = cx
5337                        .background_spawn(async move {
5338                            let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
5339                            let mut marker_quads = Vec::new();
5340                            if scrollbar_settings.git_diff {
5341                                let marker_row_ranges =
5342                                    snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
5343                                        let start_display_row =
5344                                            MultiBufferPoint::new(hunk.row_range.start.0, 0)
5345                                                .to_display_point(&snapshot.display_snapshot)
5346                                                .row();
5347                                        let mut end_display_row =
5348                                            MultiBufferPoint::new(hunk.row_range.end.0, 0)
5349                                                .to_display_point(&snapshot.display_snapshot)
5350                                                .row();
5351                                        if end_display_row != start_display_row {
5352                                            end_display_row.0 -= 1;
5353                                        }
5354                                        let color = match &hunk.status().kind {
5355                                            DiffHunkStatusKind::Added => {
5356                                                theme.colors().version_control_added
5357                                            }
5358                                            DiffHunkStatusKind::Modified => {
5359                                                theme.colors().version_control_modified
5360                                            }
5361                                            DiffHunkStatusKind::Deleted => {
5362                                                theme.colors().version_control_deleted
5363                                            }
5364                                        };
5365                                        ColoredRange {
5366                                            start: start_display_row,
5367                                            end: end_display_row,
5368                                            color,
5369                                        }
5370                                    });
5371
5372                                marker_quads.extend(
5373                                    scrollbar_layout
5374                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
5375                                );
5376                            }
5377
5378                            for (background_highlight_id, (_, background_ranges)) in
5379                                background_highlights.iter()
5380                            {
5381                                let is_search_highlights = *background_highlight_id
5382                                    == TypeId::of::<BufferSearchHighlights>();
5383                                let is_text_highlights = *background_highlight_id
5384                                    == TypeId::of::<SelectedTextHighlight>();
5385                                let is_symbol_occurrences = *background_highlight_id
5386                                    == TypeId::of::<DocumentHighlightRead>()
5387                                    || *background_highlight_id
5388                                        == TypeId::of::<DocumentHighlightWrite>();
5389                                if (is_search_highlights && scrollbar_settings.search_results)
5390                                    || (is_text_highlights && scrollbar_settings.selected_text)
5391                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
5392                                {
5393                                    let mut color = theme.status().info;
5394                                    if is_symbol_occurrences {
5395                                        color.fade_out(0.5);
5396                                    }
5397                                    let marker_row_ranges = background_ranges.iter().map(|range| {
5398                                        let display_start = range
5399                                            .start
5400                                            .to_display_point(&snapshot.display_snapshot);
5401                                        let display_end =
5402                                            range.end.to_display_point(&snapshot.display_snapshot);
5403                                        ColoredRange {
5404                                            start: display_start.row(),
5405                                            end: display_end.row(),
5406                                            color,
5407                                        }
5408                                    });
5409                                    marker_quads.extend(
5410                                        scrollbar_layout
5411                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
5412                                    );
5413                                }
5414                            }
5415
5416                            if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
5417                                let diagnostics = snapshot
5418                                    .buffer_snapshot
5419                                    .diagnostics_in_range::<Point>(Point::zero()..max_point)
5420                                    // Don't show diagnostics the user doesn't care about
5421                                    .filter(|diagnostic| {
5422                                        match (
5423                                            scrollbar_settings.diagnostics,
5424                                            diagnostic.diagnostic.severity,
5425                                        ) {
5426                                            (ScrollbarDiagnostics::All, _) => true,
5427                                            (
5428                                                ScrollbarDiagnostics::Error,
5429                                                DiagnosticSeverity::ERROR,
5430                                            ) => true,
5431                                            (
5432                                                ScrollbarDiagnostics::Warning,
5433                                                DiagnosticSeverity::ERROR
5434                                                | DiagnosticSeverity::WARNING,
5435                                            ) => true,
5436                                            (
5437                                                ScrollbarDiagnostics::Information,
5438                                                DiagnosticSeverity::ERROR
5439                                                | DiagnosticSeverity::WARNING
5440                                                | DiagnosticSeverity::INFORMATION,
5441                                            ) => true,
5442                                            (_, _) => false,
5443                                        }
5444                                    })
5445                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
5446                                    .sorted_by_key(|diagnostic| {
5447                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
5448                                    });
5449
5450                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
5451                                    let start_display = diagnostic
5452                                        .range
5453                                        .start
5454                                        .to_display_point(&snapshot.display_snapshot);
5455                                    let end_display = diagnostic
5456                                        .range
5457                                        .end
5458                                        .to_display_point(&snapshot.display_snapshot);
5459                                    let color = match diagnostic.diagnostic.severity {
5460                                        DiagnosticSeverity::ERROR => theme.status().error,
5461                                        DiagnosticSeverity::WARNING => theme.status().warning,
5462                                        DiagnosticSeverity::INFORMATION => theme.status().info,
5463                                        _ => theme.status().hint,
5464                                    };
5465                                    ColoredRange {
5466                                        start: start_display.row(),
5467                                        end: end_display.row(),
5468                                        color,
5469                                    }
5470                                });
5471                                marker_quads.extend(
5472                                    scrollbar_layout
5473                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
5474                                );
5475                            }
5476
5477                            Arc::from(marker_quads)
5478                        })
5479                        .await;
5480
5481                    editor.update(cx, |editor, cx| {
5482                        editor.scrollbar_marker_state.markers = scrollbar_markers;
5483                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
5484                        editor.scrollbar_marker_state.pending_refresh = None;
5485                        cx.notify();
5486                    })?;
5487
5488                    Ok(())
5489                }));
5490        });
5491    }
5492
5493    fn paint_highlighted_range(
5494        &self,
5495        range: Range<DisplayPoint>,
5496        color: Hsla,
5497        corner_radius: Pixels,
5498        line_end_overshoot: Pixels,
5499        layout: &EditorLayout,
5500        window: &mut Window,
5501    ) {
5502        let start_row = layout.visible_display_row_range.start;
5503        let end_row = layout.visible_display_row_range.end;
5504        if range.start != range.end {
5505            let row_range = if range.end.column() == 0 {
5506                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
5507            } else {
5508                cmp::max(range.start.row(), start_row)
5509                    ..cmp::min(range.end.row().next_row(), end_row)
5510            };
5511
5512            let highlighted_range = HighlightedRange {
5513                color,
5514                line_height: layout.position_map.line_height,
5515                corner_radius,
5516                start_y: layout.content_origin.y
5517                    + row_range.start.as_f32() * layout.position_map.line_height
5518                    - layout.position_map.scroll_pixel_position.y,
5519                lines: row_range
5520                    .iter_rows()
5521                    .map(|row| {
5522                        let line_layout =
5523                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
5524                        HighlightedRangeLine {
5525                            start_x: if row == range.start.row() {
5526                                layout.content_origin.x
5527                                    + line_layout.x_for_index(range.start.column() as usize)
5528                                    - layout.position_map.scroll_pixel_position.x
5529                            } else {
5530                                layout.content_origin.x
5531                                    - layout.position_map.scroll_pixel_position.x
5532                            },
5533                            end_x: if row == range.end.row() {
5534                                layout.content_origin.x
5535                                    + line_layout.x_for_index(range.end.column() as usize)
5536                                    - layout.position_map.scroll_pixel_position.x
5537                            } else {
5538                                layout.content_origin.x + line_layout.width + line_end_overshoot
5539                                    - layout.position_map.scroll_pixel_position.x
5540                            },
5541                        }
5542                    })
5543                    .collect(),
5544            };
5545
5546            highlighted_range.paint(layout.position_map.text_hitbox.bounds, window);
5547        }
5548    }
5549
5550    fn paint_inline_diagnostics(
5551        &mut self,
5552        layout: &mut EditorLayout,
5553        window: &mut Window,
5554        cx: &mut App,
5555    ) {
5556        for mut inline_diagnostic in layout.inline_diagnostics.drain() {
5557            inline_diagnostic.1.paint(window, cx);
5558        }
5559    }
5560
5561    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5562        if let Some(mut inline_blame) = layout.inline_blame.take() {
5563            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5564                inline_blame.paint(window, cx);
5565            })
5566        }
5567    }
5568
5569    fn paint_diff_hunk_controls(
5570        &mut self,
5571        layout: &mut EditorLayout,
5572        window: &mut Window,
5573        cx: &mut App,
5574    ) {
5575        for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
5576            diff_hunk_control.paint(window, cx);
5577        }
5578    }
5579
5580    fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5581        for mut block in layout.blocks.drain(..) {
5582            if block.overlaps_gutter {
5583                block.element.paint(window, cx);
5584            } else {
5585                let mut bounds = layout.hitbox.bounds;
5586                bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
5587                window.with_content_mask(Some(ContentMask { bounds }), |window| {
5588                    block.element.paint(window, cx);
5589                })
5590            }
5591        }
5592    }
5593
5594    fn paint_inline_completion_popover(
5595        &mut self,
5596        layout: &mut EditorLayout,
5597        window: &mut Window,
5598        cx: &mut App,
5599    ) {
5600        if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
5601            inline_completion_popover.paint(window, cx);
5602        }
5603    }
5604
5605    fn paint_mouse_context_menu(
5606        &mut self,
5607        layout: &mut EditorLayout,
5608        window: &mut Window,
5609        cx: &mut App,
5610    ) {
5611        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
5612            mouse_context_menu.paint(window, cx);
5613        }
5614    }
5615
5616    fn paint_scroll_wheel_listener(
5617        &mut self,
5618        layout: &EditorLayout,
5619        window: &mut Window,
5620        cx: &mut App,
5621    ) {
5622        window.on_mouse_event({
5623            let position_map = layout.position_map.clone();
5624            let editor = self.editor.clone();
5625            let hitbox = layout.hitbox.clone();
5626            let mut delta = ScrollDelta::default();
5627
5628            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
5629            // accidentally turn off their scrolling.
5630            let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
5631
5632            move |event: &ScrollWheelEvent, phase, window, cx| {
5633                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
5634                    delta = delta.coalesce(event.delta);
5635                    editor.update(cx, |editor, cx| {
5636                        let position_map: &PositionMap = &position_map;
5637
5638                        let line_height = position_map.line_height;
5639                        let max_glyph_width = position_map.em_width;
5640                        let (delta, axis) = match delta {
5641                            gpui::ScrollDelta::Pixels(mut pixels) => {
5642                                //Trackpad
5643                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
5644                                (pixels, axis)
5645                            }
5646
5647                            gpui::ScrollDelta::Lines(lines) => {
5648                                //Not trackpad
5649                                let pixels =
5650                                    point(lines.x * max_glyph_width, lines.y * line_height);
5651                                (pixels, None)
5652                            }
5653                        };
5654
5655                        let current_scroll_position = position_map.snapshot.scroll_position();
5656                        let x = (current_scroll_position.x * max_glyph_width
5657                            - (delta.x * scroll_sensitivity))
5658                            / max_glyph_width;
5659                        let y = (current_scroll_position.y * line_height
5660                            - (delta.y * scroll_sensitivity))
5661                            / line_height;
5662                        let mut scroll_position =
5663                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
5664                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
5665                        if forbid_vertical_scroll {
5666                            scroll_position.y = current_scroll_position.y;
5667                        }
5668
5669                        if scroll_position != current_scroll_position {
5670                            editor.scroll(scroll_position, axis, window, cx);
5671                            cx.stop_propagation();
5672                        } else if y < 0. {
5673                            // Due to clamping, we may fail to detect cases of overscroll to the top;
5674                            // We want the scroll manager to get an update in such cases and detect the change of direction
5675                            // on the next frame.
5676                            cx.notify();
5677                        }
5678                    });
5679                }
5680            }
5681        });
5682    }
5683
5684    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5685        self.paint_scroll_wheel_listener(layout, window, cx);
5686
5687        window.on_mouse_event({
5688            let position_map = layout.position_map.clone();
5689            let editor = self.editor.clone();
5690            let diff_hunk_range =
5691                layout
5692                    .display_hunks
5693                    .iter()
5694                    .find_map(|(hunk, hunk_hitbox)| match hunk {
5695                        DisplayDiffHunk::Folded { .. } => None,
5696                        DisplayDiffHunk::Unfolded {
5697                            multi_buffer_range, ..
5698                        } => {
5699                            if hunk_hitbox
5700                                .as_ref()
5701                                .map(|hitbox| hitbox.is_hovered(window))
5702                                .unwrap_or(false)
5703                            {
5704                                Some(multi_buffer_range.clone())
5705                            } else {
5706                                None
5707                            }
5708                        }
5709                    });
5710            let line_numbers = layout.line_numbers.clone();
5711
5712            move |event: &MouseDownEvent, phase, window, cx| {
5713                if phase == DispatchPhase::Bubble {
5714                    match event.button {
5715                        MouseButton::Left => editor.update(cx, |editor, cx| {
5716                            let pending_mouse_down = editor
5717                                .pending_mouse_down
5718                                .get_or_insert_with(Default::default)
5719                                .clone();
5720
5721                            *pending_mouse_down.borrow_mut() = Some(event.clone());
5722
5723                            Self::mouse_left_down(
5724                                editor,
5725                                event,
5726                                diff_hunk_range.clone(),
5727                                &position_map,
5728                                line_numbers.as_ref(),
5729                                window,
5730                                cx,
5731                            );
5732                        }),
5733                        MouseButton::Right => editor.update(cx, |editor, cx| {
5734                            Self::mouse_right_down(editor, event, &position_map, window, cx);
5735                        }),
5736                        MouseButton::Middle => editor.update(cx, |editor, cx| {
5737                            Self::mouse_middle_down(editor, event, &position_map, window, cx);
5738                        }),
5739                        _ => {}
5740                    };
5741                }
5742            }
5743        });
5744
5745        window.on_mouse_event({
5746            let editor = self.editor.clone();
5747            let position_map = layout.position_map.clone();
5748
5749            move |event: &MouseUpEvent, phase, window, cx| {
5750                if phase == DispatchPhase::Bubble {
5751                    editor.update(cx, |editor, cx| {
5752                        Self::mouse_up(editor, event, &position_map, window, cx)
5753                    });
5754                }
5755            }
5756        });
5757
5758        window.on_mouse_event({
5759            let editor = self.editor.clone();
5760            let position_map = layout.position_map.clone();
5761            let mut captured_mouse_down = None;
5762
5763            move |event: &MouseUpEvent, phase, window, cx| match phase {
5764                // Clear the pending mouse down during the capture phase,
5765                // so that it happens even if another event handler stops
5766                // propagation.
5767                DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
5768                    let pending_mouse_down = editor
5769                        .pending_mouse_down
5770                        .get_or_insert_with(Default::default)
5771                        .clone();
5772
5773                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
5774                    if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
5775                        captured_mouse_down = pending_mouse_down.take();
5776                        window.refresh();
5777                    }
5778                }),
5779                // Fire click handlers during the bubble phase.
5780                DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
5781                    if let Some(mouse_down) = captured_mouse_down.take() {
5782                        let event = ClickEvent {
5783                            down: mouse_down,
5784                            up: event.clone(),
5785                        };
5786                        Self::click(editor, &event, &position_map, window, cx);
5787                    }
5788                }),
5789            }
5790        });
5791
5792        window.on_mouse_event({
5793            let position_map = layout.position_map.clone();
5794            let editor = self.editor.clone();
5795
5796            move |event: &MouseMoveEvent, phase, window, cx| {
5797                if phase == DispatchPhase::Bubble {
5798                    editor.update(cx, |editor, cx| {
5799                        if editor.hover_state.focused(window, cx) {
5800                            return;
5801                        }
5802                        if event.pressed_button == Some(MouseButton::Left)
5803                            || event.pressed_button == Some(MouseButton::Middle)
5804                        {
5805                            Self::mouse_dragged(editor, event, &position_map, window, cx)
5806                        }
5807
5808                        Self::mouse_moved(editor, event, &position_map, window, cx)
5809                    });
5810                }
5811            }
5812        });
5813    }
5814
5815    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
5816        bounds.top_right().x - self.style.scrollbar_width
5817    }
5818
5819    fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
5820        let style = &self.style;
5821        let font_size = style.text.font_size.to_pixels(window.rem_size());
5822        let layout = window
5823            .text_system()
5824            .shape_line(
5825                SharedString::from(" ".repeat(column)),
5826                font_size,
5827                &[TextRun {
5828                    len: column,
5829                    font: style.text.font(),
5830                    color: Hsla::default(),
5831                    background_color: None,
5832                    underline: None,
5833                    strikethrough: None,
5834                }],
5835            )
5836            .unwrap();
5837
5838        layout.width
5839    }
5840
5841    fn max_line_number_width(
5842        &self,
5843        snapshot: &EditorSnapshot,
5844        window: &mut Window,
5845        cx: &mut App,
5846    ) -> Pixels {
5847        let digit_count = snapshot.widest_line_number().ilog10() + 1;
5848        self.column_pixels(digit_count as usize, window, cx)
5849    }
5850
5851    fn shape_line_number(
5852        &self,
5853        text: SharedString,
5854        color: Hsla,
5855        window: &mut Window,
5856    ) -> anyhow::Result<ShapedLine> {
5857        let run = TextRun {
5858            len: text.len(),
5859            font: self.style.text.font(),
5860            color,
5861            background_color: None,
5862            underline: None,
5863            strikethrough: None,
5864        };
5865        window.text_system().shape_line(
5866            text,
5867            self.style.text.font_size.to_pixels(window.rem_size()),
5868            &[run],
5869        )
5870    }
5871
5872    fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
5873        let unstaged = status.has_secondary_hunk();
5874        let unstaged_hollow = ProjectSettings::get_global(cx)
5875            .git
5876            .hunk_style
5877            .map_or(false, |style| {
5878                matches!(style, GitHunkStyleSetting::UnstagedHollow)
5879            });
5880
5881        unstaged == unstaged_hollow
5882    }
5883}
5884
5885fn header_jump_data(
5886    snapshot: &EditorSnapshot,
5887    block_row_start: DisplayRow,
5888    height: u32,
5889    for_excerpt: &ExcerptInfo,
5890) -> JumpData {
5891    let range = &for_excerpt.range;
5892    let buffer = &for_excerpt.buffer;
5893    let jump_anchor = range.primary.start;
5894
5895    let excerpt_start = range.context.start;
5896    let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
5897    let rows_from_excerpt_start = if jump_anchor == excerpt_start {
5898        0
5899    } else {
5900        let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
5901        jump_position.row.saturating_sub(excerpt_start_point.row)
5902    };
5903
5904    let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
5905        .saturating_sub(
5906            snapshot
5907                .scroll_anchor
5908                .scroll_position(&snapshot.display_snapshot)
5909                .y as u32,
5910        );
5911
5912    JumpData::MultiBufferPoint {
5913        excerpt_id: for_excerpt.id,
5914        anchor: jump_anchor,
5915        position: jump_position,
5916        line_offset_from_top,
5917    }
5918}
5919
5920pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
5921
5922impl AcceptEditPredictionBinding {
5923    pub fn keystroke(&self) -> Option<&Keystroke> {
5924        if let Some(binding) = self.0.as_ref() {
5925            match &binding.keystrokes() {
5926                [keystroke] => Some(keystroke),
5927                _ => None,
5928            }
5929        } else {
5930            None
5931        }
5932    }
5933}
5934
5935fn prepaint_gutter_button(
5936    button: IconButton,
5937    row: DisplayRow,
5938    line_height: Pixels,
5939    gutter_dimensions: &GutterDimensions,
5940    scroll_pixel_position: gpui::Point<Pixels>,
5941    gutter_hitbox: &Hitbox,
5942    display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
5943    window: &mut Window,
5944    cx: &mut App,
5945) -> AnyElement {
5946    let mut button = button.into_any_element();
5947
5948    let available_space = size(
5949        AvailableSpace::MinContent,
5950        AvailableSpace::Definite(line_height),
5951    );
5952    let indicator_size = button.layout_as_root(available_space, window, cx);
5953
5954    let blame_width = gutter_dimensions.git_blame_entries_width;
5955    let gutter_width = display_hunks
5956        .binary_search_by(|(hunk, _)| match hunk {
5957            DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
5958            DisplayDiffHunk::Unfolded {
5959                display_row_range, ..
5960            } => {
5961                if display_row_range.end <= row {
5962                    Ordering::Less
5963                } else if display_row_range.start > row {
5964                    Ordering::Greater
5965                } else {
5966                    Ordering::Equal
5967                }
5968            }
5969        })
5970        .ok()
5971        .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
5972    let left_offset = blame_width.max(gutter_width).unwrap_or_default();
5973
5974    let mut x = left_offset;
5975    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
5976        - indicator_size.width
5977        - left_offset;
5978    x += available_width / 2.;
5979
5980    let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
5981    y += (line_height - indicator_size.height) / 2.;
5982
5983    button.prepaint_as_root(
5984        gutter_hitbox.origin + point(x, y),
5985        available_space,
5986        window,
5987        cx,
5988    );
5989    button
5990}
5991
5992fn render_inline_blame_entry(
5993    blame_entry: BlameEntry,
5994    style: &EditorStyle,
5995    cx: &mut App,
5996) -> Option<AnyElement> {
5997    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
5998    renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
5999}
6000
6001fn render_blame_entry_popover(
6002    blame_entry: BlameEntry,
6003    scroll_handle: ScrollHandle,
6004    commit_message: Option<ParsedCommitMessage>,
6005    markdown: Entity<Markdown>,
6006    workspace: WeakEntity<Workspace>,
6007    blame: &Entity<GitBlame>,
6008    window: &mut Window,
6009    cx: &mut App,
6010) -> Option<AnyElement> {
6011    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
6012    let blame = blame.read(cx);
6013    let repository = blame.repository(cx)?.clone();
6014    renderer.render_blame_entry_popover(
6015        blame_entry,
6016        scroll_handle,
6017        commit_message,
6018        markdown,
6019        repository,
6020        workspace,
6021        window,
6022        cx,
6023    )
6024}
6025
6026fn render_blame_entry(
6027    ix: usize,
6028    blame: &Entity<GitBlame>,
6029    blame_entry: BlameEntry,
6030    style: &EditorStyle,
6031    last_used_color: &mut Option<(PlayerColor, Oid)>,
6032    editor: Entity<Editor>,
6033    workspace: Entity<Workspace>,
6034    renderer: Arc<dyn BlameRenderer>,
6035    cx: &mut App,
6036) -> Option<AnyElement> {
6037    let mut sha_color = cx
6038        .theme()
6039        .players()
6040        .color_for_participant(blame_entry.sha.into());
6041
6042    // If the last color we used is the same as the one we get for this line, but
6043    // the commit SHAs are different, then we try again to get a different color.
6044    match *last_used_color {
6045        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
6046            let index: u32 = blame_entry.sha.into();
6047            sha_color = cx.theme().players().color_for_participant(index + 1);
6048        }
6049        _ => {}
6050    };
6051    last_used_color.replace((sha_color, blame_entry.sha));
6052
6053    let blame = blame.read(cx);
6054    let details = blame.details_for_entry(&blame_entry);
6055    let repository = blame.repository(cx)?;
6056    renderer.render_blame_entry(
6057        &style.text,
6058        blame_entry,
6059        details,
6060        repository,
6061        workspace.downgrade(),
6062        editor,
6063        ix,
6064        sha_color.cursor,
6065        cx,
6066    )
6067}
6068
6069#[derive(Debug)]
6070pub(crate) struct LineWithInvisibles {
6071    fragments: SmallVec<[LineFragment; 1]>,
6072    invisibles: Vec<Invisible>,
6073    len: usize,
6074    pub(crate) width: Pixels,
6075    font_size: Pixels,
6076}
6077
6078#[allow(clippy::large_enum_variant)]
6079enum LineFragment {
6080    Text(ShapedLine),
6081    Element {
6082        id: FoldId,
6083        element: Option<AnyElement>,
6084        size: Size<Pixels>,
6085        len: usize,
6086    },
6087}
6088
6089impl fmt::Debug for LineFragment {
6090    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6091        match self {
6092            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
6093            LineFragment::Element { size, len, .. } => f
6094                .debug_struct("Element")
6095                .field("size", size)
6096                .field("len", len)
6097                .finish(),
6098        }
6099    }
6100}
6101
6102impl LineWithInvisibles {
6103    fn from_chunks<'a>(
6104        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
6105        editor_style: &EditorStyle,
6106        max_line_len: usize,
6107        max_line_count: usize,
6108        editor_mode: EditorMode,
6109        text_width: Pixels,
6110        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6111        window: &mut Window,
6112        cx: &mut App,
6113    ) -> Vec<Self> {
6114        let text_style = &editor_style.text;
6115        let mut layouts = Vec::with_capacity(max_line_count);
6116        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
6117        let mut line = String::new();
6118        let mut invisibles = Vec::new();
6119        let mut width = Pixels::ZERO;
6120        let mut len = 0;
6121        let mut styles = Vec::new();
6122        let mut non_whitespace_added = false;
6123        let mut row = 0;
6124        let mut line_exceeded_max_len = false;
6125        let font_size = text_style.font_size.to_pixels(window.rem_size());
6126
6127        let ellipsis = SharedString::from("");
6128
6129        for highlighted_chunk in chunks.chain([HighlightedChunk {
6130            text: "\n",
6131            style: None,
6132            is_tab: false,
6133            replacement: None,
6134        }]) {
6135            if let Some(replacement) = highlighted_chunk.replacement {
6136                if !line.is_empty() {
6137                    let shaped_line = window
6138                        .text_system()
6139                        .shape_line(line.clone().into(), font_size, &styles)
6140                        .unwrap();
6141                    width += shaped_line.width;
6142                    len += shaped_line.len;
6143                    fragments.push(LineFragment::Text(shaped_line));
6144                    line.clear();
6145                    styles.clear();
6146                }
6147
6148                match replacement {
6149                    ChunkReplacement::Renderer(renderer) => {
6150                        let available_width = if renderer.constrain_width {
6151                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
6152                                ellipsis.clone()
6153                            } else {
6154                                SharedString::from(Arc::from(highlighted_chunk.text))
6155                            };
6156                            let shaped_line = window
6157                                .text_system()
6158                                .shape_line(
6159                                    chunk,
6160                                    font_size,
6161                                    &[text_style.to_run(highlighted_chunk.text.len())],
6162                                )
6163                                .unwrap();
6164                            AvailableSpace::Definite(shaped_line.width)
6165                        } else {
6166                            AvailableSpace::MinContent
6167                        };
6168
6169                        let mut element = (renderer.render)(&mut ChunkRendererContext {
6170                            context: cx,
6171                            window,
6172                            max_width: text_width,
6173                        });
6174                        let line_height = text_style.line_height_in_pixels(window.rem_size());
6175                        let size = element.layout_as_root(
6176                            size(available_width, AvailableSpace::Definite(line_height)),
6177                            window,
6178                            cx,
6179                        );
6180
6181                        width += size.width;
6182                        len += highlighted_chunk.text.len();
6183                        fragments.push(LineFragment::Element {
6184                            id: renderer.id,
6185                            element: Some(element),
6186                            size,
6187                            len: highlighted_chunk.text.len(),
6188                        });
6189                    }
6190                    ChunkReplacement::Str(x) => {
6191                        let text_style = if let Some(style) = highlighted_chunk.style {
6192                            Cow::Owned(text_style.clone().highlight(style))
6193                        } else {
6194                            Cow::Borrowed(text_style)
6195                        };
6196
6197                        let run = TextRun {
6198                            len: x.len(),
6199                            font: text_style.font(),
6200                            color: text_style.color,
6201                            background_color: text_style.background_color,
6202                            underline: text_style.underline,
6203                            strikethrough: text_style.strikethrough,
6204                        };
6205                        let line_layout = window
6206                            .text_system()
6207                            .shape_line(x, font_size, &[run])
6208                            .unwrap()
6209                            .with_len(highlighted_chunk.text.len());
6210
6211                        width += line_layout.width;
6212                        len += highlighted_chunk.text.len();
6213                        fragments.push(LineFragment::Text(line_layout))
6214                    }
6215                }
6216            } else {
6217                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
6218                    if ix > 0 {
6219                        let shaped_line = window
6220                            .text_system()
6221                            .shape_line(line.clone().into(), font_size, &styles)
6222                            .unwrap();
6223                        width += shaped_line.width;
6224                        len += shaped_line.len;
6225                        fragments.push(LineFragment::Text(shaped_line));
6226                        layouts.push(Self {
6227                            width: mem::take(&mut width),
6228                            len: mem::take(&mut len),
6229                            fragments: mem::take(&mut fragments),
6230                            invisibles: std::mem::take(&mut invisibles),
6231                            font_size,
6232                        });
6233
6234                        line.clear();
6235                        styles.clear();
6236                        row += 1;
6237                        line_exceeded_max_len = false;
6238                        non_whitespace_added = false;
6239                        if row == max_line_count {
6240                            return layouts;
6241                        }
6242                    }
6243
6244                    if !line_chunk.is_empty() && !line_exceeded_max_len {
6245                        let text_style = if let Some(style) = highlighted_chunk.style {
6246                            Cow::Owned(text_style.clone().highlight(style))
6247                        } else {
6248                            Cow::Borrowed(text_style)
6249                        };
6250
6251                        if line.len() + line_chunk.len() > max_line_len {
6252                            let mut chunk_len = max_line_len - line.len();
6253                            while !line_chunk.is_char_boundary(chunk_len) {
6254                                chunk_len -= 1;
6255                            }
6256                            line_chunk = &line_chunk[..chunk_len];
6257                            line_exceeded_max_len = true;
6258                        }
6259
6260                        styles.push(TextRun {
6261                            len: line_chunk.len(),
6262                            font: text_style.font(),
6263                            color: text_style.color,
6264                            background_color: text_style.background_color,
6265                            underline: text_style.underline,
6266                            strikethrough: text_style.strikethrough,
6267                        });
6268
6269                        if editor_mode.is_full() {
6270                            // Line wrap pads its contents with fake whitespaces,
6271                            // avoid printing them
6272                            let is_soft_wrapped = is_row_soft_wrapped(row);
6273                            if highlighted_chunk.is_tab {
6274                                if non_whitespace_added || !is_soft_wrapped {
6275                                    invisibles.push(Invisible::Tab {
6276                                        line_start_offset: line.len(),
6277                                        line_end_offset: line.len() + line_chunk.len(),
6278                                    });
6279                                }
6280                            } else {
6281                                invisibles.extend(line_chunk.char_indices().filter_map(
6282                                    |(index, c)| {
6283                                        let is_whitespace = c.is_whitespace();
6284                                        non_whitespace_added |= !is_whitespace;
6285                                        if is_whitespace
6286                                            && (non_whitespace_added || !is_soft_wrapped)
6287                                        {
6288                                            Some(Invisible::Whitespace {
6289                                                line_offset: line.len() + index,
6290                                            })
6291                                        } else {
6292                                            None
6293                                        }
6294                                    },
6295                                ))
6296                            }
6297                        }
6298
6299                        line.push_str(line_chunk);
6300                    }
6301                }
6302            }
6303        }
6304
6305        layouts
6306    }
6307
6308    fn prepaint(
6309        &mut self,
6310        line_height: Pixels,
6311        scroll_pixel_position: gpui::Point<Pixels>,
6312        row: DisplayRow,
6313        content_origin: gpui::Point<Pixels>,
6314        line_elements: &mut SmallVec<[AnyElement; 1]>,
6315        window: &mut Window,
6316        cx: &mut App,
6317    ) {
6318        let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
6319        let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
6320        for fragment in &mut self.fragments {
6321            match fragment {
6322                LineFragment::Text(line) => {
6323                    fragment_origin.x += line.width;
6324                }
6325                LineFragment::Element { element, size, .. } => {
6326                    let mut element = element
6327                        .take()
6328                        .expect("you can't prepaint LineWithInvisibles twice");
6329
6330                    // Center the element vertically within the line.
6331                    let mut element_origin = fragment_origin;
6332                    element_origin.y += (line_height - size.height) / 2.;
6333                    element.prepaint_at(element_origin, window, cx);
6334                    line_elements.push(element);
6335
6336                    fragment_origin.x += size.width;
6337                }
6338            }
6339        }
6340    }
6341
6342    fn draw(
6343        &self,
6344        layout: &EditorLayout,
6345        row: DisplayRow,
6346        content_origin: gpui::Point<Pixels>,
6347        whitespace_setting: ShowWhitespaceSetting,
6348        selection_ranges: &[Range<DisplayPoint>],
6349        window: &mut Window,
6350        cx: &mut App,
6351    ) {
6352        let line_height = layout.position_map.line_height;
6353        let line_y = line_height
6354            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6355
6356        let mut fragment_origin =
6357            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6358
6359        for fragment in &self.fragments {
6360            match fragment {
6361                LineFragment::Text(line) => {
6362                    line.paint(fragment_origin, line_height, window, cx)
6363                        .log_err();
6364                    fragment_origin.x += line.width;
6365                }
6366                LineFragment::Element { size, .. } => {
6367                    fragment_origin.x += size.width;
6368                }
6369            }
6370        }
6371
6372        self.draw_invisibles(
6373            selection_ranges,
6374            layout,
6375            content_origin,
6376            line_y,
6377            row,
6378            line_height,
6379            whitespace_setting,
6380            window,
6381            cx,
6382        );
6383    }
6384
6385    fn draw_background(
6386        &self,
6387        layout: &EditorLayout,
6388        row: DisplayRow,
6389        content_origin: gpui::Point<Pixels>,
6390        window: &mut Window,
6391        cx: &mut App,
6392    ) {
6393        let line_height = layout.position_map.line_height;
6394        let line_y = line_height
6395            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6396
6397        let mut fragment_origin =
6398            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6399
6400        for fragment in &self.fragments {
6401            match fragment {
6402                LineFragment::Text(line) => {
6403                    line.paint_background(fragment_origin, line_height, window, cx)
6404                        .log_err();
6405                    fragment_origin.x += line.width;
6406                }
6407                LineFragment::Element { size, .. } => {
6408                    fragment_origin.x += size.width;
6409                }
6410            }
6411        }
6412    }
6413
6414    fn draw_invisibles(
6415        &self,
6416        selection_ranges: &[Range<DisplayPoint>],
6417        layout: &EditorLayout,
6418        content_origin: gpui::Point<Pixels>,
6419        line_y: Pixels,
6420        row: DisplayRow,
6421        line_height: Pixels,
6422        whitespace_setting: ShowWhitespaceSetting,
6423        window: &mut Window,
6424        cx: &mut App,
6425    ) {
6426        let extract_whitespace_info = |invisible: &Invisible| {
6427            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
6428                Invisible::Tab {
6429                    line_start_offset,
6430                    line_end_offset,
6431                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
6432                Invisible::Whitespace { line_offset } => {
6433                    (*line_offset, line_offset + 1, &layout.space_invisible)
6434                }
6435            };
6436
6437            let x_offset = self.x_for_index(token_offset);
6438            let invisible_offset =
6439                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
6440            let origin = content_origin
6441                + gpui::point(
6442                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
6443                    line_y,
6444                );
6445
6446            (
6447                [token_offset, token_end_offset],
6448                Box::new(move |window: &mut Window, cx: &mut App| {
6449                    invisible_symbol
6450                        .paint(origin, line_height, window, cx)
6451                        .log_err();
6452                }),
6453            )
6454        };
6455
6456        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
6457        match whitespace_setting {
6458            ShowWhitespaceSetting::None => (),
6459            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
6460            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
6461                let invisible_point = DisplayPoint::new(row, start as u32);
6462                if !selection_ranges
6463                    .iter()
6464                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
6465                {
6466                    return;
6467                }
6468
6469                paint(window, cx);
6470            }),
6471
6472            // For a whitespace to be on a boundary, any of the following conditions need to be met:
6473            // - It is a tab
6474            // - It is adjacent to an edge (start or end)
6475            // - It is adjacent to a whitespace (left or right)
6476            ShowWhitespaceSetting::Boundary => {
6477                // 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
6478                // the above cases.
6479                // Note: We zip in the original `invisibles` to check for tab equality
6480                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
6481                for (([start, end], paint), invisible) in
6482                    invisible_iter.zip_eq(self.invisibles.iter())
6483                {
6484                    let should_render = match (&last_seen, invisible) {
6485                        (_, Invisible::Tab { .. }) => true,
6486                        (Some((_, last_end, _)), _) => *last_end == start,
6487                        _ => false,
6488                    };
6489
6490                    if should_render || start == 0 || end == self.len {
6491                        paint(window, cx);
6492
6493                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
6494                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
6495                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
6496                            // Note that we need to make sure that the last one is actually adjacent
6497                            if !should_render_last && last_end == start {
6498                                paint_last(window, cx);
6499                            }
6500                        }
6501                    }
6502
6503                    // Manually render anything within a selection
6504                    let invisible_point = DisplayPoint::new(row, start as u32);
6505                    if selection_ranges.iter().any(|region| {
6506                        region.start <= invisible_point && invisible_point < region.end
6507                    }) {
6508                        paint(window, cx);
6509                    }
6510
6511                    last_seen = Some((should_render, end, paint));
6512                }
6513            }
6514        }
6515    }
6516
6517    pub fn x_for_index(&self, index: usize) -> Pixels {
6518        let mut fragment_start_x = Pixels::ZERO;
6519        let mut fragment_start_index = 0;
6520
6521        for fragment in &self.fragments {
6522            match fragment {
6523                LineFragment::Text(shaped_line) => {
6524                    let fragment_end_index = fragment_start_index + shaped_line.len;
6525                    if index < fragment_end_index {
6526                        return fragment_start_x
6527                            + shaped_line.x_for_index(index - fragment_start_index);
6528                    }
6529                    fragment_start_x += shaped_line.width;
6530                    fragment_start_index = fragment_end_index;
6531                }
6532                LineFragment::Element { len, size, .. } => {
6533                    let fragment_end_index = fragment_start_index + len;
6534                    if index < fragment_end_index {
6535                        return fragment_start_x;
6536                    }
6537                    fragment_start_x += size.width;
6538                    fragment_start_index = fragment_end_index;
6539                }
6540            }
6541        }
6542
6543        fragment_start_x
6544    }
6545
6546    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
6547        let mut fragment_start_x = Pixels::ZERO;
6548        let mut fragment_start_index = 0;
6549
6550        for fragment in &self.fragments {
6551            match fragment {
6552                LineFragment::Text(shaped_line) => {
6553                    let fragment_end_x = fragment_start_x + shaped_line.width;
6554                    if x < fragment_end_x {
6555                        return Some(
6556                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
6557                        );
6558                    }
6559                    fragment_start_x = fragment_end_x;
6560                    fragment_start_index += shaped_line.len;
6561                }
6562                LineFragment::Element { len, size, .. } => {
6563                    let fragment_end_x = fragment_start_x + size.width;
6564                    if x < fragment_end_x {
6565                        return Some(fragment_start_index);
6566                    }
6567                    fragment_start_index += len;
6568                    fragment_start_x = fragment_end_x;
6569                }
6570            }
6571        }
6572
6573        None
6574    }
6575
6576    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
6577        let mut fragment_start_index = 0;
6578
6579        for fragment in &self.fragments {
6580            match fragment {
6581                LineFragment::Text(shaped_line) => {
6582                    let fragment_end_index = fragment_start_index + shaped_line.len;
6583                    if index < fragment_end_index {
6584                        return shaped_line.font_id_for_index(index - fragment_start_index);
6585                    }
6586                    fragment_start_index = fragment_end_index;
6587                }
6588                LineFragment::Element { len, .. } => {
6589                    let fragment_end_index = fragment_start_index + len;
6590                    if index < fragment_end_index {
6591                        return None;
6592                    }
6593                    fragment_start_index = fragment_end_index;
6594                }
6595            }
6596        }
6597
6598        None
6599    }
6600}
6601
6602#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6603enum Invisible {
6604    /// A tab character
6605    ///
6606    /// A tab character is internally represented by spaces (configured by the user's tab width)
6607    /// aligned to the nearest column, so it's necessary to store the start and end offset for
6608    /// adjacency checks.
6609    Tab {
6610        line_start_offset: usize,
6611        line_end_offset: usize,
6612    },
6613    Whitespace {
6614        line_offset: usize,
6615    },
6616}
6617
6618impl EditorElement {
6619    /// Returns the rem size to use when rendering the [`EditorElement`].
6620    ///
6621    /// This allows UI elements to scale based on the `buffer_font_size`.
6622    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
6623        match self.editor.read(cx).mode {
6624            EditorMode::Full {
6625                scale_ui_elements_with_buffer_font_size,
6626                ..
6627            } => {
6628                if !scale_ui_elements_with_buffer_font_size {
6629                    return None;
6630                }
6631                let buffer_font_size = self.style.text.font_size;
6632                match buffer_font_size {
6633                    AbsoluteLength::Pixels(pixels) => {
6634                        let rem_size_scale = {
6635                            // Our default UI font size is 14px on a 16px base scale.
6636                            // This means the default UI font size is 0.875rems.
6637                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
6638
6639                            // We then determine the delta between a single rem and the default font
6640                            // size scale.
6641                            let default_font_size_delta = 1. - default_font_size_scale;
6642
6643                            // Finally, we add this delta to 1rem to get the scale factor that
6644                            // should be used to scale up the UI.
6645                            1. + default_font_size_delta
6646                        };
6647
6648                        Some(pixels * rem_size_scale)
6649                    }
6650                    AbsoluteLength::Rems(rems) => {
6651                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
6652                    }
6653                }
6654            }
6655            // We currently use single-line and auto-height editors in UI contexts,
6656            // so we don't want to scale everything with the buffer font size, as it
6657            // ends up looking off.
6658            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
6659        }
6660    }
6661}
6662
6663impl Element for EditorElement {
6664    type RequestLayoutState = ();
6665    type PrepaintState = EditorLayout;
6666
6667    fn id(&self) -> Option<ElementId> {
6668        None
6669    }
6670
6671    fn request_layout(
6672        &mut self,
6673        _: Option<&GlobalElementId>,
6674        window: &mut Window,
6675        cx: &mut App,
6676    ) -> (gpui::LayoutId, ()) {
6677        let rem_size = self.rem_size(cx);
6678        window.with_rem_size(rem_size, |window| {
6679            self.editor.update(cx, |editor, cx| {
6680                editor.set_style(self.style.clone(), window, cx);
6681
6682                let layout_id = match editor.mode {
6683                    EditorMode::SingleLine { auto_width } => {
6684                        let rem_size = window.rem_size();
6685
6686                        let height = self.style.text.line_height_in_pixels(rem_size);
6687                        if auto_width {
6688                            let editor_handle = cx.entity().clone();
6689                            let style = self.style.clone();
6690                            window.request_measured_layout(
6691                                Style::default(),
6692                                move |_, _, window, cx| {
6693                                    let editor_snapshot = editor_handle
6694                                        .update(cx, |editor, cx| editor.snapshot(window, cx));
6695                                    let line = Self::layout_lines(
6696                                        DisplayRow(0)..DisplayRow(1),
6697                                        &editor_snapshot,
6698                                        &style,
6699                                        px(f32::MAX),
6700                                        |_| false, // Single lines never soft wrap
6701                                        window,
6702                                        cx,
6703                                    )
6704                                    .pop()
6705                                    .unwrap();
6706
6707                                    let font_id =
6708                                        window.text_system().resolve_font(&style.text.font());
6709                                    let font_size =
6710                                        style.text.font_size.to_pixels(window.rem_size());
6711                                    let em_width =
6712                                        window.text_system().em_width(font_id, font_size).unwrap();
6713
6714                                    size(line.width + em_width, height)
6715                                },
6716                            )
6717                        } else {
6718                            let mut style = Style::default();
6719                            style.size.height = height.into();
6720                            style.size.width = relative(1.).into();
6721                            window.request_layout(style, None, cx)
6722                        }
6723                    }
6724                    EditorMode::AutoHeight { max_lines } => {
6725                        let editor_handle = cx.entity().clone();
6726                        let max_line_number_width =
6727                            self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
6728                        window.request_measured_layout(
6729                            Style::default(),
6730                            move |known_dimensions, available_space, window, cx| {
6731                                editor_handle
6732                                    .update(cx, |editor, cx| {
6733                                        compute_auto_height_layout(
6734                                            editor,
6735                                            max_lines,
6736                                            max_line_number_width,
6737                                            known_dimensions,
6738                                            available_space.width,
6739                                            window,
6740                                            cx,
6741                                        )
6742                                    })
6743                                    .unwrap_or_default()
6744                            },
6745                        )
6746                    }
6747                    EditorMode::Full {
6748                        sized_by_content, ..
6749                    } => {
6750                        let mut style = Style::default();
6751                        style.size.width = relative(1.).into();
6752                        if sized_by_content {
6753                            let snapshot = editor.snapshot(window, cx);
6754                            let line_height =
6755                                self.style.text.line_height_in_pixels(window.rem_size());
6756                            let scroll_height =
6757                                (snapshot.max_point().row().next_row().0 as f32) * line_height;
6758                            style.size.height = scroll_height.into();
6759                        } else {
6760                            style.size.height = relative(1.).into();
6761                        }
6762                        window.request_layout(style, None, cx)
6763                    }
6764                };
6765
6766                (layout_id, ())
6767            })
6768        })
6769    }
6770
6771    fn prepaint(
6772        &mut self,
6773        _: Option<&GlobalElementId>,
6774        bounds: Bounds<Pixels>,
6775        _: &mut Self::RequestLayoutState,
6776        window: &mut Window,
6777        cx: &mut App,
6778    ) -> Self::PrepaintState {
6779        let text_style = TextStyleRefinement {
6780            font_size: Some(self.style.text.font_size),
6781            line_height: Some(self.style.text.line_height),
6782            ..Default::default()
6783        };
6784        let focus_handle = self.editor.focus_handle(cx);
6785        window.set_view_id(self.editor.entity_id());
6786        window.set_focus_handle(&focus_handle, cx);
6787
6788        let rem_size = self.rem_size(cx);
6789        window.with_rem_size(rem_size, |window| {
6790            window.with_text_style(Some(text_style), |window| {
6791                window.with_content_mask(Some(ContentMask { bounds }), |window| {
6792                    let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
6793                        (editor.snapshot(window, cx), editor.read_only(cx))
6794                    });
6795                    let style = self.style.clone();
6796
6797                    let font_id = window.text_system().resolve_font(&style.text.font());
6798                    let font_size = style.text.font_size.to_pixels(window.rem_size());
6799                    let line_height = style.text.line_height_in_pixels(window.rem_size());
6800                    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
6801                    let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
6802
6803                    let glyph_grid_cell = size(em_width, line_height);
6804
6805                    let gutter_dimensions = snapshot
6806                        .gutter_dimensions(
6807                            font_id,
6808                            font_size,
6809                            self.max_line_number_width(&snapshot, window, cx),
6810                            cx,
6811                        )
6812                        .unwrap_or_default();
6813                    let hitbox = window.insert_hitbox(bounds, false);
6814                    let gutter_hitbox =
6815                        window.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
6816                    let text_hitbox = window.insert_hitbox(
6817                        Bounds {
6818                            origin: gutter_hitbox.top_right()
6819                                + point(style.horizontal_padding, Pixels::default()),
6820                            size: size(
6821                                bounds.size.width
6822                                    - gutter_dimensions.width
6823                                    - 2. * style.horizontal_padding,
6824                                bounds.size.height,
6825                            ),
6826                        },
6827                        false,
6828                    );
6829
6830                    let editor_width = text_hitbox.size.width
6831                        - gutter_dimensions.margin
6832                        - em_width
6833                        - style.scrollbar_width;
6834
6835                    snapshot = self.editor.update(cx, |editor, cx| {
6836                        editor.last_bounds = Some(bounds);
6837                        editor.gutter_dimensions = gutter_dimensions;
6838                        editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
6839
6840                        if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
6841                            snapshot
6842                        } else {
6843                            let wrap_width = match editor.soft_wrap_mode(cx) {
6844                                SoftWrap::GitDiff => None,
6845                                SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
6846                                SoftWrap::EditorWidth => Some(editor_width),
6847                                SoftWrap::Column(column) => Some(column as f32 * em_advance),
6848                                SoftWrap::Bounded(column) => {
6849                                    Some(editor_width.min(column as f32 * em_advance))
6850                                }
6851                            };
6852
6853                            if editor.set_wrap_width(wrap_width.map(|w| w.ceil()), cx) {
6854                                editor.snapshot(window, cx)
6855                            } else {
6856                                snapshot
6857                            }
6858                        }
6859                    });
6860
6861                    let wrap_guides = self
6862                        .editor
6863                        .read(cx)
6864                        .wrap_guides(cx)
6865                        .iter()
6866                        .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
6867                        .collect::<SmallVec<[_; 2]>>();
6868
6869                    // Offset the content_bounds from the text_bounds by the gutter margin (which
6870                    // is roughly half a character wide) to make hit testing work more like how we want.
6871                    let content_offset = point(gutter_dimensions.margin, Pixels::ZERO);
6872                    let content_origin = text_hitbox.origin + content_offset;
6873
6874                    let editor_text_bounds =
6875                        Bounds::from_corners(content_origin, text_hitbox.bounds.bottom_right());
6876
6877                    let height_in_lines = editor_text_bounds.size.height / line_height;
6878
6879                    let max_row = snapshot.max_point().row().as_f32();
6880
6881                    // The max scroll position for the top of the window
6882                    let max_scroll_top = if matches!(
6883                        snapshot.mode,
6884                        EditorMode::SingleLine { .. }
6885                            | EditorMode::AutoHeight { .. }
6886                            | EditorMode::Full {
6887                                sized_by_content: true,
6888                                ..
6889                            }
6890                    ) {
6891                        (max_row - height_in_lines + 1.).max(0.)
6892                    } else {
6893                        let settings = EditorSettings::get_global(cx);
6894                        match settings.scroll_beyond_last_line {
6895                            ScrollBeyondLastLine::OnePage => max_row,
6896                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
6897                            ScrollBeyondLastLine::VerticalScrollMargin => {
6898                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
6899                                    .max(0.)
6900                            }
6901                        }
6902                    };
6903
6904                    // TODO: Autoscrolling for both axes
6905                    let mut autoscroll_request = None;
6906                    let mut autoscroll_containing_element = false;
6907                    let mut autoscroll_horizontally = false;
6908                    self.editor.update(cx, |editor, cx| {
6909                        autoscroll_request = editor.autoscroll_request();
6910                        autoscroll_containing_element =
6911                            autoscroll_request.is_some() || editor.has_pending_selection();
6912                        // TODO: Is this horizontal or vertical?!
6913                        autoscroll_horizontally = editor.autoscroll_vertically(
6914                            bounds,
6915                            line_height,
6916                            max_scroll_top,
6917                            window,
6918                            cx,
6919                        );
6920                        snapshot = editor.snapshot(window, cx);
6921                    });
6922
6923                    let mut scroll_position = snapshot.scroll_position();
6924                    // The scroll position is a fractional point, the whole number of which represents
6925                    // the top of the window in terms of display rows.
6926                    let start_row = DisplayRow(scroll_position.y as u32);
6927                    let max_row = snapshot.max_point().row();
6928                    let end_row = cmp::min(
6929                        (scroll_position.y + height_in_lines).ceil() as u32,
6930                        max_row.next_row().0,
6931                    );
6932                    let end_row = DisplayRow(end_row);
6933
6934                    let row_infos = snapshot
6935                        .row_infos(start_row)
6936                        .take((start_row..end_row).len())
6937                        .collect::<Vec<RowInfo>>();
6938                    let is_row_soft_wrapped = |row: usize| {
6939                        row_infos
6940                            .get(row)
6941                            .map_or(true, |info| info.buffer_row.is_none())
6942                    };
6943
6944                    let start_anchor = if start_row == Default::default() {
6945                        Anchor::min()
6946                    } else {
6947                        snapshot.buffer_snapshot.anchor_before(
6948                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
6949                        )
6950                    };
6951                    let end_anchor = if end_row > max_row {
6952                        Anchor::max()
6953                    } else {
6954                        snapshot.buffer_snapshot.anchor_before(
6955                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
6956                        )
6957                    };
6958
6959                    let mut highlighted_rows = self
6960                        .editor
6961                        .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
6962
6963                    let is_light = cx.theme().appearance().is_light();
6964
6965                    for (ix, row_info) in row_infos.iter().enumerate() {
6966                        let Some(diff_status) = row_info.diff_status else {
6967                            continue;
6968                        };
6969
6970                        let background_color = match diff_status.kind {
6971                            DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
6972                            DiffHunkStatusKind::Deleted => {
6973                                cx.theme().colors().version_control_deleted
6974                            }
6975                            DiffHunkStatusKind::Modified => {
6976                                debug_panic!("modified diff status for row info");
6977                                continue;
6978                            }
6979                        };
6980
6981                        let hunk_opacity = if is_light { 0.16 } else { 0.12 };
6982
6983                        let hollow_highlight = LineHighlight {
6984                            background: (background_color.opacity(if is_light {
6985                                0.08
6986                            } else {
6987                                0.06
6988                            }))
6989                            .into(),
6990                            border: Some(if is_light {
6991                                background_color.opacity(0.48)
6992                            } else {
6993                                background_color.opacity(0.36)
6994                            }),
6995                            include_gutter: true,
6996                            type_id: None,
6997                        };
6998
6999                        let filled_highlight = LineHighlight {
7000                            background: solid_background(background_color.opacity(hunk_opacity)),
7001                            border: None,
7002                            include_gutter: true,
7003                            type_id: None,
7004                        };
7005
7006                        let background = if Self::diff_hunk_hollow(diff_status, cx) {
7007                            hollow_highlight
7008                        } else {
7009                            filled_highlight
7010                        };
7011
7012                        highlighted_rows
7013                            .entry(start_row + DisplayRow(ix as u32))
7014                            .or_insert(background);
7015                    }
7016
7017                    let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
7018                        start_anchor..end_anchor,
7019                        &snapshot.display_snapshot,
7020                        cx.theme().colors(),
7021                    );
7022                    let highlighted_gutter_ranges =
7023                        self.editor.read(cx).gutter_highlights_in_range(
7024                            start_anchor..end_anchor,
7025                            &snapshot.display_snapshot,
7026                            cx,
7027                        );
7028
7029                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
7030                        start_anchor..end_anchor,
7031                        &snapshot.display_snapshot,
7032                        cx,
7033                    );
7034
7035                    let (local_selections, selected_buffer_ids): (
7036                        Vec<Selection<Point>>,
7037                        Vec<BufferId>,
7038                    ) = self.editor.update(cx, |editor, cx| {
7039                        let all_selections = editor.selections.all::<Point>(cx);
7040                        let selected_buffer_ids = if editor.is_singleton(cx) {
7041                            Vec::new()
7042                        } else {
7043                            let mut selected_buffer_ids = Vec::with_capacity(all_selections.len());
7044
7045                            for selection in all_selections {
7046                                for buffer_id in snapshot
7047                                    .buffer_snapshot
7048                                    .buffer_ids_for_range(selection.range())
7049                                {
7050                                    if selected_buffer_ids.last() != Some(&buffer_id) {
7051                                        selected_buffer_ids.push(buffer_id);
7052                                    }
7053                                }
7054                            }
7055
7056                            selected_buffer_ids
7057                        };
7058
7059                        let mut selections = editor
7060                            .selections
7061                            .disjoint_in_range(start_anchor..end_anchor, cx);
7062                        selections.extend(editor.selections.pending(cx));
7063
7064                        (selections, selected_buffer_ids)
7065                    });
7066
7067                    let (selections, mut active_rows, newest_selection_head) = self
7068                        .layout_selections(
7069                            start_anchor,
7070                            end_anchor,
7071                            &local_selections,
7072                            &snapshot,
7073                            start_row,
7074                            end_row,
7075                            window,
7076                            cx,
7077                        );
7078                    let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
7079                        editor.active_breakpoints(start_row..end_row, window, cx)
7080                    });
7081                    if cx.has_flag::<DebuggerFeatureFlag>() {
7082                        for display_row in breakpoint_rows.keys() {
7083                            active_rows.entry(*display_row).or_default().breakpoint = true;
7084                        }
7085                    }
7086
7087                    let line_numbers = self.layout_line_numbers(
7088                        Some(&gutter_hitbox),
7089                        gutter_dimensions,
7090                        line_height,
7091                        scroll_position,
7092                        start_row..end_row,
7093                        &row_infos,
7094                        &active_rows,
7095                        newest_selection_head,
7096                        &snapshot,
7097                        window,
7098                        cx,
7099                    );
7100
7101                    // We add the gutter breakpoint indicator to breakpoint_rows after painting
7102                    // line numbers so we don't paint a line number debug accent color if a user
7103                    // has their mouse over that line when a breakpoint isn't there
7104                    if cx.has_flag::<DebuggerFeatureFlag>() {
7105                        self.editor.update(cx, |editor, _| {
7106                            if let Some(phantom_breakpoint) = &mut editor
7107                                .gutter_breakpoint_indicator
7108                                .0
7109                                .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
7110                            {
7111                                // Is there a non-phantom breakpoint on this line?
7112                                phantom_breakpoint.collides_with_existing_breakpoint = true;
7113                                breakpoint_rows
7114                                    .entry(phantom_breakpoint.display_row)
7115                                    .or_insert_with(|| {
7116                                        let position = snapshot.display_point_to_anchor(
7117                                            DisplayPoint::new(phantom_breakpoint.display_row, 0),
7118                                            Bias::Right,
7119                                        );
7120                                        let breakpoint = Breakpoint::new_standard();
7121                                        phantom_breakpoint.collides_with_existing_breakpoint =
7122                                            false;
7123                                        (position, breakpoint)
7124                                    });
7125                            }
7126                        })
7127                    }
7128
7129                    let mut expand_toggles =
7130                        window.with_element_namespace("expand_toggles", |window| {
7131                            self.layout_expand_toggles(
7132                                &gutter_hitbox,
7133                                gutter_dimensions,
7134                                em_width,
7135                                line_height,
7136                                scroll_position,
7137                                &row_infos,
7138                                window,
7139                                cx,
7140                            )
7141                        });
7142
7143                    let mut crease_toggles =
7144                        window.with_element_namespace("crease_toggles", |window| {
7145                            self.layout_crease_toggles(
7146                                start_row..end_row,
7147                                &row_infos,
7148                                &active_rows,
7149                                &snapshot,
7150                                window,
7151                                cx,
7152                            )
7153                        });
7154                    let crease_trailers =
7155                        window.with_element_namespace("crease_trailers", |window| {
7156                            self.layout_crease_trailers(
7157                                row_infos.iter().copied(),
7158                                &snapshot,
7159                                window,
7160                                cx,
7161                            )
7162                        });
7163
7164                    let display_hunks = self.layout_gutter_diff_hunks(
7165                        line_height,
7166                        &gutter_hitbox,
7167                        start_row..end_row,
7168                        &snapshot,
7169                        window,
7170                        cx,
7171                    );
7172
7173                    let mut line_layouts = Self::layout_lines(
7174                        start_row..end_row,
7175                        &snapshot,
7176                        &self.style,
7177                        editor_width,
7178                        is_row_soft_wrapped,
7179                        window,
7180                        cx,
7181                    );
7182                    let new_fold_widths = line_layouts
7183                        .iter()
7184                        .flat_map(|layout| &layout.fragments)
7185                        .filter_map(|fragment| {
7186                            if let LineFragment::Element { id, size, .. } = fragment {
7187                                Some((*id, size.width))
7188                            } else {
7189                                None
7190                            }
7191                        });
7192                    if self.editor.update(cx, |editor, cx| {
7193                        editor.update_fold_widths(new_fold_widths, cx)
7194                    }) {
7195                        // If the fold widths have changed, we need to prepaint
7196                        // the element again to account for any changes in
7197                        // wrapping.
7198                        return self.prepaint(None, bounds, &mut (), window, cx);
7199                    }
7200
7201                    let longest_line_blame_width = self
7202                        .editor
7203                        .update(cx, |editor, cx| {
7204                            if !editor.show_git_blame_inline {
7205                                return None;
7206                            }
7207                            let blame = editor.blame.as_ref()?;
7208                            let blame_entry = blame
7209                                .update(cx, |blame, cx| {
7210                                    let row_infos =
7211                                        snapshot.row_infos(snapshot.longest_row()).next()?;
7212                                    blame.blame_for_rows(&[row_infos], cx).next()
7213                                })
7214                                .flatten()?;
7215                            let mut element = render_inline_blame_entry(blame_entry, &style, cx)?;
7216                            let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
7217                            Some(
7218                                element
7219                                    .layout_as_root(AvailableSpace::min_size(), window, cx)
7220                                    .width
7221                                    + inline_blame_padding,
7222                            )
7223                        })
7224                        .unwrap_or(Pixels::ZERO);
7225
7226                    let longest_line_width = layout_line(
7227                        snapshot.longest_row(),
7228                        &snapshot,
7229                        &style,
7230                        editor_width,
7231                        is_row_soft_wrapped,
7232                        window,
7233                        cx,
7234                    )
7235                    .width;
7236
7237                    let scrollbar_layout_information = ScrollbarLayoutInformation::new(
7238                        text_hitbox.bounds,
7239                        glyph_grid_cell,
7240                        size(longest_line_width, max_row.as_f32() * line_height),
7241                        longest_line_blame_width,
7242                        style.scrollbar_width,
7243                        editor_width,
7244                        EditorSettings::get_global(cx),
7245                    );
7246
7247                    let mut scroll_width = scrollbar_layout_information.scroll_range.width;
7248
7249                    let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
7250                        snapshot.sticky_header_excerpt(scroll_position.y)
7251                    } else {
7252                        None
7253                    };
7254                    let sticky_header_excerpt_id =
7255                        sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
7256
7257                    let blocks = window.with_element_namespace("blocks", |window| {
7258                        self.render_blocks(
7259                            start_row..end_row,
7260                            &snapshot,
7261                            &hitbox,
7262                            &text_hitbox,
7263                            editor_width,
7264                            &mut scroll_width,
7265                            &gutter_dimensions,
7266                            em_width,
7267                            gutter_dimensions.full_width(),
7268                            line_height,
7269                            &mut line_layouts,
7270                            &local_selections,
7271                            &selected_buffer_ids,
7272                            is_row_soft_wrapped,
7273                            sticky_header_excerpt_id,
7274                            window,
7275                            cx,
7276                        )
7277                    });
7278                    let (mut blocks, row_block_types) = match blocks {
7279                        Ok(blocks) => blocks,
7280                        Err(resized_blocks) => {
7281                            self.editor.update(cx, |editor, cx| {
7282                                editor.resize_blocks(resized_blocks, autoscroll_request, cx)
7283                            });
7284                            return self.prepaint(None, bounds, &mut (), window, cx);
7285                        }
7286                    };
7287
7288                    let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
7289                        window.with_element_namespace("blocks", |window| {
7290                            self.layout_sticky_buffer_header(
7291                                sticky_header_excerpt,
7292                                scroll_position.y,
7293                                line_height,
7294                                &snapshot,
7295                                &hitbox,
7296                                &selected_buffer_ids,
7297                                &blocks,
7298                                window,
7299                                cx,
7300                            )
7301                        })
7302                    });
7303
7304                    let start_buffer_row =
7305                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
7306                    let end_buffer_row =
7307                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
7308
7309                    let scroll_max = point(
7310                        ((scroll_width - editor_text_bounds.size.width) / em_width).max(0.0),
7311                        max_scroll_top,
7312                    );
7313
7314                    self.editor.update(cx, |editor, cx| {
7315                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7316
7317                        let autoscrolled = if autoscroll_horizontally {
7318                            editor.autoscroll_horizontally(
7319                                start_row,
7320                                editor_width - (glyph_grid_cell.width / 2.0)
7321                                    + style.scrollbar_width,
7322                                scroll_width,
7323                                em_width,
7324                                &line_layouts,
7325                                cx,
7326                            )
7327                        } else {
7328                            false
7329                        };
7330
7331                        if clamped || autoscrolled {
7332                            snapshot = editor.snapshot(window, cx);
7333                            scroll_position = snapshot.scroll_position();
7334                        }
7335                    });
7336
7337                    let scroll_pixel_position = point(
7338                        scroll_position.x * em_width,
7339                        scroll_position.y * line_height,
7340                    );
7341
7342                    let indent_guides = self.layout_indent_guides(
7343                        content_origin,
7344                        text_hitbox.origin,
7345                        start_buffer_row..end_buffer_row,
7346                        scroll_pixel_position,
7347                        line_height,
7348                        &snapshot,
7349                        window,
7350                        cx,
7351                    );
7352
7353                    let crease_trailers =
7354                        window.with_element_namespace("crease_trailers", |window| {
7355                            self.prepaint_crease_trailers(
7356                                crease_trailers,
7357                                &line_layouts,
7358                                line_height,
7359                                content_origin,
7360                                scroll_pixel_position,
7361                                em_width,
7362                                window,
7363                                cx,
7364                            )
7365                        });
7366
7367                    let (inline_completion_popover, inline_completion_popover_origin) = self
7368                        .editor
7369                        .update(cx, |editor, cx| {
7370                            editor.render_edit_prediction_popover(
7371                                &text_hitbox.bounds,
7372                                content_origin,
7373                                &snapshot,
7374                                start_row..end_row,
7375                                scroll_position.y,
7376                                scroll_position.y + height_in_lines,
7377                                &line_layouts,
7378                                line_height,
7379                                scroll_pixel_position,
7380                                newest_selection_head,
7381                                editor_width,
7382                                &style,
7383                                window,
7384                                cx,
7385                            )
7386                        })
7387                        .unzip();
7388
7389                    let mut inline_diagnostics = self.layout_inline_diagnostics(
7390                        &line_layouts,
7391                        &crease_trailers,
7392                        &row_block_types,
7393                        content_origin,
7394                        scroll_pixel_position,
7395                        inline_completion_popover_origin,
7396                        start_row,
7397                        end_row,
7398                        line_height,
7399                        em_width,
7400                        &style,
7401                        window,
7402                        cx,
7403                    );
7404
7405                    let mut inline_blame = None;
7406                    if let Some(newest_selection_head) = newest_selection_head {
7407                        let display_row = newest_selection_head.row();
7408                        if (start_row..end_row).contains(&display_row)
7409                            && !row_block_types.contains_key(&display_row)
7410                        {
7411                            let line_ix = display_row.minus(start_row) as usize;
7412                            let row_info = &row_infos[line_ix];
7413                            let line_layout = &line_layouts[line_ix];
7414                            let crease_trailer_layout = crease_trailers[line_ix].as_ref();
7415                            inline_blame = self.layout_inline_blame(
7416                                display_row,
7417                                row_info,
7418                                line_layout,
7419                                crease_trailer_layout,
7420                                em_width,
7421                                content_origin,
7422                                scroll_pixel_position,
7423                                line_height,
7424                                &text_hitbox,
7425                                window,
7426                                cx,
7427                            );
7428                            if inline_blame.is_some() {
7429                                // Blame overrides inline diagnostics
7430                                inline_diagnostics.remove(&display_row);
7431                            }
7432                        }
7433                    }
7434
7435                    let blamed_display_rows = self.layout_blame_entries(
7436                        &row_infos,
7437                        em_width,
7438                        scroll_position,
7439                        line_height,
7440                        &gutter_hitbox,
7441                        gutter_dimensions.git_blame_entries_width,
7442                        window,
7443                        cx,
7444                    );
7445
7446                    self.editor.update(cx, |editor, cx| {
7447                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7448
7449                        let autoscrolled = if autoscroll_horizontally {
7450                            editor.autoscroll_horizontally(
7451                                start_row,
7452                                editor_width - (glyph_grid_cell.width / 2.0)
7453                                    + style.scrollbar_width,
7454                                scroll_width,
7455                                em_width,
7456                                &line_layouts,
7457                                cx,
7458                            )
7459                        } else {
7460                            false
7461                        };
7462
7463                        if clamped || autoscrolled {
7464                            snapshot = editor.snapshot(window, cx);
7465                            scroll_position = snapshot.scroll_position();
7466                        }
7467                    });
7468
7469                    let line_elements = self.prepaint_lines(
7470                        start_row,
7471                        &mut line_layouts,
7472                        line_height,
7473                        scroll_pixel_position,
7474                        content_origin,
7475                        window,
7476                        cx,
7477                    );
7478
7479                    window.with_element_namespace("blocks", |window| {
7480                        self.layout_blocks(
7481                            &mut blocks,
7482                            &hitbox,
7483                            line_height,
7484                            scroll_pixel_position,
7485                            window,
7486                            cx,
7487                        );
7488                    });
7489
7490                    let cursors = self.collect_cursors(&snapshot, cx);
7491                    let visible_row_range = start_row..end_row;
7492                    let non_visible_cursors = cursors
7493                        .iter()
7494                        .any(|c| !visible_row_range.contains(&c.0.row()));
7495
7496                    let visible_cursors = self.layout_visible_cursors(
7497                        &snapshot,
7498                        &selections,
7499                        &row_block_types,
7500                        start_row..end_row,
7501                        &line_layouts,
7502                        &text_hitbox,
7503                        content_origin,
7504                        scroll_position,
7505                        scroll_pixel_position,
7506                        line_height,
7507                        em_width,
7508                        em_advance,
7509                        autoscroll_containing_element,
7510                        window,
7511                        cx,
7512                    );
7513
7514                    let scrollbars_layout = self.layout_scrollbars(
7515                        &snapshot,
7516                        scrollbar_layout_information,
7517                        content_offset,
7518                        scroll_position,
7519                        non_visible_cursors,
7520                        window,
7521                        cx,
7522                    );
7523
7524                    let gutter_settings = EditorSettings::get_global(cx).gutter;
7525
7526                    let mut code_actions_indicator = None;
7527                    if let Some(newest_selection_head) = newest_selection_head {
7528                        let newest_selection_point =
7529                            newest_selection_head.to_point(&snapshot.display_snapshot);
7530
7531                        if (start_row..end_row).contains(&newest_selection_head.row()) {
7532                            self.layout_cursor_popovers(
7533                                line_height,
7534                                &text_hitbox,
7535                                content_origin,
7536                                start_row,
7537                                scroll_pixel_position,
7538                                &line_layouts,
7539                                newest_selection_head,
7540                                newest_selection_point,
7541                                &style,
7542                                window,
7543                                cx,
7544                            );
7545
7546                            let show_code_actions = snapshot
7547                                .show_code_actions
7548                                .unwrap_or(gutter_settings.code_actions);
7549                            if show_code_actions {
7550                                let newest_selection_point =
7551                                    newest_selection_head.to_point(&snapshot.display_snapshot);
7552                                if !snapshot
7553                                    .is_line_folded(MultiBufferRow(newest_selection_point.row))
7554                                {
7555                                    let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
7556                                        MultiBufferRow(newest_selection_point.row),
7557                                    );
7558                                    if let Some((buffer, range)) = buffer {
7559                                        let buffer_id = buffer.remote_id();
7560                                        let row = range.start.row;
7561                                        let has_test_indicator = self
7562                                            .editor
7563                                            .read(cx)
7564                                            .tasks
7565                                            .contains_key(&(buffer_id, row));
7566
7567                                        let has_expand_indicator = row_infos
7568                                            .get(
7569                                                (newest_selection_head.row() - start_row).0
7570                                                    as usize,
7571                                            )
7572                                            .is_some_and(|row_info| row_info.expand_info.is_some());
7573
7574                                        if !has_test_indicator && !has_expand_indicator {
7575                                            code_actions_indicator = self
7576                                                .layout_code_actions_indicator(
7577                                                    line_height,
7578                                                    newest_selection_head,
7579                                                    scroll_pixel_position,
7580                                                    &gutter_dimensions,
7581                                                    &gutter_hitbox,
7582                                                    &mut breakpoint_rows,
7583                                                    &display_hunks,
7584                                                    window,
7585                                                    cx,
7586                                                );
7587                                        }
7588                                    }
7589                                }
7590                            }
7591                        }
7592                    }
7593
7594                    self.layout_gutter_menu(
7595                        line_height,
7596                        &text_hitbox,
7597                        content_origin,
7598                        scroll_pixel_position,
7599                        gutter_dimensions.width - gutter_dimensions.left_padding,
7600                        window,
7601                        cx,
7602                    );
7603
7604                    let test_indicators = if gutter_settings.runnables {
7605                        self.layout_run_indicators(
7606                            line_height,
7607                            start_row..end_row,
7608                            &row_infos,
7609                            scroll_pixel_position,
7610                            &gutter_dimensions,
7611                            &gutter_hitbox,
7612                            &display_hunks,
7613                            &snapshot,
7614                            &mut breakpoint_rows,
7615                            window,
7616                            cx,
7617                        )
7618                    } else {
7619                        Vec::new()
7620                    };
7621
7622                    let show_breakpoints = snapshot
7623                        .show_breakpoints
7624                        .unwrap_or(gutter_settings.breakpoints);
7625                    let breakpoints = if cx.has_flag::<DebuggerFeatureFlag>() && show_breakpoints {
7626                        self.layout_breakpoints(
7627                            line_height,
7628                            start_row..end_row,
7629                            scroll_pixel_position,
7630                            &gutter_dimensions,
7631                            &gutter_hitbox,
7632                            &display_hunks,
7633                            &snapshot,
7634                            breakpoint_rows,
7635                            &row_infos,
7636                            window,
7637                            cx,
7638                        )
7639                    } else {
7640                        vec![]
7641                    };
7642
7643                    self.layout_signature_help(
7644                        &hitbox,
7645                        &text_hitbox,
7646                        content_origin,
7647                        scroll_pixel_position,
7648                        newest_selection_head,
7649                        start_row,
7650                        &line_layouts,
7651                        line_height,
7652                        em_width,
7653                        window,
7654                        cx,
7655                    );
7656
7657                    if !cx.has_active_drag() {
7658                        self.layout_hover_popovers(
7659                            &snapshot,
7660                            &hitbox,
7661                            &text_hitbox,
7662                            start_row..end_row,
7663                            content_origin,
7664                            scroll_pixel_position,
7665                            &line_layouts,
7666                            line_height,
7667                            em_width,
7668                            window,
7669                            cx,
7670                        );
7671                    }
7672
7673                    let mouse_context_menu = self.layout_mouse_context_menu(
7674                        &snapshot,
7675                        start_row..end_row,
7676                        content_origin,
7677                        window,
7678                        cx,
7679                    );
7680
7681                    window.with_element_namespace("crease_toggles", |window| {
7682                        self.prepaint_crease_toggles(
7683                            &mut crease_toggles,
7684                            line_height,
7685                            &gutter_dimensions,
7686                            gutter_settings,
7687                            scroll_pixel_position,
7688                            &gutter_hitbox,
7689                            window,
7690                            cx,
7691                        )
7692                    });
7693
7694                    window.with_element_namespace("expand_toggles", |window| {
7695                        self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
7696                    });
7697
7698                    let invisible_symbol_font_size = font_size / 2.;
7699                    let tab_invisible = window
7700                        .text_system()
7701                        .shape_line(
7702                            "".into(),
7703                            invisible_symbol_font_size,
7704                            &[TextRun {
7705                                len: "".len(),
7706                                font: self.style.text.font(),
7707                                color: cx.theme().colors().editor_invisible,
7708                                background_color: None,
7709                                underline: None,
7710                                strikethrough: None,
7711                            }],
7712                        )
7713                        .unwrap();
7714                    let space_invisible = window
7715                        .text_system()
7716                        .shape_line(
7717                            "".into(),
7718                            invisible_symbol_font_size,
7719                            &[TextRun {
7720                                len: "".len(),
7721                                font: self.style.text.font(),
7722                                color: cx.theme().colors().editor_invisible,
7723                                background_color: None,
7724                                underline: None,
7725                                strikethrough: None,
7726                            }],
7727                        )
7728                        .unwrap();
7729
7730                    let mode = snapshot.mode;
7731
7732                    let position_map = Rc::new(PositionMap {
7733                        size: bounds.size,
7734                        visible_row_range,
7735                        scroll_pixel_position,
7736                        scroll_max,
7737                        line_layouts,
7738                        line_height,
7739                        em_width,
7740                        em_advance,
7741                        snapshot,
7742                        gutter_hitbox: gutter_hitbox.clone(),
7743                        text_hitbox: text_hitbox.clone(),
7744                    });
7745
7746                    self.editor.update(cx, |editor, _| {
7747                        editor.last_position_map = Some(position_map.clone())
7748                    });
7749
7750                    let diff_hunk_controls = if is_read_only {
7751                        vec![]
7752                    } else {
7753                        self.layout_diff_hunk_controls(
7754                            start_row..end_row,
7755                            &row_infos,
7756                            &text_hitbox,
7757                            &position_map,
7758                            newest_selection_head,
7759                            line_height,
7760                            scroll_pixel_position,
7761                            &display_hunks,
7762                            &highlighted_rows,
7763                            self.editor.clone(),
7764                            window,
7765                            cx,
7766                        )
7767                    };
7768
7769                    EditorLayout {
7770                        mode,
7771                        position_map,
7772                        visible_display_row_range: start_row..end_row,
7773                        wrap_guides,
7774                        indent_guides,
7775                        hitbox,
7776                        gutter_hitbox,
7777                        display_hunks,
7778                        content_origin,
7779                        scrollbars_layout,
7780                        active_rows,
7781                        highlighted_rows,
7782                        highlighted_ranges,
7783                        highlighted_gutter_ranges,
7784                        redacted_ranges,
7785                        line_elements,
7786                        line_numbers,
7787                        blamed_display_rows,
7788                        inline_diagnostics,
7789                        inline_blame,
7790                        blocks,
7791                        cursors,
7792                        visible_cursors,
7793                        selections,
7794                        inline_completion_popover,
7795                        diff_hunk_controls,
7796                        mouse_context_menu,
7797                        test_indicators,
7798                        breakpoints,
7799                        code_actions_indicator,
7800                        crease_toggles,
7801                        crease_trailers,
7802                        tab_invisible,
7803                        space_invisible,
7804                        sticky_buffer_header,
7805                        expand_toggles,
7806                    }
7807                })
7808            })
7809        })
7810    }
7811
7812    fn paint(
7813        &mut self,
7814        _: Option<&GlobalElementId>,
7815        bounds: Bounds<gpui::Pixels>,
7816        _: &mut Self::RequestLayoutState,
7817        layout: &mut Self::PrepaintState,
7818        window: &mut Window,
7819        cx: &mut App,
7820    ) {
7821        let focus_handle = self.editor.focus_handle(cx);
7822        let key_context = self
7823            .editor
7824            .update(cx, |editor, cx| editor.key_context(window, cx));
7825
7826        window.set_key_context(key_context);
7827        window.handle_input(
7828            &focus_handle,
7829            ElementInputHandler::new(bounds, self.editor.clone()),
7830            cx,
7831        );
7832        self.register_actions(window, cx);
7833        self.register_key_listeners(window, cx, layout);
7834
7835        let text_style = TextStyleRefinement {
7836            font_size: Some(self.style.text.font_size),
7837            line_height: Some(self.style.text.line_height),
7838            ..Default::default()
7839        };
7840        let rem_size = self.rem_size(cx);
7841        window.with_rem_size(rem_size, |window| {
7842            window.with_text_style(Some(text_style), |window| {
7843                window.with_content_mask(Some(ContentMask { bounds }), |window| {
7844                    self.paint_mouse_listeners(layout, window, cx);
7845                    self.paint_background(layout, window, cx);
7846                    self.paint_indent_guides(layout, window, cx);
7847
7848                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
7849                        self.paint_blamed_display_rows(layout, window, cx);
7850                        self.paint_line_numbers(layout, window, cx);
7851                    }
7852
7853                    self.paint_text(layout, window, cx);
7854
7855                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
7856                        self.paint_gutter_highlights(layout, window, cx);
7857                        self.paint_gutter_indicators(layout, window, cx);
7858                    }
7859
7860                    if !layout.blocks.is_empty() {
7861                        window.with_element_namespace("blocks", |window| {
7862                            self.paint_blocks(layout, window, cx);
7863                        });
7864                    }
7865
7866                    window.with_element_namespace("blocks", |window| {
7867                        if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
7868                            sticky_header.paint(window, cx)
7869                        }
7870                    });
7871
7872                    self.paint_scrollbars(layout, window, cx);
7873                    self.paint_inline_completion_popover(layout, window, cx);
7874                    self.paint_mouse_context_menu(layout, window, cx);
7875                });
7876            })
7877        })
7878    }
7879}
7880
7881pub(super) fn gutter_bounds(
7882    editor_bounds: Bounds<Pixels>,
7883    gutter_dimensions: GutterDimensions,
7884) -> Bounds<Pixels> {
7885    Bounds {
7886        origin: editor_bounds.origin,
7887        size: size(gutter_dimensions.width, editor_bounds.size.height),
7888    }
7889}
7890
7891/// Holds information required for layouting the editor scrollbars.
7892struct ScrollbarLayoutInformation {
7893    /// The bounds of the editor area (excluding the content offset).
7894    editor_bounds: Bounds<Pixels>,
7895    /// The available range to scroll within the document.
7896    scroll_range: Size<Pixels>,
7897    /// The space available for one glyph in the editor.
7898    glyph_grid_cell: Size<Pixels>,
7899}
7900
7901impl ScrollbarLayoutInformation {
7902    pub fn new(
7903        editor_bounds: Bounds<Pixels>,
7904        glyph_grid_cell: Size<Pixels>,
7905        document_size: Size<Pixels>,
7906        longest_line_blame_width: Pixels,
7907        scrollbar_width: Pixels,
7908        editor_width: Pixels,
7909        settings: &EditorSettings,
7910    ) -> Self {
7911        let vertical_overscroll = match settings.scroll_beyond_last_line {
7912            ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
7913            ScrollBeyondLastLine::Off => glyph_grid_cell.height,
7914            ScrollBeyondLastLine::VerticalScrollMargin => {
7915                (1.0 + settings.vertical_scroll_margin) * glyph_grid_cell.height
7916            }
7917        };
7918
7919        let right_margin = if document_size.width + longest_line_blame_width >= editor_width {
7920            glyph_grid_cell.width + scrollbar_width
7921        } else {
7922            px(0.0)
7923        };
7924
7925        let overscroll = size(right_margin + longest_line_blame_width, vertical_overscroll);
7926
7927        let scroll_range = document_size + overscroll;
7928
7929        ScrollbarLayoutInformation {
7930            editor_bounds,
7931            scroll_range,
7932            glyph_grid_cell,
7933        }
7934    }
7935}
7936
7937impl IntoElement for EditorElement {
7938    type Element = Self;
7939
7940    fn into_element(self) -> Self::Element {
7941        self
7942    }
7943}
7944
7945pub struct EditorLayout {
7946    position_map: Rc<PositionMap>,
7947    hitbox: Hitbox,
7948    gutter_hitbox: Hitbox,
7949    content_origin: gpui::Point<Pixels>,
7950    scrollbars_layout: Option<EditorScrollbars>,
7951    mode: EditorMode,
7952    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
7953    indent_guides: Option<Vec<IndentGuideLayout>>,
7954    visible_display_row_range: Range<DisplayRow>,
7955    active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
7956    highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
7957    line_elements: SmallVec<[AnyElement; 1]>,
7958    line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
7959    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
7960    blamed_display_rows: Option<Vec<AnyElement>>,
7961    inline_diagnostics: HashMap<DisplayRow, AnyElement>,
7962    inline_blame: Option<AnyElement>,
7963    blocks: Vec<BlockLayout>,
7964    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7965    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7966    redacted_ranges: Vec<Range<DisplayPoint>>,
7967    cursors: Vec<(DisplayPoint, Hsla)>,
7968    visible_cursors: Vec<CursorLayout>,
7969    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
7970    code_actions_indicator: Option<AnyElement>,
7971    test_indicators: Vec<AnyElement>,
7972    breakpoints: Vec<AnyElement>,
7973    crease_toggles: Vec<Option<AnyElement>>,
7974    expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
7975    diff_hunk_controls: Vec<AnyElement>,
7976    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
7977    inline_completion_popover: Option<AnyElement>,
7978    mouse_context_menu: Option<AnyElement>,
7979    tab_invisible: ShapedLine,
7980    space_invisible: ShapedLine,
7981    sticky_buffer_header: Option<AnyElement>,
7982}
7983
7984impl EditorLayout {
7985    fn line_end_overshoot(&self) -> Pixels {
7986        0.15 * self.position_map.line_height
7987    }
7988}
7989
7990struct LineNumberLayout {
7991    shaped_line: ShapedLine,
7992    hitbox: Option<Hitbox>,
7993}
7994
7995struct ColoredRange<T> {
7996    start: T,
7997    end: T,
7998    color: Hsla,
7999}
8000
8001impl Along for ScrollbarAxes {
8002    type Unit = bool;
8003
8004    fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
8005        match axis {
8006            ScrollbarAxis::Horizontal => self.horizontal,
8007            ScrollbarAxis::Vertical => self.vertical,
8008        }
8009    }
8010
8011    fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
8012        match axis {
8013            ScrollbarAxis::Horizontal => ScrollbarAxes {
8014                horizontal: f(self.horizontal),
8015                vertical: self.vertical,
8016            },
8017            ScrollbarAxis::Vertical => ScrollbarAxes {
8018                horizontal: self.horizontal,
8019                vertical: f(self.vertical),
8020            },
8021        }
8022    }
8023}
8024
8025#[derive(Clone)]
8026struct EditorScrollbars {
8027    pub vertical: Option<ScrollbarLayout>,
8028    pub horizontal: Option<ScrollbarLayout>,
8029    pub visible: bool,
8030}
8031
8032impl EditorScrollbars {
8033    pub fn from_scrollbar_axes(
8034        settings_visibility: ScrollbarAxes,
8035        layout_information: &ScrollbarLayoutInformation,
8036        content_offset: gpui::Point<Pixels>,
8037        scroll_position: gpui::Point<f32>,
8038        scrollbar_width: Pixels,
8039        show_scrollbars: bool,
8040        window: &mut Window,
8041    ) -> Self {
8042        let ScrollbarLayoutInformation {
8043            editor_bounds,
8044            scroll_range,
8045            glyph_grid_cell,
8046        } = layout_information;
8047
8048        let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
8049            ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
8050                Corner::BottomLeft,
8051                editor_bounds.bottom_left(),
8052                size(
8053                    if settings_visibility.vertical {
8054                        editor_bounds.size.width - scrollbar_width
8055                    } else {
8056                        editor_bounds.size.width
8057                    },
8058                    scrollbar_width,
8059                ),
8060            ),
8061            ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
8062                Corner::TopRight,
8063                editor_bounds.top_right(),
8064                size(scrollbar_width, editor_bounds.size.height),
8065            ),
8066        };
8067
8068        let mut create_scrollbar_layout = |axis| {
8069            settings_visibility
8070                .along(axis)
8071                .then(|| {
8072                    (
8073                        editor_bounds.size.along(axis) - content_offset.along(axis),
8074                        scroll_range.along(axis),
8075                    )
8076                })
8077                .filter(|(editor_content_size, scroll_range)| {
8078                    // The scrollbar should only be rendered if the content does
8079                    // not entirely fit into the editor
8080                    // However, this only applies to the horizontal scrollbar, as information about the
8081                    // vertical scrollbar layout is always needed for scrollbar diagnostics.
8082                    axis != ScrollbarAxis::Horizontal || editor_content_size < scroll_range
8083                })
8084                .map(|(editor_content_size, scroll_range)| {
8085                    ScrollbarLayout::new(
8086                        window.insert_hitbox(scrollbar_bounds_for(axis), false),
8087                        editor_content_size,
8088                        scroll_range,
8089                        glyph_grid_cell.along(axis),
8090                        content_offset.along(axis),
8091                        scroll_position.along(axis),
8092                        axis,
8093                    )
8094                })
8095        };
8096
8097        Self {
8098            vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
8099            horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
8100            visible: show_scrollbars,
8101        }
8102    }
8103
8104    pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
8105        [
8106            (&self.vertical, ScrollbarAxis::Vertical),
8107            (&self.horizontal, ScrollbarAxis::Horizontal),
8108        ]
8109        .into_iter()
8110        .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
8111    }
8112
8113    /// Returns the currently hovered scrollbar axis, if any.
8114    pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
8115        self.iter_scrollbars()
8116            .find(|s| s.0.hitbox.is_hovered(window))
8117    }
8118}
8119
8120#[derive(Clone)]
8121struct ScrollbarLayout {
8122    hitbox: Hitbox,
8123    visible_range: Range<f32>,
8124    text_unit_size: Pixels,
8125    content_offset: Pixels,
8126    thumb_size: Pixels,
8127    axis: ScrollbarAxis,
8128}
8129
8130impl ScrollbarLayout {
8131    const BORDER_WIDTH: Pixels = px(1.0);
8132    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
8133    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
8134    const MIN_THUMB_SIZE: Pixels = px(25.0);
8135
8136    fn new(
8137        scrollbar_track_hitbox: Hitbox,
8138        editor_content_size: Pixels,
8139        scroll_range: Pixels,
8140        glyph_space: Pixels,
8141        content_offset: Pixels,
8142        scroll_position: f32,
8143        axis: ScrollbarAxis,
8144    ) -> Self {
8145        let track_bounds = scrollbar_track_hitbox.bounds;
8146        // The length of the track available to the scrollbar thumb. We deliberately
8147        // exclude the content size here so that the thumb aligns with the content.
8148        let track_length = track_bounds.size.along(axis) - content_offset;
8149
8150        let text_units_per_page = editor_content_size / glyph_space;
8151        let visible_range = scroll_position..scroll_position + text_units_per_page;
8152        let total_text_units = scroll_range / glyph_space;
8153
8154        let thumb_percentage = text_units_per_page / total_text_units;
8155        let thumb_size = (track_length * thumb_percentage)
8156            .max(ScrollbarLayout::MIN_THUMB_SIZE)
8157            .min(track_length);
8158        let text_unit_size =
8159            (track_length - thumb_size) / (total_text_units - text_units_per_page).max(0.);
8160
8161        ScrollbarLayout {
8162            hitbox: scrollbar_track_hitbox,
8163            visible_range,
8164            text_unit_size,
8165            content_offset,
8166            thumb_size,
8167            axis,
8168        }
8169    }
8170
8171    fn thumb_bounds(&self) -> Bounds<Pixels> {
8172        let scrollbar_track = &self.hitbox.bounds;
8173        Bounds::new(
8174            scrollbar_track
8175                .origin
8176                .apply_along(self.axis, |origin| self.thumb_origin(origin)),
8177            scrollbar_track
8178                .size
8179                .apply_along(self.axis, |_| self.thumb_size),
8180        )
8181    }
8182
8183    fn thumb_origin(&self, origin: Pixels) -> Pixels {
8184        origin + self.content_offset + self.visible_range.start * self.text_unit_size
8185    }
8186
8187    fn marker_quads_for_ranges(
8188        &self,
8189        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
8190        column: Option<usize>,
8191    ) -> Vec<PaintQuad> {
8192        struct MinMax {
8193            min: Pixels,
8194            max: Pixels,
8195        }
8196        let (x_range, height_limit) = if let Some(column) = column {
8197            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
8198            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
8199            let end = start + column_width;
8200            (
8201                Range { start, end },
8202                MinMax {
8203                    min: Self::MIN_MARKER_HEIGHT,
8204                    max: px(f32::MAX),
8205                },
8206            )
8207        } else {
8208            (
8209                Range {
8210                    start: Self::BORDER_WIDTH,
8211                    end: self.hitbox.size.width,
8212                },
8213                MinMax {
8214                    min: Self::LINE_MARKER_HEIGHT,
8215                    max: Self::LINE_MARKER_HEIGHT,
8216                },
8217            )
8218        };
8219
8220        let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
8221        let mut pixel_ranges = row_ranges
8222            .into_iter()
8223            .map(|range| {
8224                let start_y = row_to_y(range.start);
8225                let end_y = row_to_y(range.end)
8226                    + self
8227                        .text_unit_size
8228                        .max(height_limit.min)
8229                        .min(height_limit.max);
8230                ColoredRange {
8231                    start: start_y,
8232                    end: end_y,
8233                    color: range.color,
8234                }
8235            })
8236            .peekable();
8237
8238        let mut quads = Vec::new();
8239        while let Some(mut pixel_range) = pixel_ranges.next() {
8240            while let Some(next_pixel_range) = pixel_ranges.peek() {
8241                if pixel_range.end >= next_pixel_range.start - px(1.0)
8242                    && pixel_range.color == next_pixel_range.color
8243                {
8244                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
8245                    pixel_ranges.next();
8246                } else {
8247                    break;
8248                }
8249            }
8250
8251            let bounds = Bounds::from_corners(
8252                point(x_range.start, pixel_range.start),
8253                point(x_range.end, pixel_range.end),
8254            );
8255            quads.push(quad(
8256                bounds,
8257                Corners::default(),
8258                pixel_range.color,
8259                Edges::default(),
8260                Hsla::transparent_black(),
8261                BorderStyle::default(),
8262            ));
8263        }
8264
8265        quads
8266    }
8267}
8268
8269struct CreaseTrailerLayout {
8270    element: AnyElement,
8271    bounds: Bounds<Pixels>,
8272}
8273
8274pub(crate) struct PositionMap {
8275    pub size: Size<Pixels>,
8276    pub line_height: Pixels,
8277    pub scroll_pixel_position: gpui::Point<Pixels>,
8278    pub scroll_max: gpui::Point<f32>,
8279    pub em_width: Pixels,
8280    pub em_advance: Pixels,
8281    pub visible_row_range: Range<DisplayRow>,
8282    pub line_layouts: Vec<LineWithInvisibles>,
8283    pub snapshot: EditorSnapshot,
8284    pub text_hitbox: Hitbox,
8285    pub gutter_hitbox: Hitbox,
8286}
8287
8288#[derive(Debug, Copy, Clone)]
8289pub struct PointForPosition {
8290    pub previous_valid: DisplayPoint,
8291    pub next_valid: DisplayPoint,
8292    pub exact_unclipped: DisplayPoint,
8293    pub column_overshoot_after_line_end: u32,
8294}
8295
8296impl PointForPosition {
8297    pub fn as_valid(&self) -> Option<DisplayPoint> {
8298        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
8299            Some(self.previous_valid)
8300        } else {
8301            None
8302        }
8303    }
8304}
8305
8306impl PositionMap {
8307    pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
8308        let text_bounds = self.text_hitbox.bounds;
8309        let scroll_position = self.snapshot.scroll_position();
8310        let position = position - text_bounds.origin;
8311        let y = position.y.max(px(0.)).min(self.size.height);
8312        let x = position.x + (scroll_position.x * self.em_width);
8313        let row = ((y / self.line_height) + scroll_position.y) as u32;
8314
8315        let (column, x_overshoot_after_line_end) = if let Some(line) = self
8316            .line_layouts
8317            .get(row as usize - scroll_position.y as usize)
8318        {
8319            if let Some(ix) = line.index_for_x(x) {
8320                (ix as u32, px(0.))
8321            } else {
8322                (line.len as u32, px(0.).max(x - line.width))
8323            }
8324        } else {
8325            (0, x)
8326        };
8327
8328        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
8329        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
8330        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
8331
8332        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
8333        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
8334        PointForPosition {
8335            previous_valid,
8336            next_valid,
8337            exact_unclipped,
8338            column_overshoot_after_line_end,
8339        }
8340    }
8341}
8342
8343struct BlockLayout {
8344    id: BlockId,
8345    x_offset: Pixels,
8346    row: Option<DisplayRow>,
8347    element: AnyElement,
8348    available_space: Size<AvailableSpace>,
8349    style: BlockStyle,
8350    overlaps_gutter: bool,
8351    is_buffer_header: bool,
8352}
8353
8354pub fn layout_line(
8355    row: DisplayRow,
8356    snapshot: &EditorSnapshot,
8357    style: &EditorStyle,
8358    text_width: Pixels,
8359    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
8360    window: &mut Window,
8361    cx: &mut App,
8362) -> LineWithInvisibles {
8363    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
8364    LineWithInvisibles::from_chunks(
8365        chunks,
8366        &style,
8367        MAX_LINE_LEN,
8368        1,
8369        snapshot.mode,
8370        text_width,
8371        is_row_soft_wrapped,
8372        window,
8373        cx,
8374    )
8375    .pop()
8376    .unwrap()
8377}
8378
8379#[derive(Debug)]
8380pub struct IndentGuideLayout {
8381    origin: gpui::Point<Pixels>,
8382    length: Pixels,
8383    single_indent_width: Pixels,
8384    depth: u32,
8385    active: bool,
8386    settings: IndentGuideSettings,
8387}
8388
8389pub struct CursorLayout {
8390    origin: gpui::Point<Pixels>,
8391    block_width: Pixels,
8392    line_height: Pixels,
8393    color: Hsla,
8394    shape: CursorShape,
8395    block_text: Option<ShapedLine>,
8396    cursor_name: Option<AnyElement>,
8397}
8398
8399#[derive(Debug)]
8400pub struct CursorName {
8401    string: SharedString,
8402    color: Hsla,
8403    is_top_row: bool,
8404}
8405
8406impl CursorLayout {
8407    pub fn new(
8408        origin: gpui::Point<Pixels>,
8409        block_width: Pixels,
8410        line_height: Pixels,
8411        color: Hsla,
8412        shape: CursorShape,
8413        block_text: Option<ShapedLine>,
8414    ) -> CursorLayout {
8415        CursorLayout {
8416            origin,
8417            block_width,
8418            line_height,
8419            color,
8420            shape,
8421            block_text,
8422            cursor_name: None,
8423        }
8424    }
8425
8426    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8427        Bounds {
8428            origin: self.origin + origin,
8429            size: size(self.block_width, self.line_height),
8430        }
8431    }
8432
8433    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8434        match self.shape {
8435            CursorShape::Bar => Bounds {
8436                origin: self.origin + origin,
8437                size: size(px(2.0), self.line_height),
8438            },
8439            CursorShape::Block | CursorShape::Hollow => Bounds {
8440                origin: self.origin + origin,
8441                size: size(self.block_width, self.line_height),
8442            },
8443            CursorShape::Underline => Bounds {
8444                origin: self.origin
8445                    + origin
8446                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
8447                size: size(self.block_width, px(2.0)),
8448            },
8449        }
8450    }
8451
8452    pub fn layout(
8453        &mut self,
8454        origin: gpui::Point<Pixels>,
8455        cursor_name: Option<CursorName>,
8456        window: &mut Window,
8457        cx: &mut App,
8458    ) {
8459        if let Some(cursor_name) = cursor_name {
8460            let bounds = self.bounds(origin);
8461            let text_size = self.line_height / 1.5;
8462
8463            let name_origin = if cursor_name.is_top_row {
8464                point(bounds.right() - px(1.), bounds.top())
8465            } else {
8466                match self.shape {
8467                    CursorShape::Bar => point(
8468                        bounds.right() - px(2.),
8469                        bounds.top() - text_size / 2. - px(1.),
8470                    ),
8471                    _ => point(
8472                        bounds.right() - px(1.),
8473                        bounds.top() - text_size / 2. - px(1.),
8474                    ),
8475                }
8476            };
8477            let mut name_element = div()
8478                .bg(self.color)
8479                .text_size(text_size)
8480                .px_0p5()
8481                .line_height(text_size + px(2.))
8482                .text_color(cursor_name.color)
8483                .child(cursor_name.string.clone())
8484                .into_any_element();
8485
8486            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
8487
8488            self.cursor_name = Some(name_element);
8489        }
8490    }
8491
8492    pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
8493        let bounds = self.bounds(origin);
8494
8495        //Draw background or border quad
8496        let cursor = if matches!(self.shape, CursorShape::Hollow) {
8497            outline(bounds, self.color, BorderStyle::Solid)
8498        } else {
8499            fill(bounds, self.color)
8500        };
8501
8502        if let Some(name) = &mut self.cursor_name {
8503            name.paint(window, cx);
8504        }
8505
8506        window.paint_quad(cursor);
8507
8508        if let Some(block_text) = &self.block_text {
8509            block_text
8510                .paint(self.origin + origin, self.line_height, window, cx)
8511                .log_err();
8512        }
8513    }
8514
8515    pub fn shape(&self) -> CursorShape {
8516        self.shape
8517    }
8518}
8519
8520#[derive(Debug)]
8521pub struct HighlightedRange {
8522    pub start_y: Pixels,
8523    pub line_height: Pixels,
8524    pub lines: Vec<HighlightedRangeLine>,
8525    pub color: Hsla,
8526    pub corner_radius: Pixels,
8527}
8528
8529#[derive(Debug)]
8530pub struct HighlightedRangeLine {
8531    pub start_x: Pixels,
8532    pub end_x: Pixels,
8533}
8534
8535impl HighlightedRange {
8536    pub fn paint(&self, bounds: Bounds<Pixels>, window: &mut Window) {
8537        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
8538            self.paint_lines(self.start_y, &self.lines[0..1], bounds, window);
8539            self.paint_lines(
8540                self.start_y + self.line_height,
8541                &self.lines[1..],
8542                bounds,
8543                window,
8544            );
8545        } else {
8546            self.paint_lines(self.start_y, &self.lines, bounds, window);
8547        }
8548    }
8549
8550    fn paint_lines(
8551        &self,
8552        start_y: Pixels,
8553        lines: &[HighlightedRangeLine],
8554        _bounds: Bounds<Pixels>,
8555        window: &mut Window,
8556    ) {
8557        if lines.is_empty() {
8558            return;
8559        }
8560
8561        let first_line = lines.first().unwrap();
8562        let last_line = lines.last().unwrap();
8563
8564        let first_top_left = point(first_line.start_x, start_y);
8565        let first_top_right = point(first_line.end_x, start_y);
8566
8567        let curve_height = point(Pixels::ZERO, self.corner_radius);
8568        let curve_width = |start_x: Pixels, end_x: Pixels| {
8569            let max = (end_x - start_x) / 2.;
8570            let width = if max < self.corner_radius {
8571                max
8572            } else {
8573                self.corner_radius
8574            };
8575
8576            point(width, Pixels::ZERO)
8577        };
8578
8579        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
8580        let mut builder = gpui::PathBuilder::fill();
8581        builder.move_to(first_top_right - top_curve_width);
8582        builder.curve_to(first_top_right + curve_height, first_top_right);
8583
8584        let mut iter = lines.iter().enumerate().peekable();
8585        while let Some((ix, line)) = iter.next() {
8586            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
8587
8588            if let Some((_, next_line)) = iter.peek() {
8589                let next_top_right = point(next_line.end_x, bottom_right.y);
8590
8591                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
8592                    Ordering::Equal => {
8593                        builder.line_to(bottom_right);
8594                    }
8595                    Ordering::Less => {
8596                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
8597                        builder.line_to(bottom_right - curve_height);
8598                        if self.corner_radius > Pixels::ZERO {
8599                            builder.curve_to(bottom_right - curve_width, bottom_right);
8600                        }
8601                        builder.line_to(next_top_right + curve_width);
8602                        if self.corner_radius > Pixels::ZERO {
8603                            builder.curve_to(next_top_right + curve_height, next_top_right);
8604                        }
8605                    }
8606                    Ordering::Greater => {
8607                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
8608                        builder.line_to(bottom_right - curve_height);
8609                        if self.corner_radius > Pixels::ZERO {
8610                            builder.curve_to(bottom_right + curve_width, bottom_right);
8611                        }
8612                        builder.line_to(next_top_right - curve_width);
8613                        if self.corner_radius > Pixels::ZERO {
8614                            builder.curve_to(next_top_right + curve_height, next_top_right);
8615                        }
8616                    }
8617                }
8618            } else {
8619                let curve_width = curve_width(line.start_x, line.end_x);
8620                builder.line_to(bottom_right - curve_height);
8621                if self.corner_radius > Pixels::ZERO {
8622                    builder.curve_to(bottom_right - curve_width, bottom_right);
8623                }
8624
8625                let bottom_left = point(line.start_x, bottom_right.y);
8626                builder.line_to(bottom_left + curve_width);
8627                if self.corner_radius > Pixels::ZERO {
8628                    builder.curve_to(bottom_left - curve_height, bottom_left);
8629                }
8630            }
8631        }
8632
8633        if first_line.start_x > last_line.start_x {
8634            let curve_width = curve_width(last_line.start_x, first_line.start_x);
8635            let second_top_left = point(last_line.start_x, start_y + self.line_height);
8636            builder.line_to(second_top_left + curve_height);
8637            if self.corner_radius > Pixels::ZERO {
8638                builder.curve_to(second_top_left + curve_width, second_top_left);
8639            }
8640            let first_bottom_left = point(first_line.start_x, second_top_left.y);
8641            builder.line_to(first_bottom_left - curve_width);
8642            if self.corner_radius > Pixels::ZERO {
8643                builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
8644            }
8645        }
8646
8647        builder.line_to(first_top_left + curve_height);
8648        if self.corner_radius > Pixels::ZERO {
8649            builder.curve_to(first_top_left + top_curve_width, first_top_left);
8650        }
8651        builder.line_to(first_top_right - top_curve_width);
8652
8653        if let Ok(path) = builder.build() {
8654            window.paint_path(path, self.color);
8655        }
8656    }
8657}
8658
8659enum CursorPopoverType {
8660    CodeContextMenu,
8661    EditPrediction,
8662}
8663
8664pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8665    (delta.pow(1.2) / 100.0).min(px(3.0)).into()
8666}
8667
8668fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8669    (delta.pow(1.2) / 300.0).into()
8670}
8671
8672pub fn register_action<T: Action>(
8673    editor: &Entity<Editor>,
8674    window: &mut Window,
8675    listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
8676) {
8677    let editor = editor.clone();
8678    window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
8679        let action = action.downcast_ref().unwrap();
8680        if phase == DispatchPhase::Bubble {
8681            editor.update(cx, |editor, cx| {
8682                listener(editor, action, window, cx);
8683            })
8684        }
8685    })
8686}
8687
8688fn compute_auto_height_layout(
8689    editor: &mut Editor,
8690    max_lines: usize,
8691    max_line_number_width: Pixels,
8692    known_dimensions: Size<Option<Pixels>>,
8693    available_width: AvailableSpace,
8694    window: &mut Window,
8695    cx: &mut Context<Editor>,
8696) -> Option<Size<Pixels>> {
8697    let width = known_dimensions.width.or({
8698        if let AvailableSpace::Definite(available_width) = available_width {
8699            Some(available_width)
8700        } else {
8701            None
8702        }
8703    })?;
8704    if let Some(height) = known_dimensions.height {
8705        return Some(size(width, height));
8706    }
8707
8708    let style = editor.style.as_ref().unwrap();
8709    let font_id = window.text_system().resolve_font(&style.text.font());
8710    let font_size = style.text.font_size.to_pixels(window.rem_size());
8711    let line_height = style.text.line_height_in_pixels(window.rem_size());
8712    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8713
8714    let mut snapshot = editor.snapshot(window, cx);
8715    let gutter_dimensions = snapshot
8716        .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
8717        .unwrap_or_default();
8718
8719    editor.gutter_dimensions = gutter_dimensions;
8720    let text_width = width - gutter_dimensions.width;
8721    let overscroll = size(em_width, px(0.));
8722
8723    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
8724    if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None) {
8725        if editor.set_wrap_width(Some(editor_width), cx) {
8726            snapshot = editor.snapshot(window, cx);
8727        }
8728    }
8729
8730    let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
8731    let height = scroll_height
8732        .max(line_height)
8733        .min(line_height * max_lines as f32);
8734
8735    Some(size(width, height))
8736}
8737
8738#[cfg(test)]
8739mod tests {
8740    use super::*;
8741    use crate::{
8742        Editor, MultiBuffer,
8743        display_map::{BlockPlacement, BlockProperties},
8744        editor_tests::{init_test, update_test_language_settings},
8745    };
8746    use gpui::{TestAppContext, VisualTestContext};
8747    use language::language_settings;
8748    use log::info;
8749    use std::num::NonZeroU32;
8750    use util::test::sample_text;
8751
8752    #[gpui::test]
8753    fn test_shape_line_numbers(cx: &mut TestAppContext) {
8754        init_test(cx, |_| {});
8755        let window = cx.add_window(|window, cx| {
8756            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
8757            Editor::new(EditorMode::full(), buffer, None, window, cx)
8758        });
8759
8760        let editor = window.root(cx).unwrap();
8761        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
8762        let line_height = window
8763            .update(cx, |_, window, _| {
8764                style.text.line_height_in_pixels(window.rem_size())
8765            })
8766            .unwrap();
8767        let element = EditorElement::new(&editor, style);
8768        let snapshot = window
8769            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
8770            .unwrap();
8771
8772        let layouts = cx
8773            .update_window(*window, |_, window, cx| {
8774                element.layout_line_numbers(
8775                    None,
8776                    GutterDimensions {
8777                        left_padding: Pixels::ZERO,
8778                        right_padding: Pixels::ZERO,
8779                        width: px(30.0),
8780                        margin: Pixels::ZERO,
8781                        git_blame_entries_width: None,
8782                    },
8783                    line_height,
8784                    gpui::Point::default(),
8785                    DisplayRow(0)..DisplayRow(6),
8786                    &(0..6)
8787                        .map(|row| RowInfo {
8788                            buffer_row: Some(row),
8789                            ..Default::default()
8790                        })
8791                        .collect::<Vec<_>>(),
8792                    &BTreeMap::default(),
8793                    Some(DisplayPoint::new(DisplayRow(0), 0)),
8794                    &snapshot,
8795                    window,
8796                    cx,
8797                )
8798            })
8799            .unwrap();
8800        assert_eq!(layouts.len(), 6);
8801
8802        let relative_rows = window
8803            .update(cx, |editor, window, cx| {
8804                let snapshot = editor.snapshot(window, cx);
8805                element.calculate_relative_line_numbers(
8806                    &snapshot,
8807                    &(DisplayRow(0)..DisplayRow(6)),
8808                    Some(DisplayRow(3)),
8809                )
8810            })
8811            .unwrap();
8812        assert_eq!(relative_rows[&DisplayRow(0)], 3);
8813        assert_eq!(relative_rows[&DisplayRow(1)], 2);
8814        assert_eq!(relative_rows[&DisplayRow(2)], 1);
8815        // current line has no relative number
8816        assert_eq!(relative_rows[&DisplayRow(4)], 1);
8817        assert_eq!(relative_rows[&DisplayRow(5)], 2);
8818
8819        // works if cursor is before screen
8820        let relative_rows = window
8821            .update(cx, |editor, window, cx| {
8822                let snapshot = editor.snapshot(window, cx);
8823                element.calculate_relative_line_numbers(
8824                    &snapshot,
8825                    &(DisplayRow(3)..DisplayRow(6)),
8826                    Some(DisplayRow(1)),
8827                )
8828            })
8829            .unwrap();
8830        assert_eq!(relative_rows.len(), 3);
8831        assert_eq!(relative_rows[&DisplayRow(3)], 2);
8832        assert_eq!(relative_rows[&DisplayRow(4)], 3);
8833        assert_eq!(relative_rows[&DisplayRow(5)], 4);
8834
8835        // works if cursor is after screen
8836        let relative_rows = window
8837            .update(cx, |editor, window, cx| {
8838                let snapshot = editor.snapshot(window, cx);
8839                element.calculate_relative_line_numbers(
8840                    &snapshot,
8841                    &(DisplayRow(0)..DisplayRow(3)),
8842                    Some(DisplayRow(6)),
8843                )
8844            })
8845            .unwrap();
8846        assert_eq!(relative_rows.len(), 3);
8847        assert_eq!(relative_rows[&DisplayRow(0)], 5);
8848        assert_eq!(relative_rows[&DisplayRow(1)], 4);
8849        assert_eq!(relative_rows[&DisplayRow(2)], 3);
8850    }
8851
8852    #[gpui::test]
8853    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
8854        init_test(cx, |_| {});
8855
8856        let window = cx.add_window(|window, cx| {
8857            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
8858            Editor::new(EditorMode::full(), buffer, None, window, cx)
8859        });
8860        let cx = &mut VisualTestContext::from_window(*window, cx);
8861        let editor = window.root(cx).unwrap();
8862        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8863
8864        window
8865            .update(cx, |editor, window, cx| {
8866                editor.cursor_shape = CursorShape::Block;
8867                editor.change_selections(None, window, cx, |s| {
8868                    s.select_ranges([
8869                        Point::new(0, 0)..Point::new(1, 0),
8870                        Point::new(3, 2)..Point::new(3, 3),
8871                        Point::new(5, 6)..Point::new(6, 0),
8872                    ]);
8873                });
8874            })
8875            .unwrap();
8876
8877        let (_, state) = cx.draw(
8878            point(px(500.), px(500.)),
8879            size(px(500.), px(500.)),
8880            |_, _| EditorElement::new(&editor, style),
8881        );
8882
8883        assert_eq!(state.selections.len(), 1);
8884        let local_selections = &state.selections[0].1;
8885        assert_eq!(local_selections.len(), 3);
8886        // moves cursor back one line
8887        assert_eq!(
8888            local_selections[0].head,
8889            DisplayPoint::new(DisplayRow(0), 6)
8890        );
8891        assert_eq!(
8892            local_selections[0].range,
8893            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
8894        );
8895
8896        // moves cursor back one column
8897        assert_eq!(
8898            local_selections[1].range,
8899            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
8900        );
8901        assert_eq!(
8902            local_selections[1].head,
8903            DisplayPoint::new(DisplayRow(3), 2)
8904        );
8905
8906        // leaves cursor on the max point
8907        assert_eq!(
8908            local_selections[2].range,
8909            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
8910        );
8911        assert_eq!(
8912            local_selections[2].head,
8913            DisplayPoint::new(DisplayRow(6), 0)
8914        );
8915
8916        // active lines does not include 1 (even though the range of the selection does)
8917        assert_eq!(
8918            state.active_rows.keys().cloned().collect::<Vec<_>>(),
8919            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
8920        );
8921    }
8922
8923    #[gpui::test]
8924    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
8925        init_test(cx, |_| {});
8926
8927        let window = cx.add_window(|window, cx| {
8928            let buffer = MultiBuffer::build_simple("", cx);
8929            Editor::new(EditorMode::full(), buffer, None, window, cx)
8930        });
8931        let cx = &mut VisualTestContext::from_window(*window, cx);
8932        let editor = window.root(cx).unwrap();
8933        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8934        window
8935            .update(cx, |editor, window, cx| {
8936                editor.set_placeholder_text("hello", cx);
8937                editor.insert_blocks(
8938                    [BlockProperties {
8939                        style: BlockStyle::Fixed,
8940                        placement: BlockPlacement::Above(Anchor::min()),
8941                        height: Some(3),
8942                        render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
8943                        priority: 0,
8944                    }],
8945                    None,
8946                    cx,
8947                );
8948
8949                // Blur the editor so that it displays placeholder text.
8950                window.blur();
8951            })
8952            .unwrap();
8953
8954        let (_, state) = cx.draw(
8955            point(px(500.), px(500.)),
8956            size(px(500.), px(500.)),
8957            |_, _| EditorElement::new(&editor, style),
8958        );
8959        assert_eq!(state.position_map.line_layouts.len(), 4);
8960        assert_eq!(state.line_numbers.len(), 1);
8961        assert_eq!(
8962            state
8963                .line_numbers
8964                .get(&MultiBufferRow(0))
8965                .map(|line_number| line_number.shaped_line.text.as_ref()),
8966            Some("1")
8967        );
8968    }
8969
8970    #[gpui::test]
8971    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
8972        const TAB_SIZE: u32 = 4;
8973
8974        let input_text = "\t \t|\t| a b";
8975        let expected_invisibles = vec![
8976            Invisible::Tab {
8977                line_start_offset: 0,
8978                line_end_offset: TAB_SIZE as usize,
8979            },
8980            Invisible::Whitespace {
8981                line_offset: TAB_SIZE as usize,
8982            },
8983            Invisible::Tab {
8984                line_start_offset: TAB_SIZE as usize + 1,
8985                line_end_offset: TAB_SIZE as usize * 2,
8986            },
8987            Invisible::Tab {
8988                line_start_offset: TAB_SIZE as usize * 2 + 1,
8989                line_end_offset: TAB_SIZE as usize * 3,
8990            },
8991            Invisible::Whitespace {
8992                line_offset: TAB_SIZE as usize * 3 + 1,
8993            },
8994            Invisible::Whitespace {
8995                line_offset: TAB_SIZE as usize * 3 + 3,
8996            },
8997        ];
8998        assert_eq!(
8999            expected_invisibles.len(),
9000            input_text
9001                .chars()
9002                .filter(|initial_char| initial_char.is_whitespace())
9003                .count(),
9004            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
9005        );
9006
9007        for show_line_numbers in [true, false] {
9008            init_test(cx, |s| {
9009                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
9010                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
9011            });
9012
9013            let actual_invisibles = collect_invisibles_from_new_editor(
9014                cx,
9015                EditorMode::full(),
9016                input_text,
9017                px(500.0),
9018                show_line_numbers,
9019            );
9020
9021            assert_eq!(expected_invisibles, actual_invisibles);
9022        }
9023    }
9024
9025    #[gpui::test]
9026    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
9027        init_test(cx, |s| {
9028            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
9029            s.defaults.tab_size = NonZeroU32::new(4);
9030        });
9031
9032        for editor_mode_without_invisibles in [
9033            EditorMode::SingleLine { auto_width: false },
9034            EditorMode::AutoHeight { max_lines: 100 },
9035        ] {
9036            for show_line_numbers in [true, false] {
9037                let invisibles = collect_invisibles_from_new_editor(
9038                    cx,
9039                    editor_mode_without_invisibles,
9040                    "\t\t\t| | a b",
9041                    px(500.0),
9042                    show_line_numbers,
9043                );
9044                assert!(
9045                    invisibles.is_empty(),
9046                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
9047                );
9048            }
9049        }
9050    }
9051
9052    #[gpui::test]
9053    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
9054        let tab_size = 4;
9055        let input_text = "a\tbcd     ".repeat(9);
9056        let repeated_invisibles = [
9057            Invisible::Tab {
9058                line_start_offset: 1,
9059                line_end_offset: tab_size as usize,
9060            },
9061            Invisible::Whitespace {
9062                line_offset: tab_size as usize + 3,
9063            },
9064            Invisible::Whitespace {
9065                line_offset: tab_size as usize + 4,
9066            },
9067            Invisible::Whitespace {
9068                line_offset: tab_size as usize + 5,
9069            },
9070            Invisible::Whitespace {
9071                line_offset: tab_size as usize + 6,
9072            },
9073            Invisible::Whitespace {
9074                line_offset: tab_size as usize + 7,
9075            },
9076        ];
9077        let expected_invisibles = std::iter::once(repeated_invisibles)
9078            .cycle()
9079            .take(9)
9080            .flatten()
9081            .collect::<Vec<_>>();
9082        assert_eq!(
9083            expected_invisibles.len(),
9084            input_text
9085                .chars()
9086                .filter(|initial_char| initial_char.is_whitespace())
9087                .count(),
9088            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
9089        );
9090        info!("Expected invisibles: {expected_invisibles:?}");
9091
9092        init_test(cx, |_| {});
9093
9094        // Put the same string with repeating whitespace pattern into editors of various size,
9095        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
9096        let resize_step = 10.0;
9097        let mut editor_width = 200.0;
9098        while editor_width <= 1000.0 {
9099            for show_line_numbers in [true, false] {
9100                update_test_language_settings(cx, |s| {
9101                    s.defaults.tab_size = NonZeroU32::new(tab_size);
9102                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
9103                    s.defaults.preferred_line_length = Some(editor_width as u32);
9104                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
9105                });
9106
9107                let actual_invisibles = collect_invisibles_from_new_editor(
9108                    cx,
9109                    EditorMode::full(),
9110                    &input_text,
9111                    px(editor_width),
9112                    show_line_numbers,
9113                );
9114
9115                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
9116                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
9117                let mut i = 0;
9118                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
9119                    i = actual_index;
9120                    match expected_invisibles.get(i) {
9121                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
9122                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
9123                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
9124                            _ => {
9125                                panic!(
9126                                    "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
9127                                )
9128                            }
9129                        },
9130                        None => {
9131                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
9132                        }
9133                    }
9134                }
9135                let missing_expected_invisibles = &expected_invisibles[i + 1..];
9136                assert!(
9137                    missing_expected_invisibles.is_empty(),
9138                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
9139                );
9140
9141                editor_width += resize_step;
9142            }
9143        }
9144    }
9145
9146    fn collect_invisibles_from_new_editor(
9147        cx: &mut TestAppContext,
9148        editor_mode: EditorMode,
9149        input_text: &str,
9150        editor_width: Pixels,
9151        show_line_numbers: bool,
9152    ) -> Vec<Invisible> {
9153        info!(
9154            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
9155            editor_width.0
9156        );
9157        let window = cx.add_window(|window, cx| {
9158            let buffer = MultiBuffer::build_simple(input_text, cx);
9159            Editor::new(editor_mode, buffer, None, window, cx)
9160        });
9161        let cx = &mut VisualTestContext::from_window(*window, cx);
9162        let editor = window.root(cx).unwrap();
9163
9164        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
9165        window
9166            .update(cx, |editor, _, cx| {
9167                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
9168                editor.set_wrap_width(Some(editor_width), cx);
9169                editor.set_show_line_numbers(show_line_numbers, cx);
9170            })
9171            .unwrap();
9172        let (_, state) = cx.draw(
9173            point(px(500.), px(500.)),
9174            size(px(500.), px(500.)),
9175            |_, _| EditorElement::new(&editor, style),
9176        );
9177        state
9178            .position_map
9179            .line_layouts
9180            .iter()
9181            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
9182            .cloned()
9183            .collect()
9184    }
9185}