element.rs

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