element.rs

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