element.rs

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