element.rs

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