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