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