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