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