element.rs

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