element.rs

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