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