element.rs

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