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