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