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