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