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