element.rs

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