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