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