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