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