element.rs

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