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