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