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 include_line_numbers = snapshot.show_line_numbers.unwrap_or_else(|| {
1627            EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full
1628        });
1629        if !include_line_numbers {
1630            return Vec::new();
1631        }
1632
1633        let editor = self.editor.read(cx);
1634        let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
1635            let newest = editor.selections.newest::<Point>(cx);
1636            SelectionLayout::new(
1637                newest,
1638                editor.selections.line_mode,
1639                editor.cursor_shape,
1640                &snapshot.display_snapshot,
1641                true,
1642                true,
1643                None,
1644            )
1645            .head
1646        });
1647        let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1648
1649        let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1650        let relative_to = if is_relative {
1651            Some(newest_selection_head.row())
1652        } else {
1653            None
1654        };
1655        let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
1656        let mut line_number = String::new();
1657        buffer_rows
1658            .into_iter()
1659            .enumerate()
1660            .map(|(ix, multibuffer_row)| {
1661                let multibuffer_row = multibuffer_row?;
1662                let display_row = DisplayRow(rows.start.0 + ix as u32);
1663                let color = if active_rows.contains_key(&display_row) {
1664                    cx.theme().colors().editor_active_line_number
1665                } else {
1666                    cx.theme().colors().editor_line_number
1667                };
1668                line_number.clear();
1669                let default_number = multibuffer_row.0 + 1;
1670                let number = relative_rows
1671                    .get(&DisplayRow(ix as u32 + rows.start.0))
1672                    .unwrap_or(&default_number);
1673                write!(&mut line_number, "{number}").unwrap();
1674                let run = TextRun {
1675                    len: line_number.len(),
1676                    font: self.style.text.font(),
1677                    color,
1678                    background_color: None,
1679                    underline: None,
1680                    strikethrough: None,
1681                };
1682                let shaped_line = cx
1683                    .text_system()
1684                    .shape_line(line_number.clone().into(), font_size, &[run])
1685                    .unwrap();
1686                Some(shaped_line)
1687            })
1688            .collect()
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 = layout
2517            .position_map
2518            .snapshot
2519            .show_git_diff_gutter
2520            .unwrap_or_else(|| {
2521                matches!(
2522                    ProjectSettings::get_global(cx).git.git_gutter,
2523                    Some(GitGutterSetting::TrackedFiles)
2524                )
2525            });
2526        if show_git_gutter {
2527            Self::paint_diff_hunks(layout.gutter_hitbox.bounds, layout, cx)
2528        }
2529
2530        if layout.blamed_display_rows.is_some() {
2531            self.paint_blamed_display_rows(layout, cx);
2532        }
2533
2534        for (ix, line) in layout.line_numbers.iter().enumerate() {
2535            if let Some(line) = line {
2536                let line_origin = layout.gutter_hitbox.origin
2537                    + point(
2538                        layout.gutter_hitbox.size.width
2539                            - line.width
2540                            - layout.gutter_dimensions.right_padding,
2541                        ix as f32 * line_height - (scroll_top % line_height),
2542                    );
2543
2544                line.paint(line_origin, line_height, cx).log_err();
2545            }
2546        }
2547
2548        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2549            cx.with_element_namespace("gutter_fold_toggles", |cx| {
2550                for fold_indicator in layout.gutter_fold_toggles.iter_mut().flatten() {
2551                    fold_indicator.paint(cx);
2552                }
2553            });
2554
2555            for test_indicators in layout.test_indicators.iter_mut() {
2556                test_indicators.paint(cx);
2557            }
2558
2559            if let Some(indicator) = layout.code_actions_indicator.as_mut() {
2560                indicator.paint(cx);
2561            }
2562        });
2563    }
2564
2565    fn paint_diff_hunks(
2566        gutter_bounds: Bounds<Pixels>,
2567        layout: &EditorLayout,
2568        cx: &mut WindowContext,
2569    ) {
2570        if layout.display_hunks.is_empty() {
2571            return;
2572        }
2573
2574        let line_height = layout.position_map.line_height;
2575        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2576            for (hunk, hitbox) in &layout.display_hunks {
2577                let hunk_to_paint = match hunk {
2578                    DisplayDiffHunk::Folded { .. } => {
2579                        let hunk_bounds = Self::diff_hunk_bounds(
2580                            &layout.position_map.snapshot,
2581                            line_height,
2582                            gutter_bounds,
2583                            &hunk,
2584                        );
2585                        Some((
2586                            hunk_bounds,
2587                            cx.theme().status().modified,
2588                            Corners::all(1. * line_height),
2589                        ))
2590                    }
2591                    DisplayDiffHunk::Unfolded { status, .. } => {
2592                        hitbox.as_ref().map(|hunk_hitbox| match status {
2593                            DiffHunkStatus::Added => (
2594                                hunk_hitbox.bounds,
2595                                cx.theme().status().created,
2596                                Corners::all(0.05 * line_height),
2597                            ),
2598                            DiffHunkStatus::Modified => (
2599                                hunk_hitbox.bounds,
2600                                cx.theme().status().modified,
2601                                Corners::all(0.05 * line_height),
2602                            ),
2603                            DiffHunkStatus::Removed => (
2604                                hunk_hitbox.bounds,
2605                                cx.theme().status().deleted,
2606                                Corners::all(1. * line_height),
2607                            ),
2608                        })
2609                    }
2610                };
2611
2612                if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
2613                    cx.paint_quad(quad(
2614                        hunk_bounds,
2615                        corner_radii,
2616                        background_color,
2617                        Edges::default(),
2618                        transparent_black(),
2619                    ));
2620                }
2621            }
2622        });
2623    }
2624
2625    fn diff_hunk_bounds(
2626        snapshot: &EditorSnapshot,
2627        line_height: Pixels,
2628        bounds: Bounds<Pixels>,
2629        hunk: &DisplayDiffHunk,
2630    ) -> Bounds<Pixels> {
2631        let scroll_position = snapshot.scroll_position();
2632        let scroll_top = scroll_position.y * line_height;
2633
2634        match hunk {
2635            DisplayDiffHunk::Folded { display_row, .. } => {
2636                let start_y = display_row.as_f32() * line_height - scroll_top;
2637                let end_y = start_y + line_height;
2638
2639                let width = 0.275 * line_height;
2640                let highlight_origin = bounds.origin + point(-width, start_y);
2641                let highlight_size = size(width * 2., end_y - start_y);
2642                Bounds::new(highlight_origin, highlight_size)
2643            }
2644            DisplayDiffHunk::Unfolded {
2645                display_row_range,
2646                status,
2647                ..
2648            } => match status {
2649                DiffHunkStatus::Added | DiffHunkStatus::Modified => {
2650                    let start_row = display_row_range.start;
2651                    let end_row = display_row_range.end;
2652                    // If we're in a multibuffer, row range span might include an
2653                    // excerpt header, so if we were to draw the marker straight away,
2654                    // the hunk might include the rows of that header.
2655                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
2656                    // Instead, we simply check whether the range we're dealing with includes
2657                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
2658                    let end_row_in_current_excerpt = snapshot
2659                        .blocks_in_range(start_row..end_row)
2660                        .find_map(|(start_row, block)| {
2661                            if matches!(block, TransformBlock::ExcerptHeader { .. }) {
2662                                Some(start_row)
2663                            } else {
2664                                None
2665                            }
2666                        })
2667                        .unwrap_or(end_row);
2668
2669                    let start_y = start_row.as_f32() * line_height - scroll_top;
2670                    let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
2671
2672                    let width = 0.275 * line_height;
2673                    let highlight_origin = bounds.origin + point(-width, start_y);
2674                    let highlight_size = size(width * 2., end_y - start_y);
2675                    Bounds::new(highlight_origin, highlight_size)
2676                }
2677                DiffHunkStatus::Removed => {
2678                    let row = display_row_range.start;
2679
2680                    let offset = line_height / 2.;
2681                    let start_y = row.as_f32() * line_height - offset - scroll_top;
2682                    let end_y = start_y + line_height;
2683
2684                    let width = 0.35 * line_height;
2685                    let highlight_origin = bounds.origin + point(-width, start_y);
2686                    let highlight_size = size(width * 2., end_y - start_y);
2687                    Bounds::new(highlight_origin, highlight_size)
2688                }
2689            },
2690        }
2691    }
2692
2693    fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2694        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
2695            return;
2696        };
2697
2698        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2699            for mut blame_element in blamed_display_rows.into_iter() {
2700                blame_element.paint(cx);
2701            }
2702        })
2703    }
2704
2705    fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2706        cx.with_content_mask(
2707            Some(ContentMask {
2708                bounds: layout.text_hitbox.bounds,
2709            }),
2710            |cx| {
2711                let cursor_style = if self
2712                    .editor
2713                    .read(cx)
2714                    .hovered_link_state
2715                    .as_ref()
2716                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
2717                {
2718                    CursorStyle::PointingHand
2719                } else {
2720                    CursorStyle::IBeam
2721                };
2722                cx.set_cursor_style(cursor_style, &layout.text_hitbox);
2723
2724                cx.with_element_namespace("folds", |cx| self.paint_folds(layout, cx));
2725                let invisible_display_ranges = self.paint_highlights(layout, cx);
2726                self.paint_lines(&invisible_display_ranges, layout, cx);
2727                self.paint_redactions(layout, cx);
2728                self.paint_cursors(layout, cx);
2729                self.paint_inline_blame(layout, cx);
2730                cx.with_element_namespace("flap_trailers", |cx| {
2731                    for trailer in layout.flap_trailers.iter_mut().flatten() {
2732                        trailer.element.paint(cx);
2733                    }
2734                });
2735            },
2736        )
2737    }
2738
2739    fn paint_highlights(
2740        &mut self,
2741        layout: &mut EditorLayout,
2742        cx: &mut WindowContext,
2743    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
2744        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2745            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
2746            let line_end_overshoot = 0.15 * layout.position_map.line_height;
2747            for (range, color) in &layout.highlighted_ranges {
2748                self.paint_highlighted_range(
2749                    range.clone(),
2750                    *color,
2751                    Pixels::ZERO,
2752                    line_end_overshoot,
2753                    layout,
2754                    cx,
2755                );
2756            }
2757
2758            let corner_radius = 0.15 * layout.position_map.line_height;
2759
2760            for (player_color, selections) in &layout.selections {
2761                for selection in selections.into_iter() {
2762                    self.paint_highlighted_range(
2763                        selection.range.clone(),
2764                        player_color.selection,
2765                        corner_radius,
2766                        corner_radius * 2.,
2767                        layout,
2768                        cx,
2769                    );
2770
2771                    if selection.is_local && !selection.range.is_empty() {
2772                        invisible_display_ranges.push(selection.range.clone());
2773                    }
2774                }
2775            }
2776            invisible_display_ranges
2777        })
2778    }
2779
2780    fn paint_lines(
2781        &mut self,
2782        invisible_display_ranges: &[Range<DisplayPoint>],
2783        layout: &EditorLayout,
2784        cx: &mut WindowContext,
2785    ) {
2786        let whitespace_setting = self
2787            .editor
2788            .read(cx)
2789            .buffer
2790            .read(cx)
2791            .settings_at(0, cx)
2792            .show_whitespaces;
2793
2794        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
2795            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
2796            line_with_invisibles.draw(
2797                layout,
2798                row,
2799                layout.content_origin,
2800                whitespace_setting,
2801                invisible_display_ranges,
2802                cx,
2803            )
2804        }
2805    }
2806
2807    fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
2808        if layout.redacted_ranges.is_empty() {
2809            return;
2810        }
2811
2812        let line_end_overshoot = layout.line_end_overshoot();
2813
2814        // A softer than perfect black
2815        let redaction_color = gpui::rgb(0x0e1111);
2816
2817        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2818            for range in layout.redacted_ranges.iter() {
2819                self.paint_highlighted_range(
2820                    range.clone(),
2821                    redaction_color.into(),
2822                    Pixels::ZERO,
2823                    line_end_overshoot,
2824                    layout,
2825                    cx,
2826                );
2827            }
2828        });
2829    }
2830
2831    fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2832        for cursor in &mut layout.visible_cursors {
2833            cursor.paint(layout.content_origin, cx);
2834        }
2835    }
2836
2837    fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2838        let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
2839            return;
2840        };
2841
2842        let thumb_bounds = scrollbar_layout.thumb_bounds();
2843        if scrollbar_layout.visible {
2844            cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
2845                cx.paint_quad(quad(
2846                    scrollbar_layout.hitbox.bounds,
2847                    Corners::default(),
2848                    cx.theme().colors().scrollbar_track_background,
2849                    Edges {
2850                        top: Pixels::ZERO,
2851                        right: Pixels::ZERO,
2852                        bottom: Pixels::ZERO,
2853                        left: ScrollbarLayout::BORDER_WIDTH,
2854                    },
2855                    cx.theme().colors().scrollbar_track_border,
2856                ));
2857
2858                let fast_markers =
2859                    self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
2860                // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
2861                self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
2862
2863                let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
2864                for marker in markers.iter().chain(&fast_markers) {
2865                    let mut marker = marker.clone();
2866                    marker.bounds.origin += scrollbar_layout.hitbox.origin;
2867                    cx.paint_quad(marker);
2868                }
2869
2870                cx.paint_quad(quad(
2871                    thumb_bounds,
2872                    Corners::default(),
2873                    cx.theme().colors().scrollbar_thumb_background,
2874                    Edges {
2875                        top: Pixels::ZERO,
2876                        right: Pixels::ZERO,
2877                        bottom: Pixels::ZERO,
2878                        left: ScrollbarLayout::BORDER_WIDTH,
2879                    },
2880                    cx.theme().colors().scrollbar_thumb_border,
2881                ));
2882            });
2883        }
2884
2885        cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
2886
2887        let row_height = scrollbar_layout.row_height;
2888        let row_range = scrollbar_layout.visible_row_range.clone();
2889
2890        cx.on_mouse_event({
2891            let editor = self.editor.clone();
2892            let hitbox = scrollbar_layout.hitbox.clone();
2893            let mut mouse_position = cx.mouse_position();
2894            move |event: &MouseMoveEvent, phase, cx| {
2895                if phase == DispatchPhase::Capture {
2896                    return;
2897                }
2898
2899                editor.update(cx, |editor, cx| {
2900                    if event.pressed_button == Some(MouseButton::Left)
2901                        && editor.scroll_manager.is_dragging_scrollbar()
2902                    {
2903                        let y = mouse_position.y;
2904                        let new_y = event.position.y;
2905                        if (hitbox.top()..hitbox.bottom()).contains(&y) {
2906                            let mut position = editor.scroll_position(cx);
2907                            position.y += (new_y - y) / row_height;
2908                            if position.y < 0.0 {
2909                                position.y = 0.0;
2910                            }
2911                            editor.set_scroll_position(position, cx);
2912                        }
2913
2914                        cx.stop_propagation();
2915                    } else {
2916                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2917                        if hitbox.is_hovered(cx) {
2918                            editor.scroll_manager.show_scrollbar(cx);
2919                        }
2920                    }
2921                    mouse_position = event.position;
2922                })
2923            }
2924        });
2925
2926        if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
2927            cx.on_mouse_event({
2928                let editor = self.editor.clone();
2929                move |_: &MouseUpEvent, phase, cx| {
2930                    if phase == DispatchPhase::Capture {
2931                        return;
2932                    }
2933
2934                    editor.update(cx, |editor, cx| {
2935                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2936                        cx.stop_propagation();
2937                    });
2938                }
2939            });
2940        } else {
2941            cx.on_mouse_event({
2942                let editor = self.editor.clone();
2943                let hitbox = scrollbar_layout.hitbox.clone();
2944                move |event: &MouseDownEvent, phase, cx| {
2945                    if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
2946                        return;
2947                    }
2948
2949                    editor.update(cx, |editor, cx| {
2950                        editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
2951
2952                        let y = event.position.y;
2953                        if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
2954                            let center_row = ((y - hitbox.top()) / row_height).round() as u32;
2955                            let top_row = center_row
2956                                .saturating_sub((row_range.end - row_range.start) as u32 / 2);
2957                            let mut position = editor.scroll_position(cx);
2958                            position.y = top_row as f32;
2959                            editor.set_scroll_position(position, cx);
2960                        } else {
2961                            editor.scroll_manager.show_scrollbar(cx);
2962                        }
2963
2964                        cx.stop_propagation();
2965                    });
2966                }
2967            });
2968        }
2969    }
2970
2971    fn collect_fast_scrollbar_markers(
2972        &self,
2973        layout: &EditorLayout,
2974        scrollbar_layout: &ScrollbarLayout,
2975        cx: &mut WindowContext,
2976    ) -> Vec<PaintQuad> {
2977        const LIMIT: usize = 100;
2978        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
2979            return vec![];
2980        }
2981        let cursor_ranges = layout
2982            .cursors
2983            .iter()
2984            .map(|(point, color)| ColoredRange {
2985                start: point.row(),
2986                end: point.row(),
2987                color: *color,
2988            })
2989            .collect_vec();
2990        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
2991    }
2992
2993    fn refresh_slow_scrollbar_markers(
2994        &self,
2995        layout: &EditorLayout,
2996        scrollbar_layout: &ScrollbarLayout,
2997        cx: &mut WindowContext,
2998    ) {
2999        self.editor.update(cx, |editor, cx| {
3000            if !editor.is_singleton(cx)
3001                || !editor
3002                    .scrollbar_marker_state
3003                    .should_refresh(scrollbar_layout.hitbox.size)
3004            {
3005                return;
3006            }
3007
3008            let scrollbar_layout = scrollbar_layout.clone();
3009            let background_highlights = editor.background_highlights.clone();
3010            let snapshot = layout.position_map.snapshot.clone();
3011            let theme = cx.theme().clone();
3012            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
3013
3014            editor.scrollbar_marker_state.dirty = false;
3015            editor.scrollbar_marker_state.pending_refresh =
3016                Some(cx.spawn(|editor, mut cx| async move {
3017                    let scrollbar_size = scrollbar_layout.hitbox.size;
3018                    let scrollbar_markers = cx
3019                        .background_executor()
3020                        .spawn(async move {
3021                            let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
3022                            let mut marker_quads = Vec::new();
3023                            if scrollbar_settings.git_diff {
3024                                let marker_row_ranges = snapshot
3025                                    .buffer_snapshot
3026                                    .git_diff_hunks_in_range(
3027                                        MultiBufferRow::MIN..MultiBufferRow::MAX,
3028                                    )
3029                                    .map(|hunk| {
3030                                        let start_display_row =
3031                                            MultiBufferPoint::new(hunk.associated_range.start.0, 0)
3032                                                .to_display_point(&snapshot.display_snapshot)
3033                                                .row();
3034                                        let mut end_display_row =
3035                                            MultiBufferPoint::new(hunk.associated_range.end.0, 0)
3036                                                .to_display_point(&snapshot.display_snapshot)
3037                                                .row();
3038                                        if end_display_row != start_display_row {
3039                                            end_display_row.0 -= 1;
3040                                        }
3041                                        let color = match hunk_status(&hunk) {
3042                                            DiffHunkStatus::Added => theme.status().created,
3043                                            DiffHunkStatus::Modified => theme.status().modified,
3044                                            DiffHunkStatus::Removed => theme.status().deleted,
3045                                        };
3046                                        ColoredRange {
3047                                            start: start_display_row,
3048                                            end: end_display_row,
3049                                            color,
3050                                        }
3051                                    });
3052
3053                                marker_quads.extend(
3054                                    scrollbar_layout
3055                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
3056                                );
3057                            }
3058
3059                            for (background_highlight_id, (_, background_ranges)) in
3060                                background_highlights.iter()
3061                            {
3062                                let is_search_highlights = *background_highlight_id
3063                                    == TypeId::of::<BufferSearchHighlights>();
3064                                let is_symbol_occurrences = *background_highlight_id
3065                                    == TypeId::of::<DocumentHighlightRead>()
3066                                    || *background_highlight_id
3067                                        == TypeId::of::<DocumentHighlightWrite>();
3068                                if (is_search_highlights && scrollbar_settings.search_results)
3069                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
3070                                {
3071                                    let mut color = theme.status().info;
3072                                    if is_symbol_occurrences {
3073                                        color.fade_out(0.5);
3074                                    }
3075                                    let marker_row_ranges =
3076                                        background_ranges.into_iter().map(|range| {
3077                                            let display_start = range
3078                                                .start
3079                                                .to_display_point(&snapshot.display_snapshot);
3080                                            let display_end = range
3081                                                .end
3082                                                .to_display_point(&snapshot.display_snapshot);
3083                                            ColoredRange {
3084                                                start: display_start.row(),
3085                                                end: display_end.row(),
3086                                                color,
3087                                            }
3088                                        });
3089                                    marker_quads.extend(
3090                                        scrollbar_layout
3091                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
3092                                    );
3093                                }
3094                            }
3095
3096                            if scrollbar_settings.diagnostics {
3097                                let diagnostics = snapshot
3098                                    .buffer_snapshot
3099                                    .diagnostics_in_range::<_, Point>(
3100                                        Point::zero()..max_point,
3101                                        false,
3102                                    )
3103                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
3104                                    .sorted_by_key(|diagnostic| {
3105                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
3106                                    });
3107
3108                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
3109                                    let start_display = diagnostic
3110                                        .range
3111                                        .start
3112                                        .to_display_point(&snapshot.display_snapshot);
3113                                    let end_display = diagnostic
3114                                        .range
3115                                        .end
3116                                        .to_display_point(&snapshot.display_snapshot);
3117                                    let color = match diagnostic.diagnostic.severity {
3118                                        DiagnosticSeverity::ERROR => theme.status().error,
3119                                        DiagnosticSeverity::WARNING => theme.status().warning,
3120                                        DiagnosticSeverity::INFORMATION => theme.status().info,
3121                                        _ => theme.status().hint,
3122                                    };
3123                                    ColoredRange {
3124                                        start: start_display.row(),
3125                                        end: end_display.row(),
3126                                        color,
3127                                    }
3128                                });
3129                                marker_quads.extend(
3130                                    scrollbar_layout
3131                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
3132                                );
3133                            }
3134
3135                            Arc::from(marker_quads)
3136                        })
3137                        .await;
3138
3139                    editor.update(&mut cx, |editor, cx| {
3140                        editor.scrollbar_marker_state.markers = scrollbar_markers;
3141                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
3142                        editor.scrollbar_marker_state.pending_refresh = None;
3143                        cx.notify();
3144                    })?;
3145
3146                    Ok(())
3147                }));
3148        });
3149    }
3150
3151    #[allow(clippy::too_many_arguments)]
3152    fn paint_highlighted_range(
3153        &self,
3154        range: Range<DisplayPoint>,
3155        color: Hsla,
3156        corner_radius: Pixels,
3157        line_end_overshoot: Pixels,
3158        layout: &EditorLayout,
3159        cx: &mut WindowContext,
3160    ) {
3161        let start_row = layout.visible_display_row_range.start;
3162        let end_row = layout.visible_display_row_range.end;
3163        if range.start != range.end {
3164            let row_range = if range.end.column() == 0 {
3165                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3166            } else {
3167                cmp::max(range.start.row(), start_row)
3168                    ..cmp::min(range.end.row().next_row(), end_row)
3169            };
3170
3171            let highlighted_range = HighlightedRange {
3172                color,
3173                line_height: layout.position_map.line_height,
3174                corner_radius,
3175                start_y: layout.content_origin.y
3176                    + row_range.start.as_f32() * layout.position_map.line_height
3177                    - layout.position_map.scroll_pixel_position.y,
3178                lines: row_range
3179                    .iter_rows()
3180                    .map(|row| {
3181                        let line_layout =
3182                            &layout.position_map.line_layouts[row.minus(start_row) as usize].line;
3183                        HighlightedRangeLine {
3184                            start_x: if row == range.start.row() {
3185                                layout.content_origin.x
3186                                    + line_layout.x_for_index(range.start.column() as usize)
3187                                    - layout.position_map.scroll_pixel_position.x
3188                            } else {
3189                                layout.content_origin.x
3190                                    - layout.position_map.scroll_pixel_position.x
3191                            },
3192                            end_x: if row == range.end.row() {
3193                                layout.content_origin.x
3194                                    + line_layout.x_for_index(range.end.column() as usize)
3195                                    - layout.position_map.scroll_pixel_position.x
3196                            } else {
3197                                layout.content_origin.x + line_layout.width + line_end_overshoot
3198                                    - layout.position_map.scroll_pixel_position.x
3199                            },
3200                        }
3201                    })
3202                    .collect(),
3203            };
3204
3205            highlighted_range.paint(layout.text_hitbox.bounds, cx);
3206        }
3207    }
3208
3209    fn paint_folds(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3210        if layout.folds.is_empty() {
3211            return;
3212        }
3213
3214        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3215            let fold_corner_radius = 0.15 * layout.position_map.line_height;
3216            for mut fold in mem::take(&mut layout.folds) {
3217                fold.hover_element.paint(cx);
3218
3219                let hover_element = fold.hover_element.downcast_mut::<Stateful<Div>>().unwrap();
3220                let fold_background = if hover_element.interactivity().active.unwrap() {
3221                    cx.theme().colors().ghost_element_active
3222                } else if hover_element.interactivity().hovered.unwrap() {
3223                    cx.theme().colors().ghost_element_hover
3224                } else {
3225                    cx.theme().colors().ghost_element_background
3226                };
3227
3228                self.paint_highlighted_range(
3229                    fold.display_range.clone(),
3230                    fold_background,
3231                    fold_corner_radius,
3232                    fold_corner_radius * 2.,
3233                    layout,
3234                    cx,
3235                );
3236            }
3237        })
3238    }
3239
3240    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3241        if let Some(mut inline_blame) = layout.inline_blame.take() {
3242            cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3243                inline_blame.paint(cx);
3244            })
3245        }
3246    }
3247
3248    fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3249        for mut block in layout.blocks.drain(..) {
3250            block.element.paint(cx);
3251        }
3252    }
3253
3254    fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3255        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
3256            mouse_context_menu.paint(cx);
3257        }
3258    }
3259
3260    fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3261        cx.on_mouse_event({
3262            let position_map = layout.position_map.clone();
3263            let editor = self.editor.clone();
3264            let hitbox = layout.hitbox.clone();
3265            let mut delta = ScrollDelta::default();
3266
3267            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
3268            // accidentally turn off their scrolling.
3269            let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
3270
3271            move |event: &ScrollWheelEvent, phase, cx| {
3272                if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
3273                    delta = delta.coalesce(event.delta);
3274                    editor.update(cx, |editor, cx| {
3275                        let position_map: &PositionMap = &position_map;
3276
3277                        let line_height = position_map.line_height;
3278                        let max_glyph_width = position_map.em_width;
3279                        let (delta, axis) = match delta {
3280                            gpui::ScrollDelta::Pixels(mut pixels) => {
3281                                //Trackpad
3282                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
3283                                (pixels, axis)
3284                            }
3285
3286                            gpui::ScrollDelta::Lines(lines) => {
3287                                //Not trackpad
3288                                let pixels =
3289                                    point(lines.x * max_glyph_width, lines.y * line_height);
3290                                (pixels, None)
3291                            }
3292                        };
3293
3294                        let current_scroll_position = position_map.snapshot.scroll_position();
3295                        let x = (current_scroll_position.x * max_glyph_width
3296                            - (delta.x * scroll_sensitivity))
3297                            / max_glyph_width;
3298                        let y = (current_scroll_position.y * line_height
3299                            - (delta.y * scroll_sensitivity))
3300                            / line_height;
3301                        let mut scroll_position =
3302                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
3303                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
3304                        if forbid_vertical_scroll {
3305                            scroll_position.y = current_scroll_position.y;
3306                            if scroll_position == current_scroll_position {
3307                                return;
3308                            }
3309                        }
3310                        editor.scroll(scroll_position, axis, cx);
3311                        cx.stop_propagation();
3312                    });
3313                }
3314            }
3315        });
3316    }
3317
3318    fn paint_mouse_listeners(
3319        &mut self,
3320        layout: &EditorLayout,
3321        hovered_hunk: Option<HunkToExpand>,
3322        cx: &mut WindowContext,
3323    ) {
3324        self.paint_scroll_wheel_listener(layout, cx);
3325
3326        cx.on_mouse_event({
3327            let position_map = layout.position_map.clone();
3328            let editor = self.editor.clone();
3329            let text_hitbox = layout.text_hitbox.clone();
3330            let gutter_hitbox = layout.gutter_hitbox.clone();
3331
3332            move |event: &MouseDownEvent, phase, cx| {
3333                if phase == DispatchPhase::Bubble {
3334                    match event.button {
3335                        MouseButton::Left => editor.update(cx, |editor, cx| {
3336                            Self::mouse_left_down(
3337                                editor,
3338                                event,
3339                                hovered_hunk.as_ref(),
3340                                &position_map,
3341                                &text_hitbox,
3342                                &gutter_hitbox,
3343                                cx,
3344                            );
3345                        }),
3346                        MouseButton::Right => editor.update(cx, |editor, cx| {
3347                            Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
3348                        }),
3349                        MouseButton::Middle => editor.update(cx, |editor, cx| {
3350                            Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
3351                        }),
3352                        _ => {}
3353                    };
3354                }
3355            }
3356        });
3357
3358        cx.on_mouse_event({
3359            let editor = self.editor.clone();
3360            let position_map = layout.position_map.clone();
3361            let text_hitbox = layout.text_hitbox.clone();
3362
3363            move |event: &MouseUpEvent, phase, cx| {
3364                if phase == DispatchPhase::Bubble {
3365                    editor.update(cx, |editor, cx| {
3366                        Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
3367                    });
3368                }
3369            }
3370        });
3371        cx.on_mouse_event({
3372            let position_map = layout.position_map.clone();
3373            let editor = self.editor.clone();
3374            let text_hitbox = layout.text_hitbox.clone();
3375            let gutter_hitbox = layout.gutter_hitbox.clone();
3376
3377            move |event: &MouseMoveEvent, phase, cx| {
3378                if phase == DispatchPhase::Bubble {
3379                    editor.update(cx, |editor, cx| {
3380                        if event.pressed_button == Some(MouseButton::Left)
3381                            || event.pressed_button == Some(MouseButton::Middle)
3382                        {
3383                            Self::mouse_dragged(
3384                                editor,
3385                                event,
3386                                &position_map,
3387                                text_hitbox.bounds,
3388                                cx,
3389                            )
3390                        }
3391
3392                        Self::mouse_moved(
3393                            editor,
3394                            event,
3395                            &position_map,
3396                            &text_hitbox,
3397                            &gutter_hitbox,
3398                            cx,
3399                        )
3400                    });
3401                }
3402            }
3403        });
3404    }
3405
3406    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
3407        bounds.upper_right().x - self.style.scrollbar_width
3408    }
3409
3410    fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
3411        let style = &self.style;
3412        let font_size = style.text.font_size.to_pixels(cx.rem_size());
3413        let layout = cx
3414            .text_system()
3415            .shape_line(
3416                SharedString::from(" ".repeat(column)),
3417                font_size,
3418                &[TextRun {
3419                    len: column,
3420                    font: style.text.font(),
3421                    color: Hsla::default(),
3422                    background_color: None,
3423                    underline: None,
3424                    strikethrough: None,
3425                }],
3426            )
3427            .unwrap();
3428
3429        layout.width
3430    }
3431
3432    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
3433        let digit_count = snapshot
3434            .max_buffer_row()
3435            .next_row()
3436            .as_f32()
3437            .log10()
3438            .floor() as usize
3439            + 1;
3440        self.column_pixels(digit_count, cx)
3441    }
3442}
3443
3444fn prepaint_gutter_button(
3445    button: IconButton,
3446    row: DisplayRow,
3447    line_height: Pixels,
3448    gutter_dimensions: &GutterDimensions,
3449    scroll_pixel_position: gpui::Point<Pixels>,
3450    gutter_hitbox: &Hitbox,
3451    cx: &mut WindowContext<'_>,
3452) -> AnyElement {
3453    let mut button = button.into_any_element();
3454    let available_space = size(
3455        AvailableSpace::MinContent,
3456        AvailableSpace::Definite(line_height),
3457    );
3458    let indicator_size = button.layout_as_root(available_space, cx);
3459
3460    let blame_width = gutter_dimensions
3461        .git_blame_entries_width
3462        .unwrap_or(Pixels::ZERO);
3463
3464    let mut x = blame_width;
3465    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
3466        - indicator_size.width
3467        - blame_width;
3468    x += available_width / 2.;
3469
3470    let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
3471    y += (line_height - indicator_size.height) / 2.;
3472
3473    button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
3474    button
3475}
3476
3477fn render_inline_blame_entry(
3478    blame: &gpui::Model<GitBlame>,
3479    blame_entry: BlameEntry,
3480    style: &EditorStyle,
3481    workspace: Option<WeakView<Workspace>>,
3482    cx: &mut WindowContext<'_>,
3483) -> AnyElement {
3484    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3485
3486    let author = blame_entry.author.as_deref().unwrap_or_default();
3487    let text = format!("{}, {}", author, relative_timestamp);
3488
3489    let details = blame.read(cx).details_for_entry(&blame_entry);
3490
3491    let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
3492
3493    h_flex()
3494        .id("inline-blame")
3495        .w_full()
3496        .font_family(style.text.font().family)
3497        .text_color(cx.theme().status().hint)
3498        .line_height(style.text.line_height)
3499        .child(Icon::new(IconName::FileGit).color(Color::Hint))
3500        .child(text)
3501        .gap_2()
3502        .hoverable_tooltip(move |_| tooltip.clone().into())
3503        .into_any()
3504}
3505
3506fn render_blame_entry(
3507    ix: usize,
3508    blame: &gpui::Model<GitBlame>,
3509    blame_entry: BlameEntry,
3510    style: &EditorStyle,
3511    last_used_color: &mut Option<(PlayerColor, Oid)>,
3512    editor: View<Editor>,
3513    cx: &mut WindowContext<'_>,
3514) -> AnyElement {
3515    let mut sha_color = cx
3516        .theme()
3517        .players()
3518        .color_for_participant(blame_entry.sha.into());
3519    // If the last color we used is the same as the one we get for this line, but
3520    // the commit SHAs are different, then we try again to get a different color.
3521    match *last_used_color {
3522        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3523            let index: u32 = blame_entry.sha.into();
3524            sha_color = cx.theme().players().color_for_participant(index + 1);
3525        }
3526        _ => {}
3527    };
3528    last_used_color.replace((sha_color, blame_entry.sha));
3529
3530    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3531
3532    let short_commit_id = blame_entry.sha.display_short();
3533
3534    let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3535    let name = util::truncate_and_trailoff(author_name, 20);
3536
3537    let details = blame.read(cx).details_for_entry(&blame_entry);
3538
3539    let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3540
3541    let tooltip = cx.new_view(|_| {
3542        BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3543    });
3544
3545    h_flex()
3546        .w_full()
3547        .font_family(style.text.font().family)
3548        .line_height(style.text.line_height)
3549        .id(("blame", ix))
3550        .children([
3551            div()
3552                .text_color(sha_color.cursor)
3553                .child(short_commit_id)
3554                .mr_2(),
3555            div()
3556                .w_full()
3557                .h_flex()
3558                .justify_between()
3559                .text_color(cx.theme().status().hint)
3560                .child(name)
3561                .child(relative_timestamp),
3562        ])
3563        .on_mouse_down(MouseButton::Right, {
3564            let blame_entry = blame_entry.clone();
3565            let details = details.clone();
3566            move |event, cx| {
3567                deploy_blame_entry_context_menu(
3568                    &blame_entry,
3569                    details.as_ref(),
3570                    editor.clone(),
3571                    event.position,
3572                    cx,
3573                );
3574            }
3575        })
3576        .hover(|style| style.bg(cx.theme().colors().element_hover))
3577        .when_some(
3578            details.and_then(|details| details.permalink),
3579            |this, url| {
3580                let url = url.clone();
3581                this.cursor_pointer().on_click(move |_, cx| {
3582                    cx.stop_propagation();
3583                    cx.open_url(url.as_str())
3584                })
3585            },
3586        )
3587        .hoverable_tooltip(move |_| tooltip.clone().into())
3588        .into_any()
3589}
3590
3591fn deploy_blame_entry_context_menu(
3592    blame_entry: &BlameEntry,
3593    details: Option<&CommitDetails>,
3594    editor: View<Editor>,
3595    position: gpui::Point<Pixels>,
3596    cx: &mut WindowContext<'_>,
3597) {
3598    let context_menu = ContextMenu::build(cx, move |this, _| {
3599        let sha = format!("{}", blame_entry.sha);
3600        this.entry("Copy commit SHA", None, move |cx| {
3601            cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
3602        })
3603        .when_some(
3604            details.and_then(|details| details.permalink.clone()),
3605            |this, url| this.entry("Open permalink", None, move |cx| cx.open_url(url.as_str())),
3606        )
3607    });
3608
3609    editor.update(cx, move |editor, cx| {
3610        editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
3611        cx.notify();
3612    });
3613}
3614
3615#[derive(Debug)]
3616pub(crate) struct LineWithInvisibles {
3617    pub line: ShapedLine,
3618    invisibles: Vec<Invisible>,
3619}
3620
3621impl LineWithInvisibles {
3622    fn from_chunks<'a>(
3623        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
3624        text_style: &TextStyle,
3625        max_line_len: usize,
3626        max_line_count: usize,
3627        line_number_layouts: &[Option<ShapedLine>],
3628        editor_mode: EditorMode,
3629        cx: &WindowContext,
3630    ) -> Vec<Self> {
3631        let mut layouts = Vec::with_capacity(max_line_count);
3632        let mut line = String::new();
3633        let mut invisibles = Vec::new();
3634        let mut styles = Vec::new();
3635        let mut non_whitespace_added = false;
3636        let mut row = 0;
3637        let mut line_exceeded_max_len = false;
3638        let font_size = text_style.font_size.to_pixels(cx.rem_size());
3639
3640        for highlighted_chunk in chunks.chain([HighlightedChunk {
3641            chunk: "\n",
3642            style: None,
3643            is_tab: false,
3644        }]) {
3645            for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
3646                if ix > 0 {
3647                    let shaped_line = cx
3648                        .text_system()
3649                        .shape_line(line.clone().into(), font_size, &styles)
3650                        .unwrap();
3651                    layouts.push(Self {
3652                        line: shaped_line,
3653                        invisibles: std::mem::take(&mut invisibles),
3654                    });
3655
3656                    line.clear();
3657                    styles.clear();
3658                    row += 1;
3659                    line_exceeded_max_len = false;
3660                    non_whitespace_added = false;
3661                    if row == max_line_count {
3662                        return layouts;
3663                    }
3664                }
3665
3666                if !line_chunk.is_empty() && !line_exceeded_max_len {
3667                    let text_style = if let Some(style) = highlighted_chunk.style {
3668                        Cow::Owned(text_style.clone().highlight(style))
3669                    } else {
3670                        Cow::Borrowed(text_style)
3671                    };
3672
3673                    if line.len() + line_chunk.len() > max_line_len {
3674                        let mut chunk_len = max_line_len - line.len();
3675                        while !line_chunk.is_char_boundary(chunk_len) {
3676                            chunk_len -= 1;
3677                        }
3678                        line_chunk = &line_chunk[..chunk_len];
3679                        line_exceeded_max_len = true;
3680                    }
3681
3682                    styles.push(TextRun {
3683                        len: line_chunk.len(),
3684                        font: text_style.font(),
3685                        color: text_style.color,
3686                        background_color: text_style.background_color,
3687                        underline: text_style.underline,
3688                        strikethrough: text_style.strikethrough,
3689                    });
3690
3691                    if editor_mode == EditorMode::Full {
3692                        // Line wrap pads its contents with fake whitespaces,
3693                        // avoid printing them
3694                        let inside_wrapped_string = line_number_layouts
3695                            .get(row)
3696                            .and_then(|layout| layout.as_ref())
3697                            .is_none();
3698                        if highlighted_chunk.is_tab {
3699                            if non_whitespace_added || !inside_wrapped_string {
3700                                invisibles.push(Invisible::Tab {
3701                                    line_start_offset: line.len(),
3702                                });
3703                            }
3704                        } else {
3705                            invisibles.extend(
3706                                line_chunk
3707                                    .chars()
3708                                    .enumerate()
3709                                    .filter(|(_, line_char)| {
3710                                        let is_whitespace = line_char.is_whitespace();
3711                                        non_whitespace_added |= !is_whitespace;
3712                                        is_whitespace
3713                                            && (non_whitespace_added || !inside_wrapped_string)
3714                                    })
3715                                    .map(|(whitespace_index, _)| Invisible::Whitespace {
3716                                        line_offset: line.len() + whitespace_index,
3717                                    }),
3718                            )
3719                        }
3720                    }
3721
3722                    line.push_str(line_chunk);
3723                }
3724            }
3725        }
3726
3727        layouts
3728    }
3729
3730    fn draw(
3731        &self,
3732        layout: &EditorLayout,
3733        row: DisplayRow,
3734        content_origin: gpui::Point<Pixels>,
3735        whitespace_setting: ShowWhitespaceSetting,
3736        selection_ranges: &[Range<DisplayPoint>],
3737        cx: &mut WindowContext,
3738    ) {
3739        let line_height = layout.position_map.line_height;
3740        let line_y = line_height
3741            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
3742
3743        let line_origin =
3744            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
3745        self.line.paint(line_origin, line_height, cx).log_err();
3746
3747        self.draw_invisibles(
3748            &selection_ranges,
3749            layout,
3750            content_origin,
3751            line_y,
3752            row,
3753            line_height,
3754            whitespace_setting,
3755            cx,
3756        );
3757    }
3758
3759    #[allow(clippy::too_many_arguments)]
3760    fn draw_invisibles(
3761        &self,
3762        selection_ranges: &[Range<DisplayPoint>],
3763        layout: &EditorLayout,
3764        content_origin: gpui::Point<Pixels>,
3765        line_y: Pixels,
3766        row: DisplayRow,
3767        line_height: Pixels,
3768        whitespace_setting: ShowWhitespaceSetting,
3769        cx: &mut WindowContext,
3770    ) {
3771        let allowed_invisibles_regions = match whitespace_setting {
3772            ShowWhitespaceSetting::None => return,
3773            ShowWhitespaceSetting::Selection => Some(selection_ranges),
3774            ShowWhitespaceSetting::All => None,
3775        };
3776
3777        for invisible in &self.invisibles {
3778            let (&token_offset, invisible_symbol) = match invisible {
3779                Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
3780                Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
3781            };
3782
3783            let x_offset = self.line.x_for_index(token_offset);
3784            let invisible_offset =
3785                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
3786            let origin = content_origin
3787                + gpui::point(
3788                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
3789                    line_y,
3790                );
3791
3792            if let Some(allowed_regions) = allowed_invisibles_regions {
3793                let invisible_point = DisplayPoint::new(row, token_offset as u32);
3794                if !allowed_regions
3795                    .iter()
3796                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
3797                {
3798                    continue;
3799                }
3800            }
3801            invisible_symbol.paint(origin, line_height, cx).log_err();
3802        }
3803    }
3804}
3805
3806#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3807enum Invisible {
3808    Tab { line_start_offset: usize },
3809    Whitespace { line_offset: usize },
3810}
3811
3812impl EditorElement {
3813    /// Returns the rem size to use when rendering the [`EditorElement`].
3814    ///
3815    /// This allows UI elements to scale based on the `buffer_font_size`.
3816    fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
3817        match self.editor.read(cx).mode {
3818            EditorMode::Full => {
3819                let buffer_font_size = self.style.text.font_size;
3820                match buffer_font_size {
3821                    AbsoluteLength::Pixels(pixels) => {
3822                        let rem_size_scale = {
3823                            // Our default UI font size is 14px on a 16px base scale.
3824                            // This means the default UI font size is 0.875rems.
3825                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
3826
3827                            // We then determine the delta between a single rem and the default font
3828                            // size scale.
3829                            let default_font_size_delta = 1. - default_font_size_scale;
3830
3831                            // Finally, we add this delta to 1rem to get the scale factor that
3832                            // should be used to scale up the UI.
3833                            1. + default_font_size_delta
3834                        };
3835
3836                        Some(pixels * rem_size_scale)
3837                    }
3838                    AbsoluteLength::Rems(rems) => {
3839                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
3840                    }
3841                }
3842            }
3843            // We currently use single-line and auto-height editors in UI contexts,
3844            // so we don't want to scale everything with the buffer font size, as it
3845            // ends up looking off.
3846            EditorMode::SingleLine | EditorMode::AutoHeight { .. } => None,
3847        }
3848    }
3849}
3850
3851impl Element for EditorElement {
3852    type RequestLayoutState = ();
3853    type PrepaintState = EditorLayout;
3854
3855    fn id(&self) -> Option<ElementId> {
3856        None
3857    }
3858
3859    fn request_layout(
3860        &mut self,
3861        _: Option<&GlobalElementId>,
3862        cx: &mut WindowContext,
3863    ) -> (gpui::LayoutId, ()) {
3864        let rem_size = self.rem_size(cx);
3865        cx.with_rem_size(rem_size, |cx| {
3866            self.editor.update(cx, |editor, cx| {
3867                editor.set_style(self.style.clone(), cx);
3868
3869                let layout_id = match editor.mode {
3870                    EditorMode::SingleLine => {
3871                        let rem_size = cx.rem_size();
3872                        let mut style = Style::default();
3873                        style.size.width = relative(1.).into();
3874                        style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
3875                        cx.request_layout(style, None)
3876                    }
3877                    EditorMode::AutoHeight { max_lines } => {
3878                        let editor_handle = cx.view().clone();
3879                        let max_line_number_width =
3880                            self.max_line_number_width(&editor.snapshot(cx), cx);
3881                        cx.request_measured_layout(
3882                            Style::default(),
3883                            move |known_dimensions, available_space, cx| {
3884                                editor_handle
3885                                    .update(cx, |editor, cx| {
3886                                        compute_auto_height_layout(
3887                                            editor,
3888                                            max_lines,
3889                                            max_line_number_width,
3890                                            known_dimensions,
3891                                            available_space.width,
3892                                            cx,
3893                                        )
3894                                    })
3895                                    .unwrap_or_default()
3896                            },
3897                        )
3898                    }
3899                    EditorMode::Full => {
3900                        let mut style = Style::default();
3901                        style.size.width = relative(1.).into();
3902                        style.size.height = relative(1.).into();
3903                        cx.request_layout(style, None)
3904                    }
3905                };
3906
3907                (layout_id, ())
3908            })
3909        })
3910    }
3911
3912    fn prepaint(
3913        &mut self,
3914        _: Option<&GlobalElementId>,
3915        bounds: Bounds<Pixels>,
3916        _: &mut Self::RequestLayoutState,
3917        cx: &mut WindowContext,
3918    ) -> Self::PrepaintState {
3919        let text_style = TextStyleRefinement {
3920            font_size: Some(self.style.text.font_size),
3921            line_height: Some(self.style.text.line_height),
3922            ..Default::default()
3923        };
3924        cx.set_view_id(self.editor.entity_id());
3925
3926        let rem_size = self.rem_size(cx);
3927        cx.with_rem_size(rem_size, |cx| {
3928            cx.with_text_style(Some(text_style), |cx| {
3929                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3930                    let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
3931                    let style = self.style.clone();
3932
3933                    let font_id = cx.text_system().resolve_font(&style.text.font());
3934                    let font_size = style.text.font_size.to_pixels(cx.rem_size());
3935                    let line_height = style.text.line_height_in_pixels(cx.rem_size());
3936                    let em_width = cx
3937                        .text_system()
3938                        .typographic_bounds(font_id, font_size, 'm')
3939                        .unwrap()
3940                        .size
3941                        .width;
3942                    let em_advance = cx
3943                        .text_system()
3944                        .advance(font_id, font_size, 'm')
3945                        .unwrap()
3946                        .width;
3947
3948                    let gutter_dimensions = snapshot.gutter_dimensions(
3949                        font_id,
3950                        font_size,
3951                        em_width,
3952                        self.max_line_number_width(&snapshot, cx),
3953                        cx,
3954                    );
3955                    let text_width = bounds.size.width - gutter_dimensions.width;
3956
3957                    let right_margin = if snapshot.mode == EditorMode::Full {
3958                        EditorElement::SCROLLBAR_WIDTH
3959                    } else {
3960                        px(0.)
3961                    };
3962                    let overscroll = size(em_width + right_margin, px(0.));
3963
3964                    snapshot = self.editor.update(cx, |editor, cx| {
3965                        editor.last_bounds = Some(bounds);
3966                        editor.gutter_dimensions = gutter_dimensions;
3967                        editor.set_visible_line_count(bounds.size.height / line_height, cx);
3968
3969                        let editor_width =
3970                            text_width - gutter_dimensions.margin - overscroll.width - em_width;
3971                        let wrap_width = match editor.soft_wrap_mode(cx) {
3972                            SoftWrap::None => None,
3973                            SoftWrap::PreferLine => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
3974                            SoftWrap::EditorWidth => Some(editor_width),
3975                            SoftWrap::Column(column) => {
3976                                Some(editor_width.min(column as f32 * em_advance))
3977                            }
3978                        };
3979
3980                        if editor.set_wrap_width(wrap_width, cx) {
3981                            editor.snapshot(cx)
3982                        } else {
3983                            snapshot
3984                        }
3985                    });
3986
3987                    let wrap_guides = self
3988                        .editor
3989                        .read(cx)
3990                        .wrap_guides(cx)
3991                        .iter()
3992                        .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
3993                        .collect::<SmallVec<[_; 2]>>();
3994
3995                    let hitbox = cx.insert_hitbox(bounds, false);
3996                    let gutter_hitbox = cx.insert_hitbox(
3997                        Bounds {
3998                            origin: bounds.origin,
3999                            size: size(gutter_dimensions.width, bounds.size.height),
4000                        },
4001                        false,
4002                    );
4003                    let text_hitbox = cx.insert_hitbox(
4004                        Bounds {
4005                            origin: gutter_hitbox.upper_right(),
4006                            size: size(text_width, bounds.size.height),
4007                        },
4008                        false,
4009                    );
4010                    // Offset the content_bounds from the text_bounds by the gutter margin (which
4011                    // is roughly half a character wide) to make hit testing work more like how we want.
4012                    let content_origin =
4013                        text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
4014
4015                    let mut autoscroll_containing_element = false;
4016                    let mut autoscroll_horizontally = false;
4017                    self.editor.update(cx, |editor, cx| {
4018                        autoscroll_containing_element =
4019                            editor.autoscroll_requested() || editor.has_pending_selection();
4020                        autoscroll_horizontally =
4021                            editor.autoscroll_vertically(bounds, line_height, cx);
4022                        snapshot = editor.snapshot(cx);
4023                    });
4024
4025                    let mut scroll_position = snapshot.scroll_position();
4026                    // The scroll position is a fractional point, the whole number of which represents
4027                    // the top of the window in terms of display rows.
4028                    let start_row = DisplayRow(scroll_position.y as u32);
4029                    let height_in_lines = bounds.size.height / line_height;
4030                    let max_row = snapshot.max_point().row();
4031                    let end_row = cmp::min(
4032                        (scroll_position.y + height_in_lines).ceil() as u32,
4033                        max_row.next_row().0,
4034                    );
4035                    let end_row = DisplayRow(end_row);
4036
4037                    let buffer_rows = snapshot
4038                        .buffer_rows(start_row)
4039                        .take((start_row..end_row).len())
4040                        .collect::<Vec<_>>();
4041
4042                    let start_anchor = if start_row == Default::default() {
4043                        Anchor::min()
4044                    } else {
4045                        snapshot.buffer_snapshot.anchor_before(
4046                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
4047                        )
4048                    };
4049                    let end_anchor = if end_row > max_row {
4050                        Anchor::max()
4051                    } else {
4052                        snapshot.buffer_snapshot.anchor_before(
4053                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
4054                        )
4055                    };
4056
4057                    let highlighted_rows = self
4058                        .editor
4059                        .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
4060                    let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
4061                        start_anchor..end_anchor,
4062                        &snapshot.display_snapshot,
4063                        cx.theme().colors(),
4064                    );
4065
4066                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
4067                        start_anchor..end_anchor,
4068                        &snapshot.display_snapshot,
4069                        cx,
4070                    );
4071
4072                    let (selections, active_rows, newest_selection_head) = self.layout_selections(
4073                        start_anchor,
4074                        end_anchor,
4075                        &snapshot,
4076                        start_row,
4077                        end_row,
4078                        cx,
4079                    );
4080
4081                    let line_numbers = self.layout_line_numbers(
4082                        start_row..end_row,
4083                        buffer_rows.iter().copied(),
4084                        &active_rows,
4085                        newest_selection_head,
4086                        &snapshot,
4087                        cx,
4088                    );
4089
4090                    let mut gutter_fold_toggles =
4091                        cx.with_element_namespace("gutter_fold_toggles", |cx| {
4092                            self.layout_gutter_fold_toggles(
4093                                start_row..end_row,
4094                                buffer_rows.iter().copied(),
4095                                &active_rows,
4096                                &snapshot,
4097                                cx,
4098                            )
4099                        });
4100                    let flap_trailers = cx.with_element_namespace("flap_trailers", |cx| {
4101                        self.layout_flap_trailers(buffer_rows.iter().copied(), &snapshot, cx)
4102                    });
4103
4104                    let display_hunks = self.layout_git_gutters(
4105                        line_height,
4106                        &gutter_hitbox,
4107                        start_row..end_row,
4108                        &snapshot,
4109                        cx,
4110                    );
4111
4112                    let mut max_visible_line_width = Pixels::ZERO;
4113                    let line_layouts =
4114                        self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
4115                    for line_with_invisibles in &line_layouts {
4116                        if line_with_invisibles.line.width > max_visible_line_width {
4117                            max_visible_line_width = line_with_invisibles.line.width;
4118                        }
4119                    }
4120
4121                    let longest_line_width =
4122                        layout_line(snapshot.longest_row(), &snapshot, &style, cx)
4123                            .unwrap()
4124                            .width;
4125                    let mut scroll_width =
4126                        longest_line_width.max(max_visible_line_width) + overscroll.width;
4127
4128                    let mut blocks = cx.with_element_namespace("blocks", |cx| {
4129                        self.build_blocks(
4130                            start_row..end_row,
4131                            &snapshot,
4132                            &hitbox,
4133                            &text_hitbox,
4134                            &mut scroll_width,
4135                            &gutter_dimensions,
4136                            em_width,
4137                            gutter_dimensions.width + gutter_dimensions.margin,
4138                            line_height,
4139                            &line_layouts,
4140                            cx,
4141                        )
4142                    });
4143
4144                    let scroll_pixel_position = point(
4145                        scroll_position.x * em_width,
4146                        scroll_position.y * line_height,
4147                    );
4148
4149                    let flap_trailers = cx.with_element_namespace("flap_trailers", |cx| {
4150                        self.prepaint_flap_trailers(
4151                            flap_trailers,
4152                            &line_layouts,
4153                            line_height,
4154                            content_origin,
4155                            scroll_pixel_position,
4156                            em_width,
4157                            cx,
4158                        )
4159                    });
4160
4161                    let mut inline_blame = None;
4162                    if let Some(newest_selection_head) = newest_selection_head {
4163                        let display_row = newest_selection_head.row();
4164                        if (start_row..end_row).contains(&display_row) {
4165                            let line_ix = display_row.minus(start_row) as usize;
4166                            let line_layout = &line_layouts[line_ix];
4167                            let flap_trailer_layout = flap_trailers[line_ix].as_ref();
4168                            inline_blame = self.layout_inline_blame(
4169                                display_row,
4170                                &snapshot.display_snapshot,
4171                                line_layout,
4172                                flap_trailer_layout,
4173                                em_width,
4174                                content_origin,
4175                                scroll_pixel_position,
4176                                line_height,
4177                                cx,
4178                            );
4179                        }
4180                    }
4181
4182                    let blamed_display_rows = self.layout_blame_entries(
4183                        buffer_rows.into_iter(),
4184                        em_width,
4185                        scroll_position,
4186                        line_height,
4187                        &gutter_hitbox,
4188                        gutter_dimensions.git_blame_entries_width,
4189                        cx,
4190                    );
4191
4192                    let scroll_max = point(
4193                        ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
4194                        max_row.as_f32(),
4195                    );
4196
4197                    self.editor.update(cx, |editor, cx| {
4198                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
4199
4200                        let autoscrolled = if autoscroll_horizontally {
4201                            editor.autoscroll_horizontally(
4202                                start_row,
4203                                text_hitbox.size.width,
4204                                scroll_width,
4205                                em_width,
4206                                &line_layouts,
4207                                cx,
4208                            )
4209                        } else {
4210                            false
4211                        };
4212
4213                        if clamped || autoscrolled {
4214                            snapshot = editor.snapshot(cx);
4215                            scroll_position = snapshot.scroll_position();
4216                        }
4217                    });
4218
4219                    cx.with_element_namespace("blocks", |cx| {
4220                        self.layout_blocks(
4221                            &mut blocks,
4222                            &hitbox,
4223                            line_height,
4224                            scroll_pixel_position,
4225                            cx,
4226                        );
4227                    });
4228
4229                    let cursors = self.collect_cursors(&snapshot, cx);
4230                    let visible_row_range = start_row..end_row;
4231                    let non_visible_cursors = cursors
4232                        .iter()
4233                        .any(move |c| !visible_row_range.contains(&c.0.row()));
4234
4235                    let visible_cursors = self.layout_visible_cursors(
4236                        &snapshot,
4237                        &selections,
4238                        start_row..end_row,
4239                        &line_layouts,
4240                        &text_hitbox,
4241                        content_origin,
4242                        scroll_position,
4243                        scroll_pixel_position,
4244                        line_height,
4245                        em_width,
4246                        autoscroll_containing_element,
4247                        cx,
4248                    );
4249
4250                    let scrollbar_layout = self.layout_scrollbar(
4251                        &snapshot,
4252                        bounds,
4253                        scroll_position,
4254                        height_in_lines,
4255                        non_visible_cursors,
4256                        cx,
4257                    );
4258
4259                    let folds = cx.with_element_namespace("folds", |cx| {
4260                        self.layout_folds(
4261                            &snapshot,
4262                            content_origin,
4263                            start_anchor..end_anchor,
4264                            start_row..end_row,
4265                            scroll_pixel_position,
4266                            line_height,
4267                            &line_layouts,
4268                            cx,
4269                        )
4270                    });
4271
4272                    let gutter_settings = EditorSettings::get_global(cx).gutter;
4273
4274                    let mut context_menu_visible = false;
4275                    let mut code_actions_indicator = None;
4276                    if let Some(newest_selection_head) = newest_selection_head {
4277                        if (start_row..end_row).contains(&newest_selection_head.row()) {
4278                            context_menu_visible = self.layout_context_menu(
4279                                line_height,
4280                                &hitbox,
4281                                &text_hitbox,
4282                                content_origin,
4283                                start_row,
4284                                scroll_pixel_position,
4285                                &line_layouts,
4286                                newest_selection_head,
4287                                gutter_dimensions.width - gutter_dimensions.left_padding,
4288                                cx,
4289                            );
4290
4291                            let show_code_actions = snapshot
4292                                .show_code_actions
4293                                .unwrap_or_else(|| gutter_settings.code_actions);
4294                            if show_code_actions {
4295                                let newest_selection_point =
4296                                    newest_selection_head.to_point(&snapshot.display_snapshot);
4297                                let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
4298                                    MultiBufferRow(newest_selection_point.row),
4299                                );
4300                                if let Some((buffer, range)) = buffer {
4301                                    let buffer_id = buffer.remote_id();
4302                                    let row = range.start.row;
4303                                    let has_test_indicator =
4304                                        self.editor.read(cx).tasks.contains_key(&(buffer_id, row));
4305
4306                                    if !has_test_indicator {
4307                                        code_actions_indicator = self
4308                                            .layout_code_actions_indicator(
4309                                                line_height,
4310                                                newest_selection_head,
4311                                                scroll_pixel_position,
4312                                                &gutter_dimensions,
4313                                                &gutter_hitbox,
4314                                                cx,
4315                                            );
4316                                    }
4317                                }
4318                            }
4319                        }
4320                    }
4321
4322                    let test_indicators = self.layout_run_indicators(
4323                        line_height,
4324                        scroll_pixel_position,
4325                        &gutter_dimensions,
4326                        &gutter_hitbox,
4327                        &snapshot,
4328                        cx,
4329                    );
4330
4331                    if !context_menu_visible && !cx.has_active_drag() {
4332                        self.layout_hover_popovers(
4333                            &snapshot,
4334                            &hitbox,
4335                            &text_hitbox,
4336                            start_row..end_row,
4337                            content_origin,
4338                            scroll_pixel_position,
4339                            &line_layouts,
4340                            line_height,
4341                            em_width,
4342                            cx,
4343                        );
4344                    }
4345
4346                    let mouse_context_menu = self.layout_mouse_context_menu(cx);
4347
4348                    cx.with_element_namespace("gutter_fold_toggles", |cx| {
4349                        self.prepaint_gutter_fold_toggles(
4350                            &mut gutter_fold_toggles,
4351                            line_height,
4352                            &gutter_dimensions,
4353                            gutter_settings,
4354                            scroll_pixel_position,
4355                            &gutter_hitbox,
4356                            cx,
4357                        )
4358                    });
4359
4360                    let invisible_symbol_font_size = font_size / 2.;
4361                    let tab_invisible = cx
4362                        .text_system()
4363                        .shape_line(
4364                            "".into(),
4365                            invisible_symbol_font_size,
4366                            &[TextRun {
4367                                len: "".len(),
4368                                font: self.style.text.font(),
4369                                color: cx.theme().colors().editor_invisible,
4370                                background_color: None,
4371                                underline: None,
4372                                strikethrough: None,
4373                            }],
4374                        )
4375                        .unwrap();
4376                    let space_invisible = cx
4377                        .text_system()
4378                        .shape_line(
4379                            "".into(),
4380                            invisible_symbol_font_size,
4381                            &[TextRun {
4382                                len: "".len(),
4383                                font: self.style.text.font(),
4384                                color: cx.theme().colors().editor_invisible,
4385                                background_color: None,
4386                                underline: None,
4387                                strikethrough: None,
4388                            }],
4389                        )
4390                        .unwrap();
4391
4392                    EditorLayout {
4393                        mode: snapshot.mode,
4394                        position_map: Arc::new(PositionMap {
4395                            size: bounds.size,
4396                            scroll_pixel_position,
4397                            scroll_max,
4398                            line_layouts,
4399                            line_height,
4400                            em_width,
4401                            em_advance,
4402                            snapshot,
4403                        }),
4404                        visible_display_row_range: start_row..end_row,
4405                        wrap_guides,
4406                        hitbox,
4407                        text_hitbox,
4408                        gutter_hitbox,
4409                        gutter_dimensions,
4410                        content_origin,
4411                        scrollbar_layout,
4412                        active_rows,
4413                        highlighted_rows,
4414                        highlighted_ranges,
4415                        redacted_ranges,
4416                        line_numbers,
4417                        display_hunks,
4418                        blamed_display_rows,
4419                        inline_blame,
4420                        folds,
4421                        blocks,
4422                        cursors,
4423                        visible_cursors,
4424                        selections,
4425                        mouse_context_menu,
4426                        test_indicators,
4427                        code_actions_indicator,
4428                        gutter_fold_toggles,
4429                        flap_trailers,
4430                        tab_invisible,
4431                        space_invisible,
4432                    }
4433                })
4434            })
4435        })
4436    }
4437
4438    fn paint(
4439        &mut self,
4440        _: Option<&GlobalElementId>,
4441        bounds: Bounds<gpui::Pixels>,
4442        _: &mut Self::RequestLayoutState,
4443        layout: &mut Self::PrepaintState,
4444        cx: &mut WindowContext,
4445    ) {
4446        let focus_handle = self.editor.focus_handle(cx);
4447        let key_context = self.editor.read(cx).key_context(cx);
4448        cx.set_focus_handle(&focus_handle);
4449        cx.set_key_context(key_context);
4450        cx.handle_input(
4451            &focus_handle,
4452            ElementInputHandler::new(bounds, self.editor.clone()),
4453        );
4454        self.register_actions(cx);
4455        self.register_key_listeners(cx, layout);
4456
4457        let text_style = TextStyleRefinement {
4458            font_size: Some(self.style.text.font_size),
4459            line_height: Some(self.style.text.line_height),
4460            ..Default::default()
4461        };
4462        let mouse_position = cx.mouse_position();
4463        let hovered_hunk = layout
4464            .display_hunks
4465            .iter()
4466            .find_map(|(hunk, hunk_hitbox)| match hunk {
4467                DisplayDiffHunk::Folded { .. } => None,
4468                DisplayDiffHunk::Unfolded {
4469                    diff_base_byte_range,
4470                    multi_buffer_range,
4471                    status,
4472                    ..
4473                } => {
4474                    if hunk_hitbox
4475                        .as_ref()
4476                        .map(|hitbox| hitbox.contains(&mouse_position))
4477                        .unwrap_or(false)
4478                    {
4479                        Some(HunkToExpand {
4480                            status: *status,
4481                            multi_buffer_range: multi_buffer_range.clone(),
4482                            diff_base_byte_range: diff_base_byte_range.clone(),
4483                        })
4484                    } else {
4485                        None
4486                    }
4487                }
4488            });
4489        let rem_size = self.rem_size(cx);
4490        cx.with_rem_size(rem_size, |cx| {
4491            cx.with_text_style(Some(text_style), |cx| {
4492                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
4493                    self.paint_mouse_listeners(layout, hovered_hunk, cx);
4494                    self.paint_background(layout, cx);
4495                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
4496                        self.paint_gutter(layout, cx)
4497                    }
4498
4499                    self.paint_text(layout, cx);
4500
4501                    if !layout.blocks.is_empty() {
4502                        cx.with_element_namespace("blocks", |cx| {
4503                            self.paint_blocks(layout, cx);
4504                        });
4505                    }
4506
4507                    self.paint_scrollbar(layout, cx);
4508                    self.paint_mouse_context_menu(layout, cx);
4509                });
4510            })
4511        })
4512    }
4513}
4514
4515impl IntoElement for EditorElement {
4516    type Element = Self;
4517
4518    fn into_element(self) -> Self::Element {
4519        self
4520    }
4521}
4522
4523pub struct EditorLayout {
4524    position_map: Arc<PositionMap>,
4525    hitbox: Hitbox,
4526    text_hitbox: Hitbox,
4527    gutter_hitbox: Hitbox,
4528    gutter_dimensions: GutterDimensions,
4529    content_origin: gpui::Point<Pixels>,
4530    scrollbar_layout: Option<ScrollbarLayout>,
4531    mode: EditorMode,
4532    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
4533    visible_display_row_range: Range<DisplayRow>,
4534    active_rows: BTreeMap<DisplayRow, bool>,
4535    highlighted_rows: BTreeMap<DisplayRow, Hsla>,
4536    line_numbers: Vec<Option<ShapedLine>>,
4537    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
4538    blamed_display_rows: Option<Vec<AnyElement>>,
4539    inline_blame: Option<AnyElement>,
4540    folds: Vec<FoldLayout>,
4541    blocks: Vec<BlockLayout>,
4542    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
4543    redacted_ranges: Vec<Range<DisplayPoint>>,
4544    cursors: Vec<(DisplayPoint, Hsla)>,
4545    visible_cursors: Vec<CursorLayout>,
4546    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
4547    code_actions_indicator: Option<AnyElement>,
4548    test_indicators: Vec<AnyElement>,
4549    gutter_fold_toggles: Vec<Option<AnyElement>>,
4550    flap_trailers: Vec<Option<FlapTrailerLayout>>,
4551    mouse_context_menu: Option<AnyElement>,
4552    tab_invisible: ShapedLine,
4553    space_invisible: ShapedLine,
4554}
4555
4556impl EditorLayout {
4557    fn line_end_overshoot(&self) -> Pixels {
4558        0.15 * self.position_map.line_height
4559    }
4560}
4561
4562struct ColoredRange<T> {
4563    start: T,
4564    end: T,
4565    color: Hsla,
4566}
4567
4568#[derive(Clone)]
4569struct ScrollbarLayout {
4570    hitbox: Hitbox,
4571    visible_row_range: Range<f32>,
4572    visible: bool,
4573    row_height: Pixels,
4574    thumb_height: Pixels,
4575}
4576
4577impl ScrollbarLayout {
4578    const BORDER_WIDTH: Pixels = px(1.0);
4579    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
4580    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
4581    const MIN_THUMB_HEIGHT: Pixels = px(20.0);
4582
4583    fn thumb_bounds(&self) -> Bounds<Pixels> {
4584        let thumb_top = self.y_for_row(self.visible_row_range.start);
4585        let thumb_bottom = thumb_top + self.thumb_height;
4586        Bounds::from_corners(
4587            point(self.hitbox.left(), thumb_top),
4588            point(self.hitbox.right(), thumb_bottom),
4589        )
4590    }
4591
4592    fn y_for_row(&self, row: f32) -> Pixels {
4593        self.hitbox.top() + row * self.row_height
4594    }
4595
4596    fn marker_quads_for_ranges(
4597        &self,
4598        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
4599        column: Option<usize>,
4600    ) -> Vec<PaintQuad> {
4601        struct MinMax {
4602            min: Pixels,
4603            max: Pixels,
4604        }
4605        let (x_range, height_limit) = if let Some(column) = column {
4606            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
4607            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
4608            let end = start + column_width;
4609            (
4610                Range { start, end },
4611                MinMax {
4612                    min: Self::MIN_MARKER_HEIGHT,
4613                    max: px(f32::MAX),
4614                },
4615            )
4616        } else {
4617            (
4618                Range {
4619                    start: Self::BORDER_WIDTH,
4620                    end: self.hitbox.size.width,
4621                },
4622                MinMax {
4623                    min: Self::LINE_MARKER_HEIGHT,
4624                    max: Self::LINE_MARKER_HEIGHT,
4625                },
4626            )
4627        };
4628
4629        let row_to_y = |row: DisplayRow| row.as_f32() * self.row_height;
4630        let mut pixel_ranges = row_ranges
4631            .into_iter()
4632            .map(|range| {
4633                let start_y = row_to_y(range.start);
4634                let end_y = row_to_y(range.end)
4635                    + self.row_height.max(height_limit.min).min(height_limit.max);
4636                ColoredRange {
4637                    start: start_y,
4638                    end: end_y,
4639                    color: range.color,
4640                }
4641            })
4642            .peekable();
4643
4644        let mut quads = Vec::new();
4645        while let Some(mut pixel_range) = pixel_ranges.next() {
4646            while let Some(next_pixel_range) = pixel_ranges.peek() {
4647                if pixel_range.end >= next_pixel_range.start - px(1.0)
4648                    && pixel_range.color == next_pixel_range.color
4649                {
4650                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
4651                    pixel_ranges.next();
4652                } else {
4653                    break;
4654                }
4655            }
4656
4657            let bounds = Bounds::from_corners(
4658                point(x_range.start, pixel_range.start),
4659                point(x_range.end, pixel_range.end),
4660            );
4661            quads.push(quad(
4662                bounds,
4663                Corners::default(),
4664                pixel_range.color,
4665                Edges::default(),
4666                Hsla::transparent_black(),
4667            ));
4668        }
4669
4670        quads
4671    }
4672}
4673
4674struct FlapTrailerLayout {
4675    element: AnyElement,
4676    bounds: Bounds<Pixels>,
4677}
4678
4679struct FoldLayout {
4680    display_range: Range<DisplayPoint>,
4681    hover_element: AnyElement,
4682}
4683
4684struct PositionMap {
4685    size: Size<Pixels>,
4686    line_height: Pixels,
4687    scroll_pixel_position: gpui::Point<Pixels>,
4688    scroll_max: gpui::Point<f32>,
4689    em_width: Pixels,
4690    em_advance: Pixels,
4691    line_layouts: Vec<LineWithInvisibles>,
4692    snapshot: EditorSnapshot,
4693}
4694
4695#[derive(Debug, Copy, Clone)]
4696pub struct PointForPosition {
4697    pub previous_valid: DisplayPoint,
4698    pub next_valid: DisplayPoint,
4699    pub exact_unclipped: DisplayPoint,
4700    pub column_overshoot_after_line_end: u32,
4701}
4702
4703impl PointForPosition {
4704    pub fn as_valid(&self) -> Option<DisplayPoint> {
4705        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
4706            Some(self.previous_valid)
4707        } else {
4708            None
4709        }
4710    }
4711}
4712
4713impl PositionMap {
4714    fn point_for_position(
4715        &self,
4716        text_bounds: Bounds<Pixels>,
4717        position: gpui::Point<Pixels>,
4718    ) -> PointForPosition {
4719        let scroll_position = self.snapshot.scroll_position();
4720        let position = position - text_bounds.origin;
4721        let y = position.y.max(px(0.)).min(self.size.height);
4722        let x = position.x + (scroll_position.x * self.em_width);
4723        let row = ((y / self.line_height) + scroll_position.y) as u32;
4724
4725        let (column, x_overshoot_after_line_end) = if let Some(line) = self
4726            .line_layouts
4727            .get(row as usize - scroll_position.y as usize)
4728            .map(|LineWithInvisibles { line, .. }| line)
4729        {
4730            if let Some(ix) = line.index_for_x(x) {
4731                (ix as u32, px(0.))
4732            } else {
4733                (line.len as u32, px(0.).max(x - line.width))
4734            }
4735        } else {
4736            (0, x)
4737        };
4738
4739        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
4740        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
4741        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
4742
4743        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
4744        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
4745        PointForPosition {
4746            previous_valid,
4747            next_valid,
4748            exact_unclipped,
4749            column_overshoot_after_line_end,
4750        }
4751    }
4752}
4753
4754struct BlockLayout {
4755    row: DisplayRow,
4756    element: AnyElement,
4757    available_space: Size<AvailableSpace>,
4758    style: BlockStyle,
4759}
4760
4761fn layout_line(
4762    row: DisplayRow,
4763    snapshot: &EditorSnapshot,
4764    style: &EditorStyle,
4765    cx: &WindowContext,
4766) -> Result<ShapedLine> {
4767    let mut line = snapshot.line(row);
4768
4769    let len = {
4770        let line_len = line.len();
4771        if line_len > MAX_LINE_LEN {
4772            let mut len = MAX_LINE_LEN;
4773            while !line.is_char_boundary(len) {
4774                len -= 1;
4775            }
4776
4777            line.truncate(len);
4778            len
4779        } else {
4780            line_len
4781        }
4782    };
4783
4784    cx.text_system().shape_line(
4785        line.into(),
4786        style.text.font_size.to_pixels(cx.rem_size()),
4787        &[TextRun {
4788            len,
4789            font: style.text.font(),
4790            color: Hsla::default(),
4791            background_color: None,
4792            underline: None,
4793            strikethrough: None,
4794        }],
4795    )
4796}
4797
4798pub struct CursorLayout {
4799    origin: gpui::Point<Pixels>,
4800    block_width: Pixels,
4801    line_height: Pixels,
4802    color: Hsla,
4803    shape: CursorShape,
4804    block_text: Option<ShapedLine>,
4805    cursor_name: Option<AnyElement>,
4806}
4807
4808#[derive(Debug)]
4809pub struct CursorName {
4810    string: SharedString,
4811    color: Hsla,
4812    is_top_row: bool,
4813}
4814
4815impl CursorLayout {
4816    pub fn new(
4817        origin: gpui::Point<Pixels>,
4818        block_width: Pixels,
4819        line_height: Pixels,
4820        color: Hsla,
4821        shape: CursorShape,
4822        block_text: Option<ShapedLine>,
4823    ) -> CursorLayout {
4824        CursorLayout {
4825            origin,
4826            block_width,
4827            line_height,
4828            color,
4829            shape,
4830            block_text,
4831            cursor_name: None,
4832        }
4833    }
4834
4835    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4836        Bounds {
4837            origin: self.origin + origin,
4838            size: size(self.block_width, self.line_height),
4839        }
4840    }
4841
4842    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4843        match self.shape {
4844            CursorShape::Bar => Bounds {
4845                origin: self.origin + origin,
4846                size: size(px(2.0), self.line_height),
4847            },
4848            CursorShape::Block | CursorShape::Hollow => Bounds {
4849                origin: self.origin + origin,
4850                size: size(self.block_width, self.line_height),
4851            },
4852            CursorShape::Underscore => Bounds {
4853                origin: self.origin
4854                    + origin
4855                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
4856                size: size(self.block_width, px(2.0)),
4857            },
4858        }
4859    }
4860
4861    pub fn layout(
4862        &mut self,
4863        origin: gpui::Point<Pixels>,
4864        cursor_name: Option<CursorName>,
4865        cx: &mut WindowContext,
4866    ) {
4867        if let Some(cursor_name) = cursor_name {
4868            let bounds = self.bounds(origin);
4869            let text_size = self.line_height / 1.5;
4870
4871            let name_origin = if cursor_name.is_top_row {
4872                point(bounds.right() - px(1.), bounds.top())
4873            } else {
4874                point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
4875            };
4876            let mut name_element = div()
4877                .bg(self.color)
4878                .text_size(text_size)
4879                .px_0p5()
4880                .line_height(text_size + px(2.))
4881                .text_color(cursor_name.color)
4882                .child(cursor_name.string.clone())
4883                .into_any_element();
4884
4885            name_element.prepaint_as_root(
4886                name_origin,
4887                size(AvailableSpace::MinContent, AvailableSpace::MinContent),
4888                cx,
4889            );
4890
4891            self.cursor_name = Some(name_element);
4892        }
4893    }
4894
4895    pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
4896        let bounds = self.bounds(origin);
4897
4898        //Draw background or border quad
4899        let cursor = if matches!(self.shape, CursorShape::Hollow) {
4900            outline(bounds, self.color)
4901        } else {
4902            fill(bounds, self.color)
4903        };
4904
4905        if let Some(name) = &mut self.cursor_name {
4906            name.paint(cx);
4907        }
4908
4909        cx.paint_quad(cursor);
4910
4911        if let Some(block_text) = &self.block_text {
4912            block_text
4913                .paint(self.origin + origin, self.line_height, cx)
4914                .log_err();
4915        }
4916    }
4917
4918    pub fn shape(&self) -> CursorShape {
4919        self.shape
4920    }
4921}
4922
4923#[derive(Debug)]
4924pub struct HighlightedRange {
4925    pub start_y: Pixels,
4926    pub line_height: Pixels,
4927    pub lines: Vec<HighlightedRangeLine>,
4928    pub color: Hsla,
4929    pub corner_radius: Pixels,
4930}
4931
4932#[derive(Debug)]
4933pub struct HighlightedRangeLine {
4934    pub start_x: Pixels,
4935    pub end_x: Pixels,
4936}
4937
4938impl HighlightedRange {
4939    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
4940        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
4941            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
4942            self.paint_lines(
4943                self.start_y + self.line_height,
4944                &self.lines[1..],
4945                bounds,
4946                cx,
4947            );
4948        } else {
4949            self.paint_lines(self.start_y, &self.lines, bounds, cx);
4950        }
4951    }
4952
4953    fn paint_lines(
4954        &self,
4955        start_y: Pixels,
4956        lines: &[HighlightedRangeLine],
4957        _bounds: Bounds<Pixels>,
4958        cx: &mut WindowContext,
4959    ) {
4960        if lines.is_empty() {
4961            return;
4962        }
4963
4964        let first_line = lines.first().unwrap();
4965        let last_line = lines.last().unwrap();
4966
4967        let first_top_left = point(first_line.start_x, start_y);
4968        let first_top_right = point(first_line.end_x, start_y);
4969
4970        let curve_height = point(Pixels::ZERO, self.corner_radius);
4971        let curve_width = |start_x: Pixels, end_x: Pixels| {
4972            let max = (end_x - start_x) / 2.;
4973            let width = if max < self.corner_radius {
4974                max
4975            } else {
4976                self.corner_radius
4977            };
4978
4979            point(width, Pixels::ZERO)
4980        };
4981
4982        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
4983        let mut path = gpui::Path::new(first_top_right - top_curve_width);
4984        path.curve_to(first_top_right + curve_height, first_top_right);
4985
4986        let mut iter = lines.iter().enumerate().peekable();
4987        while let Some((ix, line)) = iter.next() {
4988            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
4989
4990            if let Some((_, next_line)) = iter.peek() {
4991                let next_top_right = point(next_line.end_x, bottom_right.y);
4992
4993                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
4994                    Ordering::Equal => {
4995                        path.line_to(bottom_right);
4996                    }
4997                    Ordering::Less => {
4998                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
4999                        path.line_to(bottom_right - curve_height);
5000                        if self.corner_radius > Pixels::ZERO {
5001                            path.curve_to(bottom_right - curve_width, bottom_right);
5002                        }
5003                        path.line_to(next_top_right + curve_width);
5004                        if self.corner_radius > Pixels::ZERO {
5005                            path.curve_to(next_top_right + curve_height, next_top_right);
5006                        }
5007                    }
5008                    Ordering::Greater => {
5009                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
5010                        path.line_to(bottom_right - curve_height);
5011                        if self.corner_radius > Pixels::ZERO {
5012                            path.curve_to(bottom_right + curve_width, bottom_right);
5013                        }
5014                        path.line_to(next_top_right - curve_width);
5015                        if self.corner_radius > Pixels::ZERO {
5016                            path.curve_to(next_top_right + curve_height, next_top_right);
5017                        }
5018                    }
5019                }
5020            } else {
5021                let curve_width = curve_width(line.start_x, line.end_x);
5022                path.line_to(bottom_right - curve_height);
5023                if self.corner_radius > Pixels::ZERO {
5024                    path.curve_to(bottom_right - curve_width, bottom_right);
5025                }
5026
5027                let bottom_left = point(line.start_x, bottom_right.y);
5028                path.line_to(bottom_left + curve_width);
5029                if self.corner_radius > Pixels::ZERO {
5030                    path.curve_to(bottom_left - curve_height, bottom_left);
5031                }
5032            }
5033        }
5034
5035        if first_line.start_x > last_line.start_x {
5036            let curve_width = curve_width(last_line.start_x, first_line.start_x);
5037            let second_top_left = point(last_line.start_x, start_y + self.line_height);
5038            path.line_to(second_top_left + curve_height);
5039            if self.corner_radius > Pixels::ZERO {
5040                path.curve_to(second_top_left + curve_width, second_top_left);
5041            }
5042            let first_bottom_left = point(first_line.start_x, second_top_left.y);
5043            path.line_to(first_bottom_left - curve_width);
5044            if self.corner_radius > Pixels::ZERO {
5045                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
5046            }
5047        }
5048
5049        path.line_to(first_top_left + curve_height);
5050        if self.corner_radius > Pixels::ZERO {
5051            path.curve_to(first_top_left + top_curve_width, first_top_left);
5052        }
5053        path.line_to(first_top_right - top_curve_width);
5054
5055        cx.paint_path(path, self.color);
5056    }
5057}
5058
5059pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5060    (delta.pow(1.5) / 100.0).into()
5061}
5062
5063fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5064    (delta.pow(1.2) / 300.0).into()
5065}
5066
5067#[cfg(test)]
5068mod tests {
5069    use super::*;
5070    use crate::{
5071        display_map::{BlockDisposition, BlockProperties},
5072        editor_tests::{init_test, update_test_language_settings},
5073        Editor, MultiBuffer,
5074    };
5075    use gpui::{TestAppContext, VisualTestContext};
5076    use language::language_settings;
5077    use log::info;
5078    use std::num::NonZeroU32;
5079    use ui::Context;
5080    use util::test::sample_text;
5081
5082    #[gpui::test]
5083    fn test_shape_line_numbers(cx: &mut TestAppContext) {
5084        init_test(cx, |_| {});
5085        let window = cx.add_window(|cx| {
5086            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
5087            Editor::new(EditorMode::Full, buffer, None, cx)
5088        });
5089
5090        let editor = window.root(cx).unwrap();
5091        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5092        let element = EditorElement::new(&editor, style);
5093        let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
5094
5095        let layouts = cx
5096            .update_window(*window, |_, cx| {
5097                element.layout_line_numbers(
5098                    DisplayRow(0)..DisplayRow(6),
5099                    (0..6).map(MultiBufferRow).map(Some),
5100                    &Default::default(),
5101                    Some(DisplayPoint::new(DisplayRow(0), 0)),
5102                    &snapshot,
5103                    cx,
5104                )
5105            })
5106            .unwrap();
5107        assert_eq!(layouts.len(), 6);
5108
5109        let relative_rows = window
5110            .update(cx, |editor, cx| {
5111                let snapshot = editor.snapshot(cx);
5112                element.calculate_relative_line_numbers(
5113                    &snapshot,
5114                    &(DisplayRow(0)..DisplayRow(6)),
5115                    Some(DisplayRow(3)),
5116                )
5117            })
5118            .unwrap();
5119        assert_eq!(relative_rows[&DisplayRow(0)], 3);
5120        assert_eq!(relative_rows[&DisplayRow(1)], 2);
5121        assert_eq!(relative_rows[&DisplayRow(2)], 1);
5122        // current line has no relative number
5123        assert_eq!(relative_rows[&DisplayRow(4)], 1);
5124        assert_eq!(relative_rows[&DisplayRow(5)], 2);
5125
5126        // works if cursor is before screen
5127        let relative_rows = window
5128            .update(cx, |editor, cx| {
5129                let snapshot = editor.snapshot(cx);
5130                element.calculate_relative_line_numbers(
5131                    &snapshot,
5132                    &(DisplayRow(3)..DisplayRow(6)),
5133                    Some(DisplayRow(1)),
5134                )
5135            })
5136            .unwrap();
5137        assert_eq!(relative_rows.len(), 3);
5138        assert_eq!(relative_rows[&DisplayRow(3)], 2);
5139        assert_eq!(relative_rows[&DisplayRow(4)], 3);
5140        assert_eq!(relative_rows[&DisplayRow(5)], 4);
5141
5142        // works if cursor is after screen
5143        let relative_rows = window
5144            .update(cx, |editor, cx| {
5145                let snapshot = editor.snapshot(cx);
5146                element.calculate_relative_line_numbers(
5147                    &snapshot,
5148                    &(DisplayRow(0)..DisplayRow(3)),
5149                    Some(DisplayRow(6)),
5150                )
5151            })
5152            .unwrap();
5153        assert_eq!(relative_rows.len(), 3);
5154        assert_eq!(relative_rows[&DisplayRow(0)], 5);
5155        assert_eq!(relative_rows[&DisplayRow(1)], 4);
5156        assert_eq!(relative_rows[&DisplayRow(2)], 3);
5157    }
5158
5159    #[gpui::test]
5160    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
5161        init_test(cx, |_| {});
5162
5163        let window = cx.add_window(|cx| {
5164            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
5165            Editor::new(EditorMode::Full, buffer, None, cx)
5166        });
5167        let cx = &mut VisualTestContext::from_window(*window, cx);
5168        let editor = window.root(cx).unwrap();
5169        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5170
5171        window
5172            .update(cx, |editor, cx| {
5173                editor.cursor_shape = CursorShape::Block;
5174                editor.change_selections(None, cx, |s| {
5175                    s.select_ranges([
5176                        Point::new(0, 0)..Point::new(1, 0),
5177                        Point::new(3, 2)..Point::new(3, 3),
5178                        Point::new(5, 6)..Point::new(6, 0),
5179                    ]);
5180                });
5181            })
5182            .unwrap();
5183
5184        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5185            EditorElement::new(&editor, style)
5186        });
5187
5188        assert_eq!(state.selections.len(), 1);
5189        let local_selections = &state.selections[0].1;
5190        assert_eq!(local_selections.len(), 3);
5191        // moves cursor back one line
5192        assert_eq!(
5193            local_selections[0].head,
5194            DisplayPoint::new(DisplayRow(0), 6)
5195        );
5196        assert_eq!(
5197            local_selections[0].range,
5198            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
5199        );
5200
5201        // moves cursor back one column
5202        assert_eq!(
5203            local_selections[1].range,
5204            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
5205        );
5206        assert_eq!(
5207            local_selections[1].head,
5208            DisplayPoint::new(DisplayRow(3), 2)
5209        );
5210
5211        // leaves cursor on the max point
5212        assert_eq!(
5213            local_selections[2].range,
5214            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
5215        );
5216        assert_eq!(
5217            local_selections[2].head,
5218            DisplayPoint::new(DisplayRow(6), 0)
5219        );
5220
5221        // active lines does not include 1 (even though the range of the selection does)
5222        assert_eq!(
5223            state.active_rows.keys().cloned().collect::<Vec<_>>(),
5224            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
5225        );
5226
5227        // multi-buffer support
5228        // in DisplayPoint coordinates, this is what we're dealing with:
5229        //  0: [[file
5230        //  1:   header]]
5231        //  2: aaaaaa
5232        //  3: bbbbbb
5233        //  4: cccccc
5234        //  5:
5235        //  6: ...
5236        //  7: ffffff
5237        //  8: gggggg
5238        //  9: hhhhhh
5239        // 10:
5240        // 11: [[file
5241        // 12:   header]]
5242        // 13: bbbbbb
5243        // 14: cccccc
5244        // 15: dddddd
5245        let window = cx.add_window(|cx| {
5246            let buffer = MultiBuffer::build_multi(
5247                [
5248                    (
5249                        &(sample_text(8, 6, 'a') + "\n"),
5250                        vec![
5251                            Point::new(0, 0)..Point::new(3, 0),
5252                            Point::new(4, 0)..Point::new(7, 0),
5253                        ],
5254                    ),
5255                    (
5256                        &(sample_text(8, 6, 'a') + "\n"),
5257                        vec![Point::new(1, 0)..Point::new(3, 0)],
5258                    ),
5259                ],
5260                cx,
5261            );
5262            Editor::new(EditorMode::Full, buffer, None, cx)
5263        });
5264        let editor = window.root(cx).unwrap();
5265        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5266        let _state = window.update(cx, |editor, cx| {
5267            editor.cursor_shape = CursorShape::Block;
5268            editor.change_selections(None, cx, |s| {
5269                s.select_display_ranges([
5270                    DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
5271                    DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
5272                ]);
5273            });
5274        });
5275
5276        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5277            EditorElement::new(&editor, style)
5278        });
5279        assert_eq!(state.selections.len(), 1);
5280        let local_selections = &state.selections[0].1;
5281        assert_eq!(local_selections.len(), 2);
5282
5283        // moves cursor on excerpt boundary back a line
5284        // and doesn't allow selection to bleed through
5285        assert_eq!(
5286            local_selections[0].range,
5287            DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(6), 0)
5288        );
5289        assert_eq!(
5290            local_selections[0].head,
5291            DisplayPoint::new(DisplayRow(5), 0)
5292        );
5293        // moves cursor on buffer boundary back two lines
5294        // and doesn't allow selection to bleed through
5295        assert_eq!(
5296            local_selections[1].range,
5297            DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(11), 0)
5298        );
5299        assert_eq!(
5300            local_selections[1].head,
5301            DisplayPoint::new(DisplayRow(10), 0)
5302        );
5303    }
5304
5305    #[gpui::test]
5306    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
5307        init_test(cx, |_| {});
5308
5309        let window = cx.add_window(|cx| {
5310            let buffer = MultiBuffer::build_simple("", cx);
5311            Editor::new(EditorMode::Full, buffer, None, cx)
5312        });
5313        let cx = &mut VisualTestContext::from_window(*window, cx);
5314        let editor = window.root(cx).unwrap();
5315        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5316        window
5317            .update(cx, |editor, cx| {
5318                editor.set_placeholder_text("hello", cx);
5319                editor.insert_blocks(
5320                    [BlockProperties {
5321                        style: BlockStyle::Fixed,
5322                        disposition: BlockDisposition::Above,
5323                        height: 3,
5324                        position: Anchor::min(),
5325                        render: Box::new(|_| div().into_any()),
5326                    }],
5327                    None,
5328                    cx,
5329                );
5330
5331                // Blur the editor so that it displays placeholder text.
5332                cx.blur();
5333            })
5334            .unwrap();
5335
5336        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5337            EditorElement::new(&editor, style)
5338        });
5339        assert_eq!(state.position_map.line_layouts.len(), 4);
5340        assert_eq!(
5341            state
5342                .line_numbers
5343                .iter()
5344                .map(Option::is_some)
5345                .collect::<Vec<_>>(),
5346            &[false, false, false, true]
5347        );
5348    }
5349
5350    #[gpui::test]
5351    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
5352        const TAB_SIZE: u32 = 4;
5353
5354        let input_text = "\t \t|\t| a b";
5355        let expected_invisibles = vec![
5356            Invisible::Tab {
5357                line_start_offset: 0,
5358            },
5359            Invisible::Whitespace {
5360                line_offset: TAB_SIZE as usize,
5361            },
5362            Invisible::Tab {
5363                line_start_offset: TAB_SIZE as usize + 1,
5364            },
5365            Invisible::Tab {
5366                line_start_offset: TAB_SIZE as usize * 2 + 1,
5367            },
5368            Invisible::Whitespace {
5369                line_offset: TAB_SIZE as usize * 3 + 1,
5370            },
5371            Invisible::Whitespace {
5372                line_offset: TAB_SIZE as usize * 3 + 3,
5373            },
5374        ];
5375        assert_eq!(
5376            expected_invisibles.len(),
5377            input_text
5378                .chars()
5379                .filter(|initial_char| initial_char.is_whitespace())
5380                .count(),
5381            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
5382        );
5383
5384        init_test(cx, |s| {
5385            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
5386            s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
5387        });
5388
5389        let actual_invisibles =
5390            collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
5391
5392        assert_eq!(expected_invisibles, actual_invisibles);
5393    }
5394
5395    #[gpui::test]
5396    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
5397        init_test(cx, |s| {
5398            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
5399            s.defaults.tab_size = NonZeroU32::new(4);
5400        });
5401
5402        for editor_mode_without_invisibles in [
5403            EditorMode::SingleLine,
5404            EditorMode::AutoHeight { max_lines: 100 },
5405        ] {
5406            let invisibles = collect_invisibles_from_new_editor(
5407                cx,
5408                editor_mode_without_invisibles,
5409                "\t\t\t| | a b",
5410                px(500.0),
5411            );
5412            assert!(invisibles.is_empty(),
5413                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
5414        }
5415    }
5416
5417    #[gpui::test]
5418    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
5419        let tab_size = 4;
5420        let input_text = "a\tbcd   ".repeat(9);
5421        let repeated_invisibles = [
5422            Invisible::Tab {
5423                line_start_offset: 1,
5424            },
5425            Invisible::Whitespace {
5426                line_offset: tab_size as usize + 3,
5427            },
5428            Invisible::Whitespace {
5429                line_offset: tab_size as usize + 4,
5430            },
5431            Invisible::Whitespace {
5432                line_offset: tab_size as usize + 5,
5433            },
5434        ];
5435        let expected_invisibles = std::iter::once(repeated_invisibles)
5436            .cycle()
5437            .take(9)
5438            .flatten()
5439            .collect::<Vec<_>>();
5440        assert_eq!(
5441            expected_invisibles.len(),
5442            input_text
5443                .chars()
5444                .filter(|initial_char| initial_char.is_whitespace())
5445                .count(),
5446            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
5447        );
5448        info!("Expected invisibles: {expected_invisibles:?}");
5449
5450        init_test(cx, |_| {});
5451
5452        // Put the same string with repeating whitespace pattern into editors of various size,
5453        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
5454        let resize_step = 10.0;
5455        let mut editor_width = 200.0;
5456        while editor_width <= 1000.0 {
5457            update_test_language_settings(cx, |s| {
5458                s.defaults.tab_size = NonZeroU32::new(tab_size);
5459                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
5460                s.defaults.preferred_line_length = Some(editor_width as u32);
5461                s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
5462            });
5463
5464            let actual_invisibles = collect_invisibles_from_new_editor(
5465                cx,
5466                EditorMode::Full,
5467                &input_text,
5468                px(editor_width),
5469            );
5470
5471            // Whatever the editor size is, ensure it has the same invisible kinds in the same order
5472            // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
5473            let mut i = 0;
5474            for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
5475                i = actual_index;
5476                match expected_invisibles.get(i) {
5477                    Some(expected_invisible) => match (expected_invisible, actual_invisible) {
5478                        (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
5479                        | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
5480                        _ => {
5481                            panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
5482                        }
5483                    },
5484                    None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
5485                }
5486            }
5487            let missing_expected_invisibles = &expected_invisibles[i + 1..];
5488            assert!(
5489                missing_expected_invisibles.is_empty(),
5490                "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
5491            );
5492
5493            editor_width += resize_step;
5494        }
5495    }
5496
5497    fn collect_invisibles_from_new_editor(
5498        cx: &mut TestAppContext,
5499        editor_mode: EditorMode,
5500        input_text: &str,
5501        editor_width: Pixels,
5502    ) -> Vec<Invisible> {
5503        info!(
5504            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
5505            editor_width.0
5506        );
5507        let window = cx.add_window(|cx| {
5508            let buffer = MultiBuffer::build_simple(&input_text, cx);
5509            Editor::new(editor_mode, buffer, None, cx)
5510        });
5511        let cx = &mut VisualTestContext::from_window(*window, cx);
5512        let editor = window.root(cx).unwrap();
5513        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5514        window
5515            .update(cx, |editor, cx| {
5516                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
5517                editor.set_wrap_width(Some(editor_width), cx);
5518            })
5519            .unwrap();
5520        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5521            EditorElement::new(&editor, style)
5522        });
5523        state
5524            .position_map
5525            .line_layouts
5526            .iter()
5527            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
5528            .cloned()
5529            .collect()
5530    }
5531}
5532
5533pub fn register_action<T: Action>(
5534    view: &View<Editor>,
5535    cx: &mut WindowContext,
5536    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
5537) {
5538    let view = view.clone();
5539    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
5540        let action = action.downcast_ref().unwrap();
5541        if phase == DispatchPhase::Bubble {
5542            view.update(cx, |editor, cx| {
5543                listener(editor, action, cx);
5544            })
5545        }
5546    })
5547}
5548
5549fn compute_auto_height_layout(
5550    editor: &mut Editor,
5551    max_lines: usize,
5552    max_line_number_width: Pixels,
5553    known_dimensions: Size<Option<Pixels>>,
5554    available_width: AvailableSpace,
5555    cx: &mut ViewContext<Editor>,
5556) -> Option<Size<Pixels>> {
5557    let width = known_dimensions.width.or_else(|| {
5558        if let AvailableSpace::Definite(available_width) = available_width {
5559            Some(available_width)
5560        } else {
5561            None
5562        }
5563    })?;
5564    if let Some(height) = known_dimensions.height {
5565        return Some(size(width, height));
5566    }
5567
5568    let style = editor.style.as_ref().unwrap();
5569    let font_id = cx.text_system().resolve_font(&style.text.font());
5570    let font_size = style.text.font_size.to_pixels(cx.rem_size());
5571    let line_height = style.text.line_height_in_pixels(cx.rem_size());
5572    let em_width = cx
5573        .text_system()
5574        .typographic_bounds(font_id, font_size, 'm')
5575        .unwrap()
5576        .size
5577        .width;
5578
5579    let mut snapshot = editor.snapshot(cx);
5580    let gutter_dimensions =
5581        snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
5582
5583    editor.gutter_dimensions = gutter_dimensions;
5584    let text_width = width - gutter_dimensions.width;
5585    let overscroll = size(em_width, px(0.));
5586
5587    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
5588    if editor.set_wrap_width(Some(editor_width), cx) {
5589        snapshot = editor.snapshot(cx);
5590    }
5591
5592    let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
5593    let height = scroll_height
5594        .max(line_height)
5595        .min(line_height * max_lines as f32);
5596
5597    Some(size(width, height))
5598}