element.rs

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