element.rs

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