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