element.rs

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