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