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