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