element.rs

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