element.rs

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