element.rs

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