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