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        gutter_overshoot: Pixels,
1953        cx: &mut WindowContext,
1954    ) -> bool {
1955        let max_height = cmp::min(
1956            12. * line_height,
1957            cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
1958        );
1959        let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
1960            if editor.context_menu_visible() {
1961                editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
1962            } else {
1963                None
1964            }
1965        }) else {
1966            return false;
1967        };
1968
1969        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1970        let context_menu_size = context_menu.layout_as_root(available_space, cx);
1971
1972        let (x, y) = match position {
1973            crate::ContextMenuOrigin::EditorPoint(point) => {
1974                let cursor_row_layout = &line_layouts[(point.row() - start_row) as usize].line;
1975                let x = cursor_row_layout.x_for_index(point.column() as usize)
1976                    - scroll_pixel_position.x;
1977                let y = (point.row() + 1) as f32 * line_height - scroll_pixel_position.y;
1978                (x, y)
1979            }
1980            crate::ContextMenuOrigin::GutterIndicator(row) => {
1981                // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the indicator than just a plain first column of the
1982                // text field.
1983                let x = -gutter_overshoot;
1984                let y = (row + 1) as f32 * line_height - scroll_pixel_position.y;
1985                (x, y)
1986            }
1987        };
1988
1989        let mut list_origin = content_origin + point(x, y);
1990        let list_width = context_menu_size.width;
1991        let list_height = context_menu_size.height;
1992
1993        // Snap the right edge of the list to the right edge of the window if
1994        // its horizontal bounds overflow.
1995        if list_origin.x + list_width > cx.viewport_size().width {
1996            list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
1997        }
1998
1999        if list_origin.y + list_height > text_hitbox.lower_right().y {
2000            list_origin.y -= line_height + list_height;
2001        }
2002
2003        cx.defer_draw(context_menu, list_origin, 1);
2004        true
2005    }
2006
2007    fn layout_mouse_context_menu(&self, cx: &mut WindowContext) -> Option<AnyElement> {
2008        let mouse_context_menu = self.editor.read(cx).mouse_context_menu.as_ref()?;
2009        let mut element = deferred(
2010            anchored()
2011                .position(mouse_context_menu.position)
2012                .child(mouse_context_menu.context_menu.clone())
2013                .anchor(AnchorCorner::TopLeft)
2014                .snap_to_window(),
2015        )
2016        .with_priority(1)
2017        .into_any();
2018
2019        element.prepaint_as_root(gpui::Point::default(), AvailableSpace::min_size(), cx);
2020        Some(element)
2021    }
2022
2023    #[allow(clippy::too_many_arguments)]
2024    fn layout_hover_popovers(
2025        &self,
2026        snapshot: &EditorSnapshot,
2027        hitbox: &Hitbox,
2028        text_hitbox: &Hitbox,
2029        visible_display_row_range: Range<u32>,
2030        content_origin: gpui::Point<Pixels>,
2031        scroll_pixel_position: gpui::Point<Pixels>,
2032        line_layouts: &[LineWithInvisibles],
2033        line_height: Pixels,
2034        em_width: Pixels,
2035        cx: &mut WindowContext,
2036    ) {
2037        struct MeasuredHoverPopover {
2038            element: AnyElement,
2039            size: Size<Pixels>,
2040            horizontal_offset: Pixels,
2041        }
2042
2043        let max_size = size(
2044            (120. * em_width) // Default size
2045                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2046                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2047            (16. * line_height) // Default size
2048                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2049                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2050        );
2051
2052        let hover_popovers = self.editor.update(cx, |editor, cx| {
2053            editor.hover_state.render(
2054                &snapshot,
2055                &self.style,
2056                visible_display_row_range.clone(),
2057                max_size,
2058                editor.workspace.as_ref().map(|(w, _)| w.clone()),
2059                cx,
2060            )
2061        });
2062        let Some((position, hover_popovers)) = hover_popovers else {
2063            return;
2064        };
2065
2066        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2067
2068        // This is safe because we check on layout whether the required row is available
2069        let hovered_row_layout =
2070            &line_layouts[(position.row() - visible_display_row_range.start) as usize].line;
2071
2072        // Compute Hovered Point
2073        let x =
2074            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
2075        let y = position.row() as f32 * line_height - scroll_pixel_position.y;
2076        let hovered_point = content_origin + point(x, y);
2077
2078        let mut overall_height = Pixels::ZERO;
2079        let mut measured_hover_popovers = Vec::new();
2080        for mut hover_popover in hover_popovers {
2081            let size = hover_popover.layout_as_root(available_space, cx);
2082            let horizontal_offset =
2083                (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
2084
2085            overall_height += HOVER_POPOVER_GAP + size.height;
2086
2087            measured_hover_popovers.push(MeasuredHoverPopover {
2088                element: hover_popover,
2089                size,
2090                horizontal_offset,
2091            });
2092        }
2093        overall_height += HOVER_POPOVER_GAP;
2094
2095        fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
2096            let mut occlusion = div()
2097                .size_full()
2098                .occlude()
2099                .on_mouse_move(|_, cx| cx.stop_propagation())
2100                .into_any_element();
2101            occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), cx);
2102            cx.defer_draw(occlusion, origin, 2);
2103        }
2104
2105        if hovered_point.y > overall_height {
2106            // There is enough space above. Render popovers above the hovered point
2107            let mut current_y = hovered_point.y;
2108            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2109                let size = popover.size;
2110                let popover_origin = point(
2111                    hovered_point.x + popover.horizontal_offset,
2112                    current_y - size.height,
2113                );
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 - HOVER_POPOVER_GAP);
2118                    draw_occluder(size.width, origin, cx);
2119                }
2120
2121                current_y = popover_origin.y - HOVER_POPOVER_GAP;
2122            }
2123        } else {
2124            // There is not enough space above. Render popovers below the hovered point
2125            let mut current_y = hovered_point.y + line_height;
2126            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2127                let size = popover.size;
2128                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
2129
2130                cx.defer_draw(popover.element, popover_origin, 2);
2131                if position != itertools::Position::Last {
2132                    let origin = point(popover_origin.x, popover_origin.y + size.height);
2133                    draw_occluder(size.width, origin, cx);
2134                }
2135
2136                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
2137            }
2138        }
2139    }
2140
2141    fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
2142        cx.paint_layer(layout.hitbox.bounds, |cx| {
2143            let scroll_top = layout.position_map.snapshot.scroll_position().y;
2144            let gutter_bg = cx.theme().colors().editor_gutter_background;
2145            cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
2146            cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
2147
2148            if let EditorMode::Full = layout.mode {
2149                let mut active_rows = layout.active_rows.iter().peekable();
2150                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
2151                    let mut end_row = *start_row;
2152                    while active_rows.peek().map_or(false, |r| {
2153                        *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
2154                    }) {
2155                        active_rows.next().unwrap();
2156                        end_row += 1;
2157                    }
2158
2159                    if !contains_non_empty_selection {
2160                        let origin = point(
2161                            layout.hitbox.origin.x,
2162                            layout.hitbox.origin.y
2163                                + (*start_row as f32 - scroll_top)
2164                                    * layout.position_map.line_height,
2165                        );
2166                        let size = size(
2167                            layout.hitbox.size.width,
2168                            layout.position_map.line_height * (end_row - start_row + 1) as f32,
2169                        );
2170                        let active_line_bg = cx.theme().colors().editor_active_line_background;
2171                        cx.paint_quad(fill(Bounds { origin, size }, active_line_bg));
2172                    }
2173                }
2174
2175                let mut paint_highlight =
2176                    |highlight_row_start: u32, highlight_row_end: u32, color| {
2177                        let origin = point(
2178                            layout.hitbox.origin.x,
2179                            layout.hitbox.origin.y
2180                                + (highlight_row_start as f32 - scroll_top)
2181                                    * layout.position_map.line_height,
2182                        );
2183                        let size = size(
2184                            layout.hitbox.size.width,
2185                            layout.position_map.line_height
2186                                * (highlight_row_end + 1 - highlight_row_start) as f32,
2187                        );
2188                        cx.paint_quad(fill(Bounds { origin, size }, color));
2189                    };
2190
2191                let mut last_row = None;
2192                let mut highlight_row_start = 0u32;
2193                let mut highlight_row_end = 0u32;
2194                for (&row, &color) in &layout.highlighted_rows {
2195                    let paint = last_row.map_or(false, |(last_row, last_color)| {
2196                        last_color != color || last_row + 1 < row
2197                    });
2198
2199                    if paint {
2200                        let paint_range_is_unfinished = highlight_row_end == 0;
2201                        if paint_range_is_unfinished {
2202                            highlight_row_end = row;
2203                            last_row = None;
2204                        }
2205                        paint_highlight(highlight_row_start, highlight_row_end, color);
2206                        highlight_row_start = 0;
2207                        highlight_row_end = 0;
2208                        if !paint_range_is_unfinished {
2209                            highlight_row_start = row;
2210                            last_row = Some((row, color));
2211                        }
2212                    } else {
2213                        if last_row.is_none() {
2214                            highlight_row_start = row;
2215                        } else {
2216                            highlight_row_end = row;
2217                        }
2218                        last_row = Some((row, color));
2219                    }
2220                }
2221                if let Some((row, hsla)) = last_row {
2222                    highlight_row_end = row;
2223                    paint_highlight(highlight_row_start, highlight_row_end, hsla);
2224                }
2225
2226                let scroll_left =
2227                    layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
2228
2229                for (wrap_position, active) in layout.wrap_guides.iter() {
2230                    let x = (layout.text_hitbox.origin.x
2231                        + *wrap_position
2232                        + layout.position_map.em_width / 2.)
2233                        - scroll_left;
2234
2235                    let show_scrollbars = layout
2236                        .scrollbar_layout
2237                        .as_ref()
2238                        .map_or(false, |scrollbar| scrollbar.visible);
2239                    if x < layout.text_hitbox.origin.x
2240                        || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
2241                    {
2242                        continue;
2243                    }
2244
2245                    let color = if *active {
2246                        cx.theme().colors().editor_active_wrap_guide
2247                    } else {
2248                        cx.theme().colors().editor_wrap_guide
2249                    };
2250                    cx.paint_quad(fill(
2251                        Bounds {
2252                            origin: point(x, layout.text_hitbox.origin.y),
2253                            size: size(px(1.), layout.text_hitbox.size.height),
2254                        },
2255                        color,
2256                    ));
2257                }
2258            }
2259        })
2260    }
2261
2262    fn paint_gutter(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2263        let line_height = layout.position_map.line_height;
2264
2265        let scroll_position = layout.position_map.snapshot.scroll_position();
2266        let scroll_top = scroll_position.y * line_height;
2267
2268        cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
2269
2270        let show_git_gutter = matches!(
2271            ProjectSettings::get_global(cx).git.git_gutter,
2272            Some(GitGutterSetting::TrackedFiles)
2273        );
2274
2275        if show_git_gutter {
2276            Self::paint_diff_hunks(layout, cx);
2277        }
2278
2279        if layout.blamed_display_rows.is_some() {
2280            self.paint_blamed_display_rows(layout, cx);
2281        }
2282
2283        for (ix, line) in layout.line_numbers.iter().enumerate() {
2284            if let Some(line) = line {
2285                let line_origin = layout.gutter_hitbox.origin
2286                    + point(
2287                        layout.gutter_hitbox.size.width
2288                            - line.width
2289                            - layout.gutter_dimensions.right_padding,
2290                        ix as f32 * line_height - (scroll_top % line_height),
2291                    );
2292
2293                line.paint(line_origin, line_height, cx).log_err();
2294            }
2295        }
2296
2297        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2298            cx.with_element_namespace("gutter_fold_indicators", |cx| {
2299                for fold_indicator in layout.fold_indicators.iter_mut().flatten() {
2300                    fold_indicator.paint(cx);
2301                }
2302            });
2303
2304            if let Some(indicator) = layout.code_actions_indicator.as_mut() {
2305                indicator.paint(cx);
2306            }
2307        })
2308    }
2309
2310    fn paint_diff_hunks(layout: &EditorLayout, cx: &mut WindowContext) {
2311        if layout.display_hunks.is_empty() {
2312            return;
2313        }
2314
2315        let line_height = layout.position_map.line_height;
2316
2317        let scroll_position = layout.position_map.snapshot.scroll_position();
2318        let scroll_top = scroll_position.y * line_height;
2319
2320        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2321            for hunk in &layout.display_hunks {
2322                let (display_row_range, status) = match hunk {
2323                    //TODO: This rendering is entirely a horrible hack
2324                    &DisplayDiffHunk::Folded { display_row: row } => {
2325                        let start_y = row as f32 * line_height - scroll_top;
2326                        let end_y = start_y + line_height;
2327
2328                        let width = 0.275 * line_height;
2329                        let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2330                        let highlight_size = size(width * 2., end_y - start_y);
2331                        let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2332                        cx.paint_quad(quad(
2333                            highlight_bounds,
2334                            Corners::all(1. * line_height),
2335                            cx.theme().status().modified,
2336                            Edges::default(),
2337                            transparent_black(),
2338                        ));
2339
2340                        continue;
2341                    }
2342
2343                    DisplayDiffHunk::Unfolded {
2344                        display_row_range,
2345                        status,
2346                    } => (display_row_range, status),
2347                };
2348
2349                let color = match status {
2350                    DiffHunkStatus::Added => cx.theme().status().created,
2351                    DiffHunkStatus::Modified => cx.theme().status().modified,
2352
2353                    //TODO: This rendering is entirely a horrible hack
2354                    DiffHunkStatus::Removed => {
2355                        let row = display_row_range.start;
2356
2357                        let offset = line_height / 2.;
2358                        let start_y = row as f32 * line_height - offset - scroll_top;
2359                        let end_y = start_y + line_height;
2360
2361                        let width = 0.275 * line_height;
2362                        let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2363                        let highlight_size = size(width * 2., end_y - start_y);
2364                        let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2365                        cx.paint_quad(quad(
2366                            highlight_bounds,
2367                            Corners::all(1. * line_height),
2368                            cx.theme().status().deleted,
2369                            Edges::default(),
2370                            transparent_black(),
2371                        ));
2372
2373                        continue;
2374                    }
2375                };
2376
2377                let start_row = display_row_range.start;
2378                let end_row = display_row_range.end;
2379                // If we're in a multibuffer, row range span might include an
2380                // excerpt header, so if we were to draw the marker straight away,
2381                // the hunk might include the rows of that header.
2382                // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
2383                // Instead, we simply check whether the range we're dealing with includes
2384                // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
2385                let end_row_in_current_excerpt = layout
2386                    .position_map
2387                    .snapshot
2388                    .blocks_in_range(start_row..end_row)
2389                    .find_map(|(start_row, block)| {
2390                        if matches!(block, TransformBlock::ExcerptHeader { .. }) {
2391                            Some(start_row)
2392                        } else {
2393                            None
2394                        }
2395                    })
2396                    .unwrap_or(end_row);
2397
2398                let start_y = start_row as f32 * line_height - scroll_top;
2399                let end_y = end_row_in_current_excerpt as f32 * line_height - scroll_top;
2400
2401                let width = 0.275 * line_height;
2402                let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2403                let highlight_size = size(width * 2., end_y - start_y);
2404                let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2405                cx.paint_quad(quad(
2406                    highlight_bounds,
2407                    Corners::all(0.05 * line_height),
2408                    color,
2409                    Edges::default(),
2410                    transparent_black(),
2411                ));
2412            }
2413        })
2414    }
2415
2416    fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2417        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
2418            return;
2419        };
2420
2421        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2422            for mut blame_element in blamed_display_rows.into_iter() {
2423                blame_element.paint(cx);
2424            }
2425        })
2426    }
2427
2428    fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2429        cx.with_content_mask(
2430            Some(ContentMask {
2431                bounds: layout.text_hitbox.bounds,
2432            }),
2433            |cx| {
2434                let cursor_style = if self
2435                    .editor
2436                    .read(cx)
2437                    .hovered_link_state
2438                    .as_ref()
2439                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
2440                {
2441                    CursorStyle::PointingHand
2442                } else {
2443                    CursorStyle::IBeam
2444                };
2445                cx.set_cursor_style(cursor_style, &layout.text_hitbox);
2446
2447                cx.with_element_namespace("folds", |cx| self.paint_folds(layout, cx));
2448                let invisible_display_ranges = self.paint_highlights(layout, cx);
2449                self.paint_lines(&invisible_display_ranges, layout, cx);
2450                self.paint_redactions(layout, cx);
2451                self.paint_cursors(layout, cx);
2452                self.paint_inline_blame(layout, cx);
2453            },
2454        )
2455    }
2456
2457    fn paint_highlights(
2458        &mut self,
2459        layout: &mut EditorLayout,
2460        cx: &mut WindowContext,
2461    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
2462        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2463            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
2464            let line_end_overshoot = 0.15 * layout.position_map.line_height;
2465            for (range, color) in &layout.highlighted_ranges {
2466                self.paint_highlighted_range(
2467                    range.clone(),
2468                    *color,
2469                    Pixels::ZERO,
2470                    line_end_overshoot,
2471                    layout,
2472                    cx,
2473                );
2474            }
2475
2476            let corner_radius = 0.15 * layout.position_map.line_height;
2477
2478            for (player_color, selections) in &layout.selections {
2479                for selection in selections.into_iter() {
2480                    self.paint_highlighted_range(
2481                        selection.range.clone(),
2482                        player_color.selection,
2483                        corner_radius,
2484                        corner_radius * 2.,
2485                        layout,
2486                        cx,
2487                    );
2488
2489                    if selection.is_local && !selection.range.is_empty() {
2490                        invisible_display_ranges.push(selection.range.clone());
2491                    }
2492                }
2493            }
2494            invisible_display_ranges
2495        })
2496    }
2497
2498    fn paint_lines(
2499        &mut self,
2500        invisible_display_ranges: &[Range<DisplayPoint>],
2501        layout: &EditorLayout,
2502        cx: &mut WindowContext,
2503    ) {
2504        let whitespace_setting = self
2505            .editor
2506            .read(cx)
2507            .buffer
2508            .read(cx)
2509            .settings_at(0, cx)
2510            .show_whitespaces;
2511
2512        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
2513            let row = layout.visible_display_row_range.start + ix as u32;
2514            line_with_invisibles.draw(
2515                layout,
2516                row,
2517                layout.content_origin,
2518                whitespace_setting,
2519                invisible_display_ranges,
2520                cx,
2521            )
2522        }
2523    }
2524
2525    fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
2526        if layout.redacted_ranges.is_empty() {
2527            return;
2528        }
2529
2530        let line_end_overshoot = layout.line_end_overshoot();
2531
2532        // A softer than perfect black
2533        let redaction_color = gpui::rgb(0x0e1111);
2534
2535        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2536            for range in layout.redacted_ranges.iter() {
2537                self.paint_highlighted_range(
2538                    range.clone(),
2539                    redaction_color.into(),
2540                    Pixels::ZERO,
2541                    line_end_overshoot,
2542                    layout,
2543                    cx,
2544                );
2545            }
2546        });
2547    }
2548
2549    fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2550        for cursor in &mut layout.visible_cursors {
2551            cursor.paint(layout.content_origin, cx);
2552        }
2553    }
2554
2555    fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2556        let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
2557            return;
2558        };
2559
2560        let thumb_bounds = scrollbar_layout.thumb_bounds();
2561        if scrollbar_layout.visible {
2562            cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
2563                cx.paint_quad(quad(
2564                    scrollbar_layout.hitbox.bounds,
2565                    Corners::default(),
2566                    cx.theme().colors().scrollbar_track_background,
2567                    Edges {
2568                        top: Pixels::ZERO,
2569                        right: Pixels::ZERO,
2570                        bottom: Pixels::ZERO,
2571                        left: ScrollbarLayout::BORDER_WIDTH,
2572                    },
2573                    cx.theme().colors().scrollbar_track_border,
2574                ));
2575
2576                let fast_markers =
2577                    self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
2578                // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
2579                self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
2580
2581                let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
2582                for marker in markers.iter().chain(&fast_markers) {
2583                    let mut marker = marker.clone();
2584                    marker.bounds.origin += scrollbar_layout.hitbox.origin;
2585                    cx.paint_quad(marker);
2586                }
2587
2588                cx.paint_quad(quad(
2589                    thumb_bounds,
2590                    Corners::default(),
2591                    cx.theme().colors().scrollbar_thumb_background,
2592                    Edges {
2593                        top: Pixels::ZERO,
2594                        right: Pixels::ZERO,
2595                        bottom: Pixels::ZERO,
2596                        left: ScrollbarLayout::BORDER_WIDTH,
2597                    },
2598                    cx.theme().colors().scrollbar_thumb_border,
2599                ));
2600            });
2601        }
2602
2603        cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
2604
2605        let row_height = scrollbar_layout.row_height;
2606        let row_range = scrollbar_layout.visible_row_range.clone();
2607
2608        cx.on_mouse_event({
2609            let editor = self.editor.clone();
2610            let hitbox = scrollbar_layout.hitbox.clone();
2611            let mut mouse_position = cx.mouse_position();
2612            move |event: &MouseMoveEvent, phase, cx| {
2613                if phase == DispatchPhase::Capture {
2614                    return;
2615                }
2616
2617                editor.update(cx, |editor, cx| {
2618                    if event.pressed_button == Some(MouseButton::Left)
2619                        && editor.scroll_manager.is_dragging_scrollbar()
2620                    {
2621                        let y = mouse_position.y;
2622                        let new_y = event.position.y;
2623                        if (hitbox.top()..hitbox.bottom()).contains(&y) {
2624                            let mut position = editor.scroll_position(cx);
2625                            position.y += (new_y - y) / row_height;
2626                            if position.y < 0.0 {
2627                                position.y = 0.0;
2628                            }
2629                            editor.set_scroll_position(position, cx);
2630                        }
2631
2632                        cx.stop_propagation();
2633                    } else {
2634                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2635                        if hitbox.is_hovered(cx) {
2636                            editor.scroll_manager.show_scrollbar(cx);
2637                        }
2638                    }
2639                    mouse_position = event.position;
2640                })
2641            }
2642        });
2643
2644        if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
2645            cx.on_mouse_event({
2646                let editor = self.editor.clone();
2647                move |_: &MouseUpEvent, phase, cx| {
2648                    if phase == DispatchPhase::Capture {
2649                        return;
2650                    }
2651
2652                    editor.update(cx, |editor, cx| {
2653                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2654                        cx.stop_propagation();
2655                    });
2656                }
2657            });
2658        } else {
2659            cx.on_mouse_event({
2660                let editor = self.editor.clone();
2661                let hitbox = scrollbar_layout.hitbox.clone();
2662                move |event: &MouseDownEvent, phase, cx| {
2663                    if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
2664                        return;
2665                    }
2666
2667                    editor.update(cx, |editor, cx| {
2668                        editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
2669
2670                        let y = event.position.y;
2671                        if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
2672                            let center_row = ((y - hitbox.top()) / row_height).round() as u32;
2673                            let top_row = center_row
2674                                .saturating_sub((row_range.end - row_range.start) as u32 / 2);
2675                            let mut position = editor.scroll_position(cx);
2676                            position.y = top_row as f32;
2677                            editor.set_scroll_position(position, cx);
2678                        } else {
2679                            editor.scroll_manager.show_scrollbar(cx);
2680                        }
2681
2682                        cx.stop_propagation();
2683                    });
2684                }
2685            });
2686        }
2687    }
2688
2689    fn collect_fast_scrollbar_markers(
2690        &self,
2691        layout: &EditorLayout,
2692        scrollbar_layout: &ScrollbarLayout,
2693        cx: &mut WindowContext,
2694    ) -> Vec<PaintQuad> {
2695        const LIMIT: usize = 100;
2696        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
2697            return vec![];
2698        }
2699        let cursor_ranges = layout
2700            .cursors
2701            .iter()
2702            .map(|cursor| {
2703                let point = cursor
2704                    .0
2705                    .to_display_point(&layout.position_map.snapshot.display_snapshot);
2706                ColoredRange {
2707                    start: point.row(),
2708                    end: point.row(),
2709                    color: cursor.1,
2710                }
2711            })
2712            .collect_vec();
2713        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
2714    }
2715
2716    fn refresh_slow_scrollbar_markers(
2717        &self,
2718        layout: &EditorLayout,
2719        scrollbar_layout: &ScrollbarLayout,
2720        cx: &mut WindowContext,
2721    ) {
2722        self.editor.update(cx, |editor, cx| {
2723            if !editor.is_singleton(cx)
2724                || !editor
2725                    .scrollbar_marker_state
2726                    .should_refresh(scrollbar_layout.hitbox.size)
2727            {
2728                return;
2729            }
2730
2731            let scrollbar_layout = scrollbar_layout.clone();
2732            let background_highlights = editor.background_highlights.clone();
2733            let snapshot = layout.position_map.snapshot.clone();
2734            let theme = cx.theme().clone();
2735            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
2736            let max_row = layout.max_row;
2737
2738            editor.scrollbar_marker_state.dirty = false;
2739            editor.scrollbar_marker_state.pending_refresh =
2740                Some(cx.spawn(|editor, mut cx| async move {
2741                    let scrollbar_size = scrollbar_layout.hitbox.size;
2742                    let scrollbar_markers = cx
2743                        .background_executor()
2744                        .spawn(async move {
2745                            let mut marker_quads = Vec::new();
2746
2747                            if scrollbar_settings.git_diff {
2748                                let marker_row_ranges = snapshot
2749                                    .buffer_snapshot
2750                                    .git_diff_hunks_in_range(0..max_row)
2751                                    .map(|hunk| {
2752                                        let start_display_row =
2753                                            Point::new(hunk.associated_range.start, 0)
2754                                                .to_display_point(&snapshot.display_snapshot)
2755                                                .row();
2756                                        let mut end_display_row =
2757                                            Point::new(hunk.associated_range.end, 0)
2758                                                .to_display_point(&snapshot.display_snapshot)
2759                                                .row();
2760                                        if end_display_row != start_display_row {
2761                                            end_display_row -= 1;
2762                                        }
2763                                        let color = match hunk.status() {
2764                                            DiffHunkStatus::Added => theme.status().created,
2765                                            DiffHunkStatus::Modified => theme.status().modified,
2766                                            DiffHunkStatus::Removed => theme.status().deleted,
2767                                        };
2768                                        ColoredRange {
2769                                            start: start_display_row,
2770                                            end: end_display_row,
2771                                            color,
2772                                        }
2773                                    });
2774
2775                                marker_quads.extend(
2776                                    scrollbar_layout
2777                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
2778                                );
2779                            }
2780
2781                            for (background_highlight_id, (_, background_ranges)) in
2782                                background_highlights.iter()
2783                            {
2784                                let is_search_highlights = *background_highlight_id
2785                                    == TypeId::of::<BufferSearchHighlights>();
2786                                let is_symbol_occurrences = *background_highlight_id
2787                                    == TypeId::of::<DocumentHighlightRead>()
2788                                    || *background_highlight_id
2789                                        == TypeId::of::<DocumentHighlightWrite>();
2790                                if (is_search_highlights && scrollbar_settings.search_results)
2791                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
2792                                {
2793                                    let mut color = theme.status().info;
2794                                    if is_symbol_occurrences {
2795                                        color.fade_out(0.5);
2796                                    }
2797                                    let marker_row_ranges =
2798                                        background_ranges.into_iter().map(|range| {
2799                                            let display_start = range
2800                                                .start
2801                                                .to_display_point(&snapshot.display_snapshot);
2802                                            let display_end = range
2803                                                .end
2804                                                .to_display_point(&snapshot.display_snapshot);
2805                                            ColoredRange {
2806                                                start: display_start.row(),
2807                                                end: display_end.row(),
2808                                                color,
2809                                            }
2810                                        });
2811                                    marker_quads.extend(
2812                                        scrollbar_layout
2813                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
2814                                    );
2815                                }
2816                            }
2817
2818                            if scrollbar_settings.diagnostics {
2819                                let max_point =
2820                                    snapshot.display_snapshot.buffer_snapshot.max_point();
2821
2822                                let diagnostics = snapshot
2823                                    .buffer_snapshot
2824                                    .diagnostics_in_range::<_, Point>(
2825                                        Point::zero()..max_point,
2826                                        false,
2827                                    )
2828                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
2829                                    .sorted_by_key(|diagnostic| {
2830                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
2831                                    });
2832
2833                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
2834                                    let start_display = diagnostic
2835                                        .range
2836                                        .start
2837                                        .to_display_point(&snapshot.display_snapshot);
2838                                    let end_display = diagnostic
2839                                        .range
2840                                        .end
2841                                        .to_display_point(&snapshot.display_snapshot);
2842                                    let color = match diagnostic.diagnostic.severity {
2843                                        DiagnosticSeverity::ERROR => theme.status().error,
2844                                        DiagnosticSeverity::WARNING => theme.status().warning,
2845                                        DiagnosticSeverity::INFORMATION => theme.status().info,
2846                                        _ => theme.status().hint,
2847                                    };
2848                                    ColoredRange {
2849                                        start: start_display.row(),
2850                                        end: end_display.row(),
2851                                        color,
2852                                    }
2853                                });
2854                                marker_quads.extend(
2855                                    scrollbar_layout
2856                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
2857                                );
2858                            }
2859
2860                            Arc::from(marker_quads)
2861                        })
2862                        .await;
2863
2864                    editor.update(&mut cx, |editor, cx| {
2865                        editor.scrollbar_marker_state.markers = scrollbar_markers;
2866                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
2867                        editor.scrollbar_marker_state.pending_refresh = None;
2868                        cx.notify();
2869                    })?;
2870
2871                    Ok(())
2872                }));
2873        });
2874    }
2875
2876    #[allow(clippy::too_many_arguments)]
2877    fn paint_highlighted_range(
2878        &self,
2879        range: Range<DisplayPoint>,
2880        color: Hsla,
2881        corner_radius: Pixels,
2882        line_end_overshoot: Pixels,
2883        layout: &EditorLayout,
2884        cx: &mut WindowContext,
2885    ) {
2886        let start_row = layout.visible_display_row_range.start;
2887        let end_row = layout.visible_display_row_range.end;
2888        if range.start != range.end {
2889            let row_range = if range.end.column() == 0 {
2890                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2891            } else {
2892                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2893            };
2894
2895            let highlighted_range = HighlightedRange {
2896                color,
2897                line_height: layout.position_map.line_height,
2898                corner_radius,
2899                start_y: layout.content_origin.y
2900                    + row_range.start as f32 * layout.position_map.line_height
2901                    - layout.position_map.scroll_pixel_position.y,
2902                lines: row_range
2903                    .into_iter()
2904                    .map(|row| {
2905                        let line_layout =
2906                            &layout.position_map.line_layouts[(row - start_row) as usize].line;
2907                        HighlightedRangeLine {
2908                            start_x: if row == range.start.row() {
2909                                layout.content_origin.x
2910                                    + line_layout.x_for_index(range.start.column() as usize)
2911                                    - layout.position_map.scroll_pixel_position.x
2912                            } else {
2913                                layout.content_origin.x
2914                                    - layout.position_map.scroll_pixel_position.x
2915                            },
2916                            end_x: if row == range.end.row() {
2917                                layout.content_origin.x
2918                                    + line_layout.x_for_index(range.end.column() as usize)
2919                                    - layout.position_map.scroll_pixel_position.x
2920                            } else {
2921                                layout.content_origin.x + line_layout.width + line_end_overshoot
2922                                    - layout.position_map.scroll_pixel_position.x
2923                            },
2924                        }
2925                    })
2926                    .collect(),
2927            };
2928
2929            highlighted_range.paint(layout.text_hitbox.bounds, cx);
2930        }
2931    }
2932
2933    fn paint_folds(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2934        if layout.folds.is_empty() {
2935            return;
2936        }
2937
2938        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2939            let fold_corner_radius = 0.15 * layout.position_map.line_height;
2940            for mut fold in mem::take(&mut layout.folds) {
2941                fold.hover_element.paint(cx);
2942
2943                let hover_element = fold.hover_element.downcast_mut::<Stateful<Div>>().unwrap();
2944                let fold_background = if hover_element.interactivity().active.unwrap() {
2945                    cx.theme().colors().ghost_element_active
2946                } else if hover_element.interactivity().hovered.unwrap() {
2947                    cx.theme().colors().ghost_element_hover
2948                } else {
2949                    cx.theme().colors().ghost_element_background
2950                };
2951
2952                self.paint_highlighted_range(
2953                    fold.display_range.clone(),
2954                    fold_background,
2955                    fold_corner_radius,
2956                    fold_corner_radius * 2.,
2957                    layout,
2958                    cx,
2959                );
2960            }
2961        })
2962    }
2963
2964    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2965        if let Some(mut inline_blame) = layout.inline_blame.take() {
2966            cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2967                inline_blame.paint(cx);
2968            })
2969        }
2970    }
2971
2972    fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2973        for mut block in layout.blocks.drain(..) {
2974            block.element.paint(cx);
2975        }
2976    }
2977
2978    fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2979        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
2980            mouse_context_menu.paint(cx);
2981        }
2982    }
2983
2984    fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
2985        cx.on_mouse_event({
2986            let position_map = layout.position_map.clone();
2987            let editor = self.editor.clone();
2988            let hitbox = layout.hitbox.clone();
2989            let mut delta = ScrollDelta::default();
2990
2991            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
2992            // accidentally turn off their scrolling.
2993            let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
2994
2995            move |event: &ScrollWheelEvent, phase, cx| {
2996                if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
2997                    delta = delta.coalesce(event.delta);
2998                    editor.update(cx, |editor, cx| {
2999                        let position_map: &PositionMap = &position_map;
3000
3001                        let line_height = position_map.line_height;
3002                        let max_glyph_width = position_map.em_width;
3003                        let (delta, axis) = match delta {
3004                            gpui::ScrollDelta::Pixels(mut pixels) => {
3005                                //Trackpad
3006                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
3007                                (pixels, axis)
3008                            }
3009
3010                            gpui::ScrollDelta::Lines(lines) => {
3011                                //Not trackpad
3012                                let pixels =
3013                                    point(lines.x * max_glyph_width, lines.y * line_height);
3014                                (pixels, None)
3015                            }
3016                        };
3017
3018                        let scroll_position = position_map.snapshot.scroll_position();
3019                        let x = (scroll_position.x * max_glyph_width
3020                            - (delta.x * scroll_sensitivity))
3021                            / max_glyph_width;
3022                        let y = (scroll_position.y * line_height - (delta.y * scroll_sensitivity))
3023                            / line_height;
3024                        let scroll_position =
3025                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
3026                        editor.scroll(scroll_position, axis, cx);
3027                        cx.stop_propagation();
3028                    });
3029                }
3030            }
3031        });
3032    }
3033
3034    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3035        self.paint_scroll_wheel_listener(layout, cx);
3036
3037        cx.on_mouse_event({
3038            let position_map = layout.position_map.clone();
3039            let editor = self.editor.clone();
3040            let text_hitbox = layout.text_hitbox.clone();
3041            let gutter_hitbox = layout.gutter_hitbox.clone();
3042
3043            move |event: &MouseDownEvent, phase, cx| {
3044                if phase == DispatchPhase::Bubble {
3045                    match event.button {
3046                        MouseButton::Left => editor.update(cx, |editor, cx| {
3047                            Self::mouse_left_down(
3048                                editor,
3049                                event,
3050                                &position_map,
3051                                &text_hitbox,
3052                                &gutter_hitbox,
3053                                cx,
3054                            );
3055                        }),
3056                        MouseButton::Right => editor.update(cx, |editor, cx| {
3057                            Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
3058                        }),
3059                        MouseButton::Middle => editor.update(cx, |editor, cx| {
3060                            Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
3061                        }),
3062                        _ => {}
3063                    };
3064                }
3065            }
3066        });
3067
3068        cx.on_mouse_event({
3069            let editor = self.editor.clone();
3070            let position_map = layout.position_map.clone();
3071            let text_hitbox = layout.text_hitbox.clone();
3072
3073            move |event: &MouseUpEvent, phase, cx| {
3074                if phase == DispatchPhase::Bubble {
3075                    editor.update(cx, |editor, cx| {
3076                        Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
3077                    });
3078                }
3079            }
3080        });
3081        cx.on_mouse_event({
3082            let position_map = layout.position_map.clone();
3083            let editor = self.editor.clone();
3084            let text_hitbox = layout.text_hitbox.clone();
3085            let gutter_hitbox = layout.gutter_hitbox.clone();
3086
3087            move |event: &MouseMoveEvent, phase, cx| {
3088                if phase == DispatchPhase::Bubble {
3089                    editor.update(cx, |editor, cx| {
3090                        if event.pressed_button == Some(MouseButton::Left) {
3091                            Self::mouse_dragged(
3092                                editor,
3093                                event,
3094                                &position_map,
3095                                text_hitbox.bounds,
3096                                cx,
3097                            )
3098                        }
3099
3100                        Self::mouse_moved(
3101                            editor,
3102                            event,
3103                            &position_map,
3104                            &text_hitbox,
3105                            &gutter_hitbox,
3106                            cx,
3107                        )
3108                    });
3109                }
3110            }
3111        });
3112    }
3113
3114    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
3115        bounds.upper_right().x - self.style.scrollbar_width
3116    }
3117
3118    fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
3119        let style = &self.style;
3120        let font_size = style.text.font_size.to_pixels(cx.rem_size());
3121        let layout = cx
3122            .text_system()
3123            .shape_line(
3124                SharedString::from(" ".repeat(column)),
3125                font_size,
3126                &[TextRun {
3127                    len: column,
3128                    font: style.text.font(),
3129                    color: Hsla::default(),
3130                    background_color: None,
3131                    underline: None,
3132                    strikethrough: None,
3133                }],
3134            )
3135            .unwrap();
3136
3137        layout.width
3138    }
3139
3140    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
3141        let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
3142        self.column_pixels(digit_count, cx)
3143    }
3144}
3145
3146fn render_inline_blame_entry(
3147    blame: &gpui::Model<GitBlame>,
3148    blame_entry: BlameEntry,
3149    style: &EditorStyle,
3150    workspace: Option<WeakView<Workspace>>,
3151    cx: &mut WindowContext<'_>,
3152) -> AnyElement {
3153    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3154
3155    let author = blame_entry.author.as_deref().unwrap_or_default();
3156    let text = format!("{}, {}", author, relative_timestamp);
3157
3158    let details = blame.read(cx).details_for_entry(&blame_entry);
3159
3160    let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
3161
3162    h_flex()
3163        .id("inline-blame")
3164        .w_full()
3165        .font_family(style.text.font().family)
3166        .text_color(cx.theme().status().hint)
3167        .line_height(style.text.line_height)
3168        .child(Icon::new(IconName::FileGit).color(Color::Hint))
3169        .child(text)
3170        .gap_2()
3171        .hoverable_tooltip(move |_| tooltip.clone().into())
3172        .into_any()
3173}
3174
3175fn render_blame_entry(
3176    ix: usize,
3177    blame: &gpui::Model<GitBlame>,
3178    blame_entry: BlameEntry,
3179    style: &EditorStyle,
3180    last_used_color: &mut Option<(PlayerColor, Oid)>,
3181    editor: View<Editor>,
3182    cx: &mut WindowContext<'_>,
3183) -> AnyElement {
3184    let mut sha_color = cx
3185        .theme()
3186        .players()
3187        .color_for_participant(blame_entry.sha.into());
3188    // If the last color we used is the same as the one we get for this line, but
3189    // the commit SHAs are different, then we try again to get a different color.
3190    match *last_used_color {
3191        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3192            let index: u32 = blame_entry.sha.into();
3193            sha_color = cx.theme().players().color_for_participant(index + 1);
3194        }
3195        _ => {}
3196    };
3197    last_used_color.replace((sha_color, blame_entry.sha));
3198
3199    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3200
3201    let pretty_commit_id = format!("{}", blame_entry.sha);
3202    let short_commit_id = pretty_commit_id.chars().take(6).collect::<String>();
3203
3204    let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3205    let name = util::truncate_and_trailoff(author_name, 20);
3206
3207    let details = blame.read(cx).details_for_entry(&blame_entry);
3208
3209    let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3210
3211    let tooltip = cx.new_view(|_| {
3212        BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3213    });
3214
3215    h_flex()
3216        .w_full()
3217        .font_family(style.text.font().family)
3218        .line_height(style.text.line_height)
3219        .id(("blame", ix))
3220        .children([
3221            div()
3222                .text_color(sha_color.cursor)
3223                .child(short_commit_id)
3224                .mr_2(),
3225            div()
3226                .w_full()
3227                .h_flex()
3228                .justify_between()
3229                .text_color(cx.theme().status().hint)
3230                .child(name)
3231                .child(relative_timestamp),
3232        ])
3233        .on_mouse_down(MouseButton::Right, {
3234            let blame_entry = blame_entry.clone();
3235            move |event, cx| {
3236                deploy_blame_entry_context_menu(&blame_entry, editor.clone(), event.position, cx);
3237            }
3238        })
3239        .hover(|style| style.bg(cx.theme().colors().element_hover))
3240        .when_some(
3241            details.and_then(|details| details.permalink),
3242            |this, url| {
3243                let url = url.clone();
3244                this.cursor_pointer().on_click(move |_, cx| {
3245                    cx.stop_propagation();
3246                    cx.open_url(url.as_str())
3247                })
3248            },
3249        )
3250        .hoverable_tooltip(move |_| tooltip.clone().into())
3251        .into_any()
3252}
3253
3254fn deploy_blame_entry_context_menu(
3255    blame_entry: &BlameEntry,
3256    editor: View<Editor>,
3257    position: gpui::Point<Pixels>,
3258    cx: &mut WindowContext<'_>,
3259) {
3260    let context_menu = ContextMenu::build(cx, move |this, _| {
3261        let sha = format!("{}", blame_entry.sha);
3262        this.entry("Copy commit SHA", None, move |cx| {
3263            cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
3264        })
3265    });
3266
3267    editor.update(cx, move |editor, cx| {
3268        editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
3269        cx.notify();
3270    });
3271}
3272
3273#[derive(Debug)]
3274pub(crate) struct LineWithInvisibles {
3275    pub line: ShapedLine,
3276    invisibles: Vec<Invisible>,
3277}
3278
3279impl LineWithInvisibles {
3280    fn from_chunks<'a>(
3281        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
3282        text_style: &TextStyle,
3283        max_line_len: usize,
3284        max_line_count: usize,
3285        line_number_layouts: &[Option<ShapedLine>],
3286        editor_mode: EditorMode,
3287        cx: &WindowContext,
3288    ) -> Vec<Self> {
3289        let mut layouts = Vec::with_capacity(max_line_count);
3290        let mut line = String::new();
3291        let mut invisibles = Vec::new();
3292        let mut styles = Vec::new();
3293        let mut non_whitespace_added = false;
3294        let mut row = 0;
3295        let mut line_exceeded_max_len = false;
3296        let font_size = text_style.font_size.to_pixels(cx.rem_size());
3297
3298        for highlighted_chunk in chunks.chain([HighlightedChunk {
3299            chunk: "\n",
3300            style: None,
3301            is_tab: false,
3302        }]) {
3303            for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
3304                if ix > 0 {
3305                    let shaped_line = cx
3306                        .text_system()
3307                        .shape_line(line.clone().into(), font_size, &styles)
3308                        .unwrap();
3309                    layouts.push(Self {
3310                        line: shaped_line,
3311                        invisibles: std::mem::take(&mut invisibles),
3312                    });
3313
3314                    line.clear();
3315                    styles.clear();
3316                    row += 1;
3317                    line_exceeded_max_len = false;
3318                    non_whitespace_added = false;
3319                    if row == max_line_count {
3320                        return layouts;
3321                    }
3322                }
3323
3324                if !line_chunk.is_empty() && !line_exceeded_max_len {
3325                    let text_style = if let Some(style) = highlighted_chunk.style {
3326                        Cow::Owned(text_style.clone().highlight(style))
3327                    } else {
3328                        Cow::Borrowed(text_style)
3329                    };
3330
3331                    if line.len() + line_chunk.len() > max_line_len {
3332                        let mut chunk_len = max_line_len - line.len();
3333                        while !line_chunk.is_char_boundary(chunk_len) {
3334                            chunk_len -= 1;
3335                        }
3336                        line_chunk = &line_chunk[..chunk_len];
3337                        line_exceeded_max_len = true;
3338                    }
3339
3340                    styles.push(TextRun {
3341                        len: line_chunk.len(),
3342                        font: text_style.font(),
3343                        color: text_style.color,
3344                        background_color: text_style.background_color,
3345                        underline: text_style.underline,
3346                        strikethrough: text_style.strikethrough,
3347                    });
3348
3349                    if editor_mode == EditorMode::Full {
3350                        // Line wrap pads its contents with fake whitespaces,
3351                        // avoid printing them
3352                        let inside_wrapped_string = line_number_layouts
3353                            .get(row)
3354                            .and_then(|layout| layout.as_ref())
3355                            .is_none();
3356                        if highlighted_chunk.is_tab {
3357                            if non_whitespace_added || !inside_wrapped_string {
3358                                invisibles.push(Invisible::Tab {
3359                                    line_start_offset: line.len(),
3360                                });
3361                            }
3362                        } else {
3363                            invisibles.extend(
3364                                line_chunk
3365                                    .chars()
3366                                    .enumerate()
3367                                    .filter(|(_, line_char)| {
3368                                        let is_whitespace = line_char.is_whitespace();
3369                                        non_whitespace_added |= !is_whitespace;
3370                                        is_whitespace
3371                                            && (non_whitespace_added || !inside_wrapped_string)
3372                                    })
3373                                    .map(|(whitespace_index, _)| Invisible::Whitespace {
3374                                        line_offset: line.len() + whitespace_index,
3375                                    }),
3376                            )
3377                        }
3378                    }
3379
3380                    line.push_str(line_chunk);
3381                }
3382            }
3383        }
3384
3385        layouts
3386    }
3387
3388    fn draw(
3389        &self,
3390        layout: &EditorLayout,
3391        row: u32,
3392        content_origin: gpui::Point<Pixels>,
3393        whitespace_setting: ShowWhitespaceSetting,
3394        selection_ranges: &[Range<DisplayPoint>],
3395        cx: &mut WindowContext,
3396    ) {
3397        let line_height = layout.position_map.line_height;
3398        let line_y =
3399            line_height * (row as f32 - layout.position_map.scroll_pixel_position.y / line_height);
3400
3401        let line_origin =
3402            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
3403        self.line.paint(line_origin, line_height, cx).log_err();
3404
3405        self.draw_invisibles(
3406            &selection_ranges,
3407            layout,
3408            content_origin,
3409            line_y,
3410            row,
3411            line_height,
3412            whitespace_setting,
3413            cx,
3414        );
3415    }
3416
3417    #[allow(clippy::too_many_arguments)]
3418    fn draw_invisibles(
3419        &self,
3420        selection_ranges: &[Range<DisplayPoint>],
3421        layout: &EditorLayout,
3422        content_origin: gpui::Point<Pixels>,
3423        line_y: Pixels,
3424        row: u32,
3425        line_height: Pixels,
3426        whitespace_setting: ShowWhitespaceSetting,
3427        cx: &mut WindowContext,
3428    ) {
3429        let allowed_invisibles_regions = match whitespace_setting {
3430            ShowWhitespaceSetting::None => return,
3431            ShowWhitespaceSetting::Selection => Some(selection_ranges),
3432            ShowWhitespaceSetting::All => None,
3433        };
3434
3435        for invisible in &self.invisibles {
3436            let (&token_offset, invisible_symbol) = match invisible {
3437                Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
3438                Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
3439            };
3440
3441            let x_offset = self.line.x_for_index(token_offset);
3442            let invisible_offset =
3443                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
3444            let origin = content_origin
3445                + gpui::point(
3446                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
3447                    line_y,
3448                );
3449
3450            if let Some(allowed_regions) = allowed_invisibles_regions {
3451                let invisible_point = DisplayPoint::new(row, token_offset as u32);
3452                if !allowed_regions
3453                    .iter()
3454                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
3455                {
3456                    continue;
3457                }
3458            }
3459            invisible_symbol.paint(origin, line_height, cx).log_err();
3460        }
3461    }
3462}
3463
3464#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3465enum Invisible {
3466    Tab { line_start_offset: usize },
3467    Whitespace { line_offset: usize },
3468}
3469
3470impl Element for EditorElement {
3471    type RequestLayoutState = ();
3472    type PrepaintState = EditorLayout;
3473
3474    fn id(&self) -> Option<ElementId> {
3475        None
3476    }
3477
3478    fn request_layout(
3479        &mut self,
3480        _: Option<&GlobalElementId>,
3481        cx: &mut WindowContext,
3482    ) -> (gpui::LayoutId, ()) {
3483        self.editor.update(cx, |editor, cx| {
3484            editor.set_style(self.style.clone(), cx);
3485
3486            let layout_id = match editor.mode {
3487                EditorMode::SingleLine => {
3488                    let rem_size = cx.rem_size();
3489                    let mut style = Style::default();
3490                    style.size.width = relative(1.).into();
3491                    style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
3492                    cx.request_layout(&style, None)
3493                }
3494                EditorMode::AutoHeight { max_lines } => {
3495                    let editor_handle = cx.view().clone();
3496                    let max_line_number_width =
3497                        self.max_line_number_width(&editor.snapshot(cx), cx);
3498                    cx.request_measured_layout(Style::default(), move |known_dimensions, _, cx| {
3499                        editor_handle
3500                            .update(cx, |editor, cx| {
3501                                compute_auto_height_layout(
3502                                    editor,
3503                                    max_lines,
3504                                    max_line_number_width,
3505                                    known_dimensions,
3506                                    cx,
3507                                )
3508                            })
3509                            .unwrap_or_default()
3510                    })
3511                }
3512                EditorMode::Full => {
3513                    let mut style = Style::default();
3514                    style.size.width = relative(1.).into();
3515                    style.size.height = relative(1.).into();
3516                    cx.request_layout(&style, None)
3517                }
3518            };
3519
3520            (layout_id, ())
3521        })
3522    }
3523
3524    fn prepaint(
3525        &mut self,
3526        _: Option<&GlobalElementId>,
3527        bounds: Bounds<Pixels>,
3528        _: &mut Self::RequestLayoutState,
3529        cx: &mut WindowContext,
3530    ) -> Self::PrepaintState {
3531        let text_style = TextStyleRefinement {
3532            font_size: Some(self.style.text.font_size),
3533            line_height: Some(self.style.text.line_height),
3534            ..Default::default()
3535        };
3536        cx.set_view_id(self.editor.entity_id());
3537        cx.with_text_style(Some(text_style), |cx| {
3538            cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3539                let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
3540                let style = self.style.clone();
3541
3542                let font_id = cx.text_system().resolve_font(&style.text.font());
3543                let font_size = style.text.font_size.to_pixels(cx.rem_size());
3544                let line_height = style.text.line_height_in_pixels(cx.rem_size());
3545                let em_width = cx
3546                    .text_system()
3547                    .typographic_bounds(font_id, font_size, 'm')
3548                    .unwrap()
3549                    .size
3550                    .width;
3551                let em_advance = cx
3552                    .text_system()
3553                    .advance(font_id, font_size, 'm')
3554                    .unwrap()
3555                    .width;
3556
3557                let gutter_dimensions = snapshot.gutter_dimensions(
3558                    font_id,
3559                    font_size,
3560                    em_width,
3561                    self.max_line_number_width(&snapshot, cx),
3562                    cx,
3563                );
3564                let text_width = bounds.size.width - gutter_dimensions.width;
3565                let overscroll = size(em_width, px(0.));
3566
3567                snapshot = self.editor.update(cx, |editor, cx| {
3568                    editor.last_bounds = Some(bounds);
3569                    editor.gutter_width = gutter_dimensions.width;
3570                    editor.set_visible_line_count(bounds.size.height / line_height, cx);
3571
3572                    let editor_width =
3573                        text_width - gutter_dimensions.margin - overscroll.width - em_width;
3574                    let wrap_width = match editor.soft_wrap_mode(cx) {
3575                        SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
3576                        SoftWrap::EditorWidth => editor_width,
3577                        SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
3578                    };
3579
3580                    if editor.set_wrap_width(Some(wrap_width), cx) {
3581                        editor.snapshot(cx)
3582                    } else {
3583                        snapshot
3584                    }
3585                });
3586
3587                let wrap_guides = self
3588                    .editor
3589                    .read(cx)
3590                    .wrap_guides(cx)
3591                    .iter()
3592                    .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
3593                    .collect::<SmallVec<[_; 2]>>();
3594
3595                let hitbox = cx.insert_hitbox(bounds, false);
3596                let gutter_hitbox = cx.insert_hitbox(
3597                    Bounds {
3598                        origin: bounds.origin,
3599                        size: size(gutter_dimensions.width, bounds.size.height),
3600                    },
3601                    false,
3602                );
3603                let text_hitbox = cx.insert_hitbox(
3604                    Bounds {
3605                        origin: gutter_hitbox.upper_right(),
3606                        size: size(text_width, bounds.size.height),
3607                    },
3608                    false,
3609                );
3610                // Offset the content_bounds from the text_bounds by the gutter margin (which
3611                // is roughly half a character wide) to make hit testing work more like how we want.
3612                let content_origin =
3613                    text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
3614
3615                let mut autoscroll_containing_element = false;
3616                let mut autoscroll_horizontally = false;
3617                self.editor.update(cx, |editor, cx| {
3618                    autoscroll_containing_element =
3619                        editor.autoscroll_requested() || editor.has_pending_selection();
3620                    autoscroll_horizontally = editor.autoscroll_vertically(bounds, line_height, cx);
3621                    snapshot = editor.snapshot(cx);
3622                });
3623
3624                let mut scroll_position = snapshot.scroll_position();
3625                // The scroll position is a fractional point, the whole number of which represents
3626                // the top of the window in terms of display rows.
3627                let start_row = scroll_position.y as u32;
3628                let height_in_lines = bounds.size.height / line_height;
3629                let max_row = snapshot.max_point().row();
3630                let end_row = cmp::min(
3631                    (scroll_position.y + height_in_lines).ceil() as u32,
3632                    max_row + 1,
3633                );
3634
3635                let buffer_rows = snapshot
3636                    .buffer_rows(start_row)
3637                    .take((start_row..end_row).len());
3638
3639                let start_anchor = if start_row == 0 {
3640                    Anchor::min()
3641                } else {
3642                    snapshot.buffer_snapshot.anchor_before(
3643                        DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
3644                    )
3645                };
3646                let end_anchor = if end_row > max_row {
3647                    Anchor::max()
3648                } else {
3649                    snapshot.buffer_snapshot.anchor_before(
3650                        DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
3651                    )
3652                };
3653
3654                let highlighted_rows = self
3655                    .editor
3656                    .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
3657                let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
3658                    start_anchor..end_anchor,
3659                    &snapshot.display_snapshot,
3660                    cx.theme().colors(),
3661                );
3662
3663                let redacted_ranges = self.editor.read(cx).redacted_ranges(
3664                    start_anchor..end_anchor,
3665                    &snapshot.display_snapshot,
3666                    cx,
3667                );
3668
3669                let (selections, active_rows, newest_selection_head) = self.layout_selections(
3670                    start_anchor,
3671                    end_anchor,
3672                    &snapshot,
3673                    start_row,
3674                    end_row,
3675                    cx,
3676                );
3677
3678                let (line_numbers, fold_statuses) = self.layout_line_numbers(
3679                    start_row..end_row,
3680                    buffer_rows.clone(),
3681                    &active_rows,
3682                    newest_selection_head,
3683                    &snapshot,
3684                    cx,
3685                );
3686
3687                let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
3688
3689                let mut max_visible_line_width = Pixels::ZERO;
3690                let line_layouts =
3691                    self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
3692                for line_with_invisibles in &line_layouts {
3693                    if line_with_invisibles.line.width > max_visible_line_width {
3694                        max_visible_line_width = line_with_invisibles.line.width;
3695                    }
3696                }
3697
3698                let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
3699                    .unwrap()
3700                    .width;
3701                let mut scroll_width =
3702                    longest_line_width.max(max_visible_line_width) + overscroll.width;
3703
3704                let mut blocks = cx.with_element_namespace("blocks", |cx| {
3705                    self.build_blocks(
3706                        start_row..end_row,
3707                        &snapshot,
3708                        &hitbox,
3709                        &text_hitbox,
3710                        &mut scroll_width,
3711                        &gutter_dimensions,
3712                        em_width,
3713                        gutter_dimensions.width + gutter_dimensions.margin,
3714                        line_height,
3715                        &line_layouts,
3716                        cx,
3717                    )
3718                });
3719
3720                let scroll_pixel_position = point(
3721                    scroll_position.x * em_width,
3722                    scroll_position.y * line_height,
3723                );
3724
3725                let mut inline_blame = None;
3726                if let Some(newest_selection_head) = newest_selection_head {
3727                    let display_row = newest_selection_head.row();
3728                    if (start_row..end_row).contains(&display_row) {
3729                        let line_layout = &line_layouts[(display_row - start_row) as usize];
3730                        inline_blame = self.layout_inline_blame(
3731                            display_row,
3732                            &snapshot.display_snapshot,
3733                            line_layout,
3734                            em_width,
3735                            content_origin,
3736                            scroll_pixel_position,
3737                            line_height,
3738                            cx,
3739                        );
3740                    }
3741                }
3742
3743                let blamed_display_rows = self.layout_blame_entries(
3744                    buffer_rows,
3745                    em_width,
3746                    scroll_position,
3747                    line_height,
3748                    &gutter_hitbox,
3749                    gutter_dimensions.git_blame_entries_width,
3750                    cx,
3751                );
3752
3753                let scroll_max = point(
3754                    ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
3755                    max_row as f32,
3756                );
3757
3758                self.editor.update(cx, |editor, cx| {
3759                    let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3760
3761                    let autoscrolled = if autoscroll_horizontally {
3762                        editor.autoscroll_horizontally(
3763                            start_row,
3764                            text_hitbox.size.width,
3765                            scroll_width,
3766                            em_width,
3767                            &line_layouts,
3768                            cx,
3769                        )
3770                    } else {
3771                        false
3772                    };
3773
3774                    if clamped || autoscrolled {
3775                        snapshot = editor.snapshot(cx);
3776                        scroll_position = snapshot.scroll_position();
3777                    }
3778                });
3779
3780                cx.with_element_namespace("blocks", |cx| {
3781                    self.layout_blocks(
3782                        &mut blocks,
3783                        &hitbox,
3784                        line_height,
3785                        scroll_pixel_position,
3786                        cx,
3787                    );
3788                });
3789
3790                let cursors = self.collect_cursors(&snapshot, cx);
3791
3792                let (visible_cursors, non_visible_cursors) = self.layout_visible_cursors(
3793                    &snapshot,
3794                    &selections,
3795                    start_row..end_row,
3796                    &line_layouts,
3797                    &text_hitbox,
3798                    content_origin,
3799                    scroll_position,
3800                    scroll_pixel_position,
3801                    line_height,
3802                    em_width,
3803                    autoscroll_containing_element,
3804                    cx,
3805                );
3806
3807                let scrollbar_layout = self.layout_scrollbar(
3808                    &snapshot,
3809                    bounds,
3810                    scroll_position,
3811                    height_in_lines,
3812                    non_visible_cursors,
3813                    cx,
3814                );
3815
3816                let folds = cx.with_element_namespace("folds", |cx| {
3817                    self.layout_folds(
3818                        &snapshot,
3819                        content_origin,
3820                        start_anchor..end_anchor,
3821                        start_row..end_row,
3822                        scroll_pixel_position,
3823                        line_height,
3824                        &line_layouts,
3825                        cx,
3826                    )
3827                });
3828
3829                let gutter_settings = EditorSettings::get_global(cx).gutter;
3830
3831                let mut context_menu_visible = false;
3832                let mut code_actions_indicator = None;
3833                if let Some(newest_selection_head) = newest_selection_head {
3834                    if (start_row..end_row).contains(&newest_selection_head.row()) {
3835                        context_menu_visible = self.layout_context_menu(
3836                            line_height,
3837                            &hitbox,
3838                            &text_hitbox,
3839                            content_origin,
3840                            start_row,
3841                            scroll_pixel_position,
3842                            &line_layouts,
3843                            newest_selection_head,
3844                            gutter_dimensions.width - gutter_dimensions.left_padding,
3845                            cx,
3846                        );
3847                        if gutter_settings.code_actions {
3848                            code_actions_indicator = self.layout_code_actions_indicator(
3849                                line_height,
3850                                newest_selection_head,
3851                                scroll_pixel_position,
3852                                &gutter_dimensions,
3853                                &gutter_hitbox,
3854                                cx,
3855                            );
3856                        }
3857                    }
3858                }
3859
3860                if !context_menu_visible && !cx.has_active_drag() {
3861                    self.layout_hover_popovers(
3862                        &snapshot,
3863                        &hitbox,
3864                        &text_hitbox,
3865                        start_row..end_row,
3866                        content_origin,
3867                        scroll_pixel_position,
3868                        &line_layouts,
3869                        line_height,
3870                        em_width,
3871                        cx,
3872                    );
3873                }
3874
3875                let mouse_context_menu = self.layout_mouse_context_menu(cx);
3876
3877                let fold_indicators = if gutter_settings.folds {
3878                    cx.with_element_namespace("gutter_fold_indicators", |cx| {
3879                        self.layout_gutter_fold_indicators(
3880                            fold_statuses,
3881                            line_height,
3882                            &gutter_dimensions,
3883                            gutter_settings,
3884                            scroll_pixel_position,
3885                            &gutter_hitbox,
3886                            cx,
3887                        )
3888                    })
3889                } else {
3890                    Vec::new()
3891                };
3892
3893                let invisible_symbol_font_size = font_size / 2.;
3894                let tab_invisible = cx
3895                    .text_system()
3896                    .shape_line(
3897                        "".into(),
3898                        invisible_symbol_font_size,
3899                        &[TextRun {
3900                            len: "".len(),
3901                            font: self.style.text.font(),
3902                            color: cx.theme().colors().editor_invisible,
3903                            background_color: None,
3904                            underline: None,
3905                            strikethrough: None,
3906                        }],
3907                    )
3908                    .unwrap();
3909                let space_invisible = cx
3910                    .text_system()
3911                    .shape_line(
3912                        "".into(),
3913                        invisible_symbol_font_size,
3914                        &[TextRun {
3915                            len: "".len(),
3916                            font: self.style.text.font(),
3917                            color: cx.theme().colors().editor_invisible,
3918                            background_color: None,
3919                            underline: None,
3920                            strikethrough: None,
3921                        }],
3922                    )
3923                    .unwrap();
3924
3925                EditorLayout {
3926                    mode: snapshot.mode,
3927                    position_map: Arc::new(PositionMap {
3928                        size: bounds.size,
3929                        scroll_pixel_position,
3930                        scroll_max,
3931                        line_layouts,
3932                        line_height,
3933                        em_width,
3934                        em_advance,
3935                        snapshot,
3936                    }),
3937                    visible_display_row_range: start_row..end_row,
3938                    wrap_guides,
3939                    hitbox,
3940                    text_hitbox,
3941                    gutter_hitbox,
3942                    gutter_dimensions,
3943                    content_origin,
3944                    scrollbar_layout,
3945                    max_row,
3946                    active_rows,
3947                    highlighted_rows,
3948                    highlighted_ranges,
3949                    redacted_ranges,
3950                    line_numbers,
3951                    display_hunks,
3952                    blamed_display_rows,
3953                    inline_blame,
3954                    folds,
3955                    blocks,
3956                    cursors,
3957                    visible_cursors,
3958                    selections,
3959                    mouse_context_menu,
3960                    code_actions_indicator,
3961                    fold_indicators,
3962                    tab_invisible,
3963                    space_invisible,
3964                }
3965            })
3966        })
3967    }
3968
3969    fn paint(
3970        &mut self,
3971        _: Option<&GlobalElementId>,
3972        bounds: Bounds<gpui::Pixels>,
3973        _: &mut Self::RequestLayoutState,
3974        layout: &mut Self::PrepaintState,
3975        cx: &mut WindowContext,
3976    ) {
3977        let focus_handle = self.editor.focus_handle(cx);
3978        let key_context = self.editor.read(cx).key_context(cx);
3979        cx.set_focus_handle(&focus_handle);
3980        cx.set_key_context(key_context);
3981        cx.handle_input(
3982            &focus_handle,
3983            ElementInputHandler::new(bounds, self.editor.clone()),
3984        );
3985        self.register_actions(cx);
3986        self.register_key_listeners(cx, layout);
3987
3988        let text_style = TextStyleRefinement {
3989            font_size: Some(self.style.text.font_size),
3990            line_height: Some(self.style.text.line_height),
3991            ..Default::default()
3992        };
3993        cx.with_text_style(Some(text_style), |cx| {
3994            cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3995                self.paint_mouse_listeners(layout, cx);
3996
3997                self.paint_background(layout, cx);
3998                if layout.gutter_hitbox.size.width > Pixels::ZERO {
3999                    self.paint_gutter(layout, cx);
4000                }
4001                self.paint_text(layout, cx);
4002
4003                if !layout.blocks.is_empty() {
4004                    cx.with_element_namespace("blocks", |cx| {
4005                        self.paint_blocks(layout, cx);
4006                    });
4007                }
4008
4009                self.paint_scrollbar(layout, cx);
4010                self.paint_mouse_context_menu(layout, cx);
4011            });
4012        })
4013    }
4014}
4015
4016impl IntoElement for EditorElement {
4017    type Element = Self;
4018
4019    fn into_element(self) -> Self::Element {
4020        self
4021    }
4022}
4023
4024type BufferRow = u32;
4025
4026pub struct EditorLayout {
4027    position_map: Arc<PositionMap>,
4028    hitbox: Hitbox,
4029    text_hitbox: Hitbox,
4030    gutter_hitbox: Hitbox,
4031    gutter_dimensions: GutterDimensions,
4032    content_origin: gpui::Point<Pixels>,
4033    scrollbar_layout: Option<ScrollbarLayout>,
4034    mode: EditorMode,
4035    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
4036    visible_display_row_range: Range<u32>,
4037    active_rows: BTreeMap<u32, bool>,
4038    highlighted_rows: BTreeMap<u32, Hsla>,
4039    line_numbers: Vec<Option<ShapedLine>>,
4040    display_hunks: Vec<DisplayDiffHunk>,
4041    blamed_display_rows: Option<Vec<AnyElement>>,
4042    inline_blame: Option<AnyElement>,
4043    folds: Vec<FoldLayout>,
4044    blocks: Vec<BlockLayout>,
4045    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
4046    redacted_ranges: Vec<Range<DisplayPoint>>,
4047    cursors: Vec<(Anchor, Hsla)>,
4048    visible_cursors: Vec<CursorLayout>,
4049    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
4050    max_row: u32,
4051    code_actions_indicator: Option<AnyElement>,
4052    fold_indicators: Vec<Option<AnyElement>>,
4053    mouse_context_menu: Option<AnyElement>,
4054    tab_invisible: ShapedLine,
4055    space_invisible: ShapedLine,
4056}
4057
4058impl EditorLayout {
4059    fn line_end_overshoot(&self) -> Pixels {
4060        0.15 * self.position_map.line_height
4061    }
4062}
4063
4064struct ColoredRange<T> {
4065    start: T,
4066    end: T,
4067    color: Hsla,
4068}
4069
4070#[derive(Clone)]
4071struct ScrollbarLayout {
4072    hitbox: Hitbox,
4073    visible_row_range: Range<f32>,
4074    visible: bool,
4075    row_height: Pixels,
4076    thumb_height: Pixels,
4077}
4078
4079impl ScrollbarLayout {
4080    const BORDER_WIDTH: Pixels = px(1.0);
4081    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
4082    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
4083    const MIN_THUMB_HEIGHT: Pixels = px(20.0);
4084
4085    fn thumb_bounds(&self) -> Bounds<Pixels> {
4086        let thumb_top = self.y_for_row(self.visible_row_range.start);
4087        let thumb_bottom = thumb_top + self.thumb_height;
4088        Bounds::from_corners(
4089            point(self.hitbox.left(), thumb_top),
4090            point(self.hitbox.right(), thumb_bottom),
4091        )
4092    }
4093
4094    fn y_for_row(&self, row: f32) -> Pixels {
4095        self.hitbox.top() + row * self.row_height
4096    }
4097
4098    fn marker_quads_for_ranges(
4099        &self,
4100        row_ranges: impl IntoIterator<Item = ColoredRange<u32>>,
4101        column: Option<usize>,
4102    ) -> Vec<PaintQuad> {
4103        struct MinMax {
4104            min: Pixels,
4105            max: Pixels,
4106        }
4107        let (x_range, height_limit) = if let Some(column) = column {
4108            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
4109            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
4110            let end = start + column_width;
4111            (
4112                Range { start, end },
4113                MinMax {
4114                    min: Self::MIN_MARKER_HEIGHT,
4115                    max: px(f32::MAX),
4116                },
4117            )
4118        } else {
4119            (
4120                Range {
4121                    start: Self::BORDER_WIDTH,
4122                    end: self.hitbox.size.width,
4123                },
4124                MinMax {
4125                    min: Self::LINE_MARKER_HEIGHT,
4126                    max: Self::LINE_MARKER_HEIGHT,
4127                },
4128            )
4129        };
4130
4131        let row_to_y = |row: u32| row as f32 * self.row_height;
4132        let mut pixel_ranges = row_ranges
4133            .into_iter()
4134            .map(|range| {
4135                let start_y = row_to_y(range.start);
4136                let end_y = row_to_y(range.end)
4137                    + self.row_height.max(height_limit.min).min(height_limit.max);
4138                ColoredRange {
4139                    start: start_y,
4140                    end: end_y,
4141                    color: range.color,
4142                }
4143            })
4144            .peekable();
4145
4146        let mut quads = Vec::new();
4147        while let Some(mut pixel_range) = pixel_ranges.next() {
4148            while let Some(next_pixel_range) = pixel_ranges.peek() {
4149                if pixel_range.end >= next_pixel_range.start - px(1.0)
4150                    && pixel_range.color == next_pixel_range.color
4151                {
4152                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
4153                    pixel_ranges.next();
4154                } else {
4155                    break;
4156                }
4157            }
4158
4159            let bounds = Bounds::from_corners(
4160                point(x_range.start, pixel_range.start),
4161                point(x_range.end, pixel_range.end),
4162            );
4163            quads.push(quad(
4164                bounds,
4165                Corners::default(),
4166                pixel_range.color,
4167                Edges::default(),
4168                Hsla::transparent_black(),
4169            ));
4170        }
4171
4172        quads
4173    }
4174}
4175
4176struct FoldLayout {
4177    display_range: Range<DisplayPoint>,
4178    hover_element: AnyElement,
4179}
4180
4181struct PositionMap {
4182    size: Size<Pixels>,
4183    line_height: Pixels,
4184    scroll_pixel_position: gpui::Point<Pixels>,
4185    scroll_max: gpui::Point<f32>,
4186    em_width: Pixels,
4187    em_advance: Pixels,
4188    line_layouts: Vec<LineWithInvisibles>,
4189    snapshot: EditorSnapshot,
4190}
4191
4192#[derive(Debug, Copy, Clone)]
4193pub struct PointForPosition {
4194    pub previous_valid: DisplayPoint,
4195    pub next_valid: DisplayPoint,
4196    pub exact_unclipped: DisplayPoint,
4197    pub column_overshoot_after_line_end: u32,
4198}
4199
4200impl PointForPosition {
4201    pub fn as_valid(&self) -> Option<DisplayPoint> {
4202        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
4203            Some(self.previous_valid)
4204        } else {
4205            None
4206        }
4207    }
4208}
4209
4210impl PositionMap {
4211    fn point_for_position(
4212        &self,
4213        text_bounds: Bounds<Pixels>,
4214        position: gpui::Point<Pixels>,
4215    ) -> PointForPosition {
4216        let scroll_position = self.snapshot.scroll_position();
4217        let position = position - text_bounds.origin;
4218        let y = position.y.max(px(0.)).min(self.size.height);
4219        let x = position.x + (scroll_position.x * self.em_width);
4220        let row = ((y / self.line_height) + scroll_position.y) as u32;
4221
4222        let (column, x_overshoot_after_line_end) = if let Some(line) = self
4223            .line_layouts
4224            .get(row as usize - scroll_position.y as usize)
4225            .map(|LineWithInvisibles { line, .. }| line)
4226        {
4227            if let Some(ix) = line.index_for_x(x) {
4228                (ix as u32, px(0.))
4229            } else {
4230                (line.len as u32, px(0.).max(x - line.width))
4231            }
4232        } else {
4233            (0, x)
4234        };
4235
4236        let mut exact_unclipped = DisplayPoint::new(row, column);
4237        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
4238        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
4239
4240        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
4241        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
4242        PointForPosition {
4243            previous_valid,
4244            next_valid,
4245            exact_unclipped,
4246            column_overshoot_after_line_end,
4247        }
4248    }
4249}
4250
4251struct BlockLayout {
4252    row: u32,
4253    element: AnyElement,
4254    available_space: Size<AvailableSpace>,
4255    style: BlockStyle,
4256}
4257
4258fn layout_line(
4259    row: u32,
4260    snapshot: &EditorSnapshot,
4261    style: &EditorStyle,
4262    cx: &WindowContext,
4263) -> Result<ShapedLine> {
4264    let mut line = snapshot.line(row);
4265
4266    if line.len() > MAX_LINE_LEN {
4267        let mut len = MAX_LINE_LEN;
4268        while !line.is_char_boundary(len) {
4269            len -= 1;
4270        }
4271
4272        line.truncate(len);
4273    }
4274
4275    cx.text_system().shape_line(
4276        line.into(),
4277        style.text.font_size.to_pixels(cx.rem_size()),
4278        &[TextRun {
4279            len: snapshot.line_len(row) as usize,
4280            font: style.text.font(),
4281            color: Hsla::default(),
4282            background_color: None,
4283            underline: None,
4284            strikethrough: None,
4285        }],
4286    )
4287}
4288
4289pub struct CursorLayout {
4290    origin: gpui::Point<Pixels>,
4291    block_width: Pixels,
4292    line_height: Pixels,
4293    color: Hsla,
4294    shape: CursorShape,
4295    block_text: Option<ShapedLine>,
4296    cursor_name: Option<AnyElement>,
4297}
4298
4299#[derive(Debug)]
4300pub struct CursorName {
4301    string: SharedString,
4302    color: Hsla,
4303    is_top_row: bool,
4304}
4305
4306impl CursorLayout {
4307    pub fn new(
4308        origin: gpui::Point<Pixels>,
4309        block_width: Pixels,
4310        line_height: Pixels,
4311        color: Hsla,
4312        shape: CursorShape,
4313        block_text: Option<ShapedLine>,
4314    ) -> CursorLayout {
4315        CursorLayout {
4316            origin,
4317            block_width,
4318            line_height,
4319            color,
4320            shape,
4321            block_text,
4322            cursor_name: None,
4323        }
4324    }
4325
4326    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4327        Bounds {
4328            origin: self.origin + origin,
4329            size: size(self.block_width, self.line_height),
4330        }
4331    }
4332
4333    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4334        match self.shape {
4335            CursorShape::Bar => Bounds {
4336                origin: self.origin + origin,
4337                size: size(px(2.0), self.line_height),
4338            },
4339            CursorShape::Block | CursorShape::Hollow => Bounds {
4340                origin: self.origin + origin,
4341                size: size(self.block_width, self.line_height),
4342            },
4343            CursorShape::Underscore => Bounds {
4344                origin: self.origin
4345                    + origin
4346                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
4347                size: size(self.block_width, px(2.0)),
4348            },
4349        }
4350    }
4351
4352    pub fn layout(
4353        &mut self,
4354        origin: gpui::Point<Pixels>,
4355        cursor_name: Option<CursorName>,
4356        cx: &mut WindowContext,
4357    ) {
4358        if let Some(cursor_name) = cursor_name {
4359            let bounds = self.bounds(origin);
4360            let text_size = self.line_height / 1.5;
4361
4362            let name_origin = if cursor_name.is_top_row {
4363                point(bounds.right() - px(1.), bounds.top())
4364            } else {
4365                point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
4366            };
4367            let mut name_element = div()
4368                .bg(self.color)
4369                .text_size(text_size)
4370                .px_0p5()
4371                .line_height(text_size + px(2.))
4372                .text_color(cursor_name.color)
4373                .child(cursor_name.string.clone())
4374                .into_any_element();
4375
4376            name_element.prepaint_as_root(
4377                name_origin,
4378                size(AvailableSpace::MinContent, AvailableSpace::MinContent),
4379                cx,
4380            );
4381
4382            self.cursor_name = Some(name_element);
4383        }
4384    }
4385
4386    pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
4387        let bounds = self.bounds(origin);
4388
4389        //Draw background or border quad
4390        let cursor = if matches!(self.shape, CursorShape::Hollow) {
4391            outline(bounds, self.color)
4392        } else {
4393            fill(bounds, self.color)
4394        };
4395
4396        if let Some(name) = &mut self.cursor_name {
4397            name.paint(cx);
4398        }
4399
4400        cx.paint_quad(cursor);
4401
4402        if let Some(block_text) = &self.block_text {
4403            block_text
4404                .paint(self.origin + origin, self.line_height, cx)
4405                .log_err();
4406        }
4407    }
4408
4409    pub fn shape(&self) -> CursorShape {
4410        self.shape
4411    }
4412}
4413
4414#[derive(Debug)]
4415pub struct HighlightedRange {
4416    pub start_y: Pixels,
4417    pub line_height: Pixels,
4418    pub lines: Vec<HighlightedRangeLine>,
4419    pub color: Hsla,
4420    pub corner_radius: Pixels,
4421}
4422
4423#[derive(Debug)]
4424pub struct HighlightedRangeLine {
4425    pub start_x: Pixels,
4426    pub end_x: Pixels,
4427}
4428
4429impl HighlightedRange {
4430    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
4431        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
4432            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
4433            self.paint_lines(
4434                self.start_y + self.line_height,
4435                &self.lines[1..],
4436                bounds,
4437                cx,
4438            );
4439        } else {
4440            self.paint_lines(self.start_y, &self.lines, bounds, cx);
4441        }
4442    }
4443
4444    fn paint_lines(
4445        &self,
4446        start_y: Pixels,
4447        lines: &[HighlightedRangeLine],
4448        _bounds: Bounds<Pixels>,
4449        cx: &mut WindowContext,
4450    ) {
4451        if lines.is_empty() {
4452            return;
4453        }
4454
4455        let first_line = lines.first().unwrap();
4456        let last_line = lines.last().unwrap();
4457
4458        let first_top_left = point(first_line.start_x, start_y);
4459        let first_top_right = point(first_line.end_x, start_y);
4460
4461        let curve_height = point(Pixels::ZERO, self.corner_radius);
4462        let curve_width = |start_x: Pixels, end_x: Pixels| {
4463            let max = (end_x - start_x) / 2.;
4464            let width = if max < self.corner_radius {
4465                max
4466            } else {
4467                self.corner_radius
4468            };
4469
4470            point(width, Pixels::ZERO)
4471        };
4472
4473        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
4474        let mut path = gpui::Path::new(first_top_right - top_curve_width);
4475        path.curve_to(first_top_right + curve_height, first_top_right);
4476
4477        let mut iter = lines.iter().enumerate().peekable();
4478        while let Some((ix, line)) = iter.next() {
4479            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
4480
4481            if let Some((_, next_line)) = iter.peek() {
4482                let next_top_right = point(next_line.end_x, bottom_right.y);
4483
4484                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
4485                    Ordering::Equal => {
4486                        path.line_to(bottom_right);
4487                    }
4488                    Ordering::Less => {
4489                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
4490                        path.line_to(bottom_right - curve_height);
4491                        if self.corner_radius > Pixels::ZERO {
4492                            path.curve_to(bottom_right - curve_width, bottom_right);
4493                        }
4494                        path.line_to(next_top_right + curve_width);
4495                        if self.corner_radius > Pixels::ZERO {
4496                            path.curve_to(next_top_right + curve_height, next_top_right);
4497                        }
4498                    }
4499                    Ordering::Greater => {
4500                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
4501                        path.line_to(bottom_right - curve_height);
4502                        if self.corner_radius > Pixels::ZERO {
4503                            path.curve_to(bottom_right + curve_width, bottom_right);
4504                        }
4505                        path.line_to(next_top_right - curve_width);
4506                        if self.corner_radius > Pixels::ZERO {
4507                            path.curve_to(next_top_right + curve_height, next_top_right);
4508                        }
4509                    }
4510                }
4511            } else {
4512                let curve_width = curve_width(line.start_x, line.end_x);
4513                path.line_to(bottom_right - curve_height);
4514                if self.corner_radius > Pixels::ZERO {
4515                    path.curve_to(bottom_right - curve_width, bottom_right);
4516                }
4517
4518                let bottom_left = point(line.start_x, bottom_right.y);
4519                path.line_to(bottom_left + curve_width);
4520                if self.corner_radius > Pixels::ZERO {
4521                    path.curve_to(bottom_left - curve_height, bottom_left);
4522                }
4523            }
4524        }
4525
4526        if first_line.start_x > last_line.start_x {
4527            let curve_width = curve_width(last_line.start_x, first_line.start_x);
4528            let second_top_left = point(last_line.start_x, start_y + self.line_height);
4529            path.line_to(second_top_left + curve_height);
4530            if self.corner_radius > Pixels::ZERO {
4531                path.curve_to(second_top_left + curve_width, second_top_left);
4532            }
4533            let first_bottom_left = point(first_line.start_x, second_top_left.y);
4534            path.line_to(first_bottom_left - curve_width);
4535            if self.corner_radius > Pixels::ZERO {
4536                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
4537            }
4538        }
4539
4540        path.line_to(first_top_left + curve_height);
4541        if self.corner_radius > Pixels::ZERO {
4542            path.curve_to(first_top_left + top_curve_width, first_top_left);
4543        }
4544        path.line_to(first_top_right - top_curve_width);
4545
4546        cx.paint_path(path, self.color);
4547    }
4548}
4549
4550pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4551    (delta.pow(1.5) / 100.0).into()
4552}
4553
4554fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4555    (delta.pow(1.2) / 300.0).into()
4556}
4557
4558#[cfg(test)]
4559mod tests {
4560    use super::*;
4561    use crate::{
4562        display_map::{BlockDisposition, BlockProperties},
4563        editor_tests::{init_test, update_test_language_settings},
4564        Editor, MultiBuffer,
4565    };
4566    use gpui::{TestAppContext, VisualTestContext};
4567    use language::language_settings;
4568    use log::info;
4569    use std::num::NonZeroU32;
4570    use util::test::sample_text;
4571
4572    #[gpui::test]
4573    fn test_shape_line_numbers(cx: &mut TestAppContext) {
4574        init_test(cx, |_| {});
4575        let window = cx.add_window(|cx| {
4576            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4577            Editor::new(EditorMode::Full, buffer, None, cx)
4578        });
4579
4580        let editor = window.root(cx).unwrap();
4581        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4582        let element = EditorElement::new(&editor, style);
4583        let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
4584
4585        let layouts = cx
4586            .update_window(*window, |_, cx| {
4587                element
4588                    .layout_line_numbers(
4589                        0..6,
4590                        (0..6).map(Some),
4591                        &Default::default(),
4592                        Some(DisplayPoint::new(0, 0)),
4593                        &snapshot,
4594                        cx,
4595                    )
4596                    .0
4597            })
4598            .unwrap();
4599        assert_eq!(layouts.len(), 6);
4600
4601        let relative_rows = window
4602            .update(cx, |editor, cx| {
4603                let snapshot = editor.snapshot(cx);
4604                element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
4605            })
4606            .unwrap();
4607        assert_eq!(relative_rows[&0], 3);
4608        assert_eq!(relative_rows[&1], 2);
4609        assert_eq!(relative_rows[&2], 1);
4610        // current line has no relative number
4611        assert_eq!(relative_rows[&4], 1);
4612        assert_eq!(relative_rows[&5], 2);
4613
4614        // works if cursor is before screen
4615        let relative_rows = window
4616            .update(cx, |editor, cx| {
4617                let snapshot = editor.snapshot(cx);
4618                element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
4619            })
4620            .unwrap();
4621        assert_eq!(relative_rows.len(), 3);
4622        assert_eq!(relative_rows[&3], 2);
4623        assert_eq!(relative_rows[&4], 3);
4624        assert_eq!(relative_rows[&5], 4);
4625
4626        // works if cursor is after screen
4627        let relative_rows = window
4628            .update(cx, |editor, cx| {
4629                let snapshot = editor.snapshot(cx);
4630                element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
4631            })
4632            .unwrap();
4633        assert_eq!(relative_rows.len(), 3);
4634        assert_eq!(relative_rows[&0], 5);
4635        assert_eq!(relative_rows[&1], 4);
4636        assert_eq!(relative_rows[&2], 3);
4637    }
4638
4639    #[gpui::test]
4640    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
4641        init_test(cx, |_| {});
4642
4643        let window = cx.add_window(|cx| {
4644            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
4645            Editor::new(EditorMode::Full, buffer, None, cx)
4646        });
4647        let cx = &mut VisualTestContext::from_window(*window, cx);
4648        let editor = window.root(cx).unwrap();
4649        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4650
4651        window
4652            .update(cx, |editor, cx| {
4653                editor.cursor_shape = CursorShape::Block;
4654                editor.change_selections(None, cx, |s| {
4655                    s.select_ranges([
4656                        Point::new(0, 0)..Point::new(1, 0),
4657                        Point::new(3, 2)..Point::new(3, 3),
4658                        Point::new(5, 6)..Point::new(6, 0),
4659                    ]);
4660                });
4661            })
4662            .unwrap();
4663
4664        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
4665            EditorElement::new(&editor, style)
4666        });
4667
4668        assert_eq!(state.selections.len(), 1);
4669        let local_selections = &state.selections[0].1;
4670        assert_eq!(local_selections.len(), 3);
4671        // moves cursor back one line
4672        assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
4673        assert_eq!(
4674            local_selections[0].range,
4675            DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
4676        );
4677
4678        // moves cursor back one column
4679        assert_eq!(
4680            local_selections[1].range,
4681            DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
4682        );
4683        assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
4684
4685        // leaves cursor on the max point
4686        assert_eq!(
4687            local_selections[2].range,
4688            DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
4689        );
4690        assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
4691
4692        // active lines does not include 1 (even though the range of the selection does)
4693        assert_eq!(
4694            state.active_rows.keys().cloned().collect::<Vec<u32>>(),
4695            vec![0, 3, 5, 6]
4696        );
4697
4698        // multi-buffer support
4699        // in DisplayPoint coordinates, this is what we're dealing with:
4700        //  0: [[file
4701        //  1:   header]]
4702        //  2: aaaaaa
4703        //  3: bbbbbb
4704        //  4: cccccc
4705        //  5:
4706        //  6: ...
4707        //  7: ffffff
4708        //  8: gggggg
4709        //  9: hhhhhh
4710        // 10:
4711        // 11: [[file
4712        // 12:   header]]
4713        // 13: bbbbbb
4714        // 14: cccccc
4715        // 15: dddddd
4716        let window = cx.add_window(|cx| {
4717            let buffer = MultiBuffer::build_multi(
4718                [
4719                    (
4720                        &(sample_text(8, 6, 'a') + "\n"),
4721                        vec![
4722                            Point::new(0, 0)..Point::new(3, 0),
4723                            Point::new(4, 0)..Point::new(7, 0),
4724                        ],
4725                    ),
4726                    (
4727                        &(sample_text(8, 6, 'a') + "\n"),
4728                        vec![Point::new(1, 0)..Point::new(3, 0)],
4729                    ),
4730                ],
4731                cx,
4732            );
4733            Editor::new(EditorMode::Full, buffer, None, cx)
4734        });
4735        let editor = window.root(cx).unwrap();
4736        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4737        let _state = window.update(cx, |editor, cx| {
4738            editor.cursor_shape = CursorShape::Block;
4739            editor.change_selections(None, cx, |s| {
4740                s.select_display_ranges([
4741                    DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
4742                    DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
4743                ]);
4744            });
4745        });
4746
4747        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
4748            EditorElement::new(&editor, style)
4749        });
4750        assert_eq!(state.selections.len(), 1);
4751        let local_selections = &state.selections[0].1;
4752        assert_eq!(local_selections.len(), 2);
4753
4754        // moves cursor on excerpt boundary back a line
4755        // and doesn't allow selection to bleed through
4756        assert_eq!(
4757            local_selections[0].range,
4758            DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
4759        );
4760        assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
4761        // moves cursor on buffer boundary back two lines
4762        // and doesn't allow selection to bleed through
4763        assert_eq!(
4764            local_selections[1].range,
4765            DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
4766        );
4767        assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
4768    }
4769
4770    #[gpui::test]
4771    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
4772        init_test(cx, |_| {});
4773
4774        let window = cx.add_window(|cx| {
4775            let buffer = MultiBuffer::build_simple("", cx);
4776            Editor::new(EditorMode::Full, buffer, None, cx)
4777        });
4778        let cx = &mut VisualTestContext::from_window(*window, cx);
4779        let editor = window.root(cx).unwrap();
4780        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4781        window
4782            .update(cx, |editor, cx| {
4783                editor.set_placeholder_text("hello", cx);
4784                editor.insert_blocks(
4785                    [BlockProperties {
4786                        style: BlockStyle::Fixed,
4787                        disposition: BlockDisposition::Above,
4788                        height: 3,
4789                        position: Anchor::min(),
4790                        render: Box::new(|_| div().into_any()),
4791                    }],
4792                    None,
4793                    cx,
4794                );
4795
4796                // Blur the editor so that it displays placeholder text.
4797                cx.blur();
4798            })
4799            .unwrap();
4800
4801        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
4802            EditorElement::new(&editor, style)
4803        });
4804        assert_eq!(state.position_map.line_layouts.len(), 4);
4805        assert_eq!(
4806            state
4807                .line_numbers
4808                .iter()
4809                .map(Option::is_some)
4810                .collect::<Vec<_>>(),
4811            &[false, false, false, true]
4812        );
4813    }
4814
4815    #[gpui::test]
4816    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
4817        const TAB_SIZE: u32 = 4;
4818
4819        let input_text = "\t \t|\t| a b";
4820        let expected_invisibles = vec![
4821            Invisible::Tab {
4822                line_start_offset: 0,
4823            },
4824            Invisible::Whitespace {
4825                line_offset: TAB_SIZE as usize,
4826            },
4827            Invisible::Tab {
4828                line_start_offset: TAB_SIZE as usize + 1,
4829            },
4830            Invisible::Tab {
4831                line_start_offset: TAB_SIZE as usize * 2 + 1,
4832            },
4833            Invisible::Whitespace {
4834                line_offset: TAB_SIZE as usize * 3 + 1,
4835            },
4836            Invisible::Whitespace {
4837                line_offset: TAB_SIZE as usize * 3 + 3,
4838            },
4839        ];
4840        assert_eq!(
4841            expected_invisibles.len(),
4842            input_text
4843                .chars()
4844                .filter(|initial_char| initial_char.is_whitespace())
4845                .count(),
4846            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4847        );
4848
4849        init_test(cx, |s| {
4850            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4851            s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
4852        });
4853
4854        let actual_invisibles =
4855            collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
4856
4857        assert_eq!(expected_invisibles, actual_invisibles);
4858    }
4859
4860    #[gpui::test]
4861    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
4862        init_test(cx, |s| {
4863            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4864            s.defaults.tab_size = NonZeroU32::new(4);
4865        });
4866
4867        for editor_mode_without_invisibles in [
4868            EditorMode::SingleLine,
4869            EditorMode::AutoHeight { max_lines: 100 },
4870        ] {
4871            let invisibles = collect_invisibles_from_new_editor(
4872                cx,
4873                editor_mode_without_invisibles,
4874                "\t\t\t| | a b",
4875                px(500.0),
4876            );
4877            assert!(invisibles.is_empty(),
4878                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
4879        }
4880    }
4881
4882    #[gpui::test]
4883    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
4884        let tab_size = 4;
4885        let input_text = "a\tbcd   ".repeat(9);
4886        let repeated_invisibles = [
4887            Invisible::Tab {
4888                line_start_offset: 1,
4889            },
4890            Invisible::Whitespace {
4891                line_offset: tab_size as usize + 3,
4892            },
4893            Invisible::Whitespace {
4894                line_offset: tab_size as usize + 4,
4895            },
4896            Invisible::Whitespace {
4897                line_offset: tab_size as usize + 5,
4898            },
4899        ];
4900        let expected_invisibles = std::iter::once(repeated_invisibles)
4901            .cycle()
4902            .take(9)
4903            .flatten()
4904            .collect::<Vec<_>>();
4905        assert_eq!(
4906            expected_invisibles.len(),
4907            input_text
4908                .chars()
4909                .filter(|initial_char| initial_char.is_whitespace())
4910                .count(),
4911            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4912        );
4913        info!("Expected invisibles: {expected_invisibles:?}");
4914
4915        init_test(cx, |_| {});
4916
4917        // Put the same string with repeating whitespace pattern into editors of various size,
4918        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4919        let resize_step = 10.0;
4920        let mut editor_width = 200.0;
4921        while editor_width <= 1000.0 {
4922            update_test_language_settings(cx, |s| {
4923                s.defaults.tab_size = NonZeroU32::new(tab_size);
4924                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4925                s.defaults.preferred_line_length = Some(editor_width as u32);
4926                s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4927            });
4928
4929            let actual_invisibles = collect_invisibles_from_new_editor(
4930                cx,
4931                EditorMode::Full,
4932                &input_text,
4933                px(editor_width),
4934            );
4935
4936            // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4937            // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4938            let mut i = 0;
4939            for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4940                i = actual_index;
4941                match expected_invisibles.get(i) {
4942                    Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4943                        (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4944                        | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4945                        _ => {
4946                            panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4947                        }
4948                    },
4949                    None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4950                }
4951            }
4952            let missing_expected_invisibles = &expected_invisibles[i + 1..];
4953            assert!(
4954                missing_expected_invisibles.is_empty(),
4955                "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4956            );
4957
4958            editor_width += resize_step;
4959        }
4960    }
4961
4962    fn collect_invisibles_from_new_editor(
4963        cx: &mut TestAppContext,
4964        editor_mode: EditorMode,
4965        input_text: &str,
4966        editor_width: Pixels,
4967    ) -> Vec<Invisible> {
4968        info!(
4969            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
4970            editor_width.0
4971        );
4972        let window = cx.add_window(|cx| {
4973            let buffer = MultiBuffer::build_simple(&input_text, cx);
4974            Editor::new(editor_mode, buffer, None, cx)
4975        });
4976        let cx = &mut VisualTestContext::from_window(*window, cx);
4977        let editor = window.root(cx).unwrap();
4978        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4979        window
4980            .update(cx, |editor, cx| {
4981                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4982                editor.set_wrap_width(Some(editor_width), cx);
4983            })
4984            .unwrap();
4985        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
4986            EditorElement::new(&editor, style)
4987        });
4988        state
4989            .position_map
4990            .line_layouts
4991            .iter()
4992            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
4993            .cloned()
4994            .collect()
4995    }
4996}
4997
4998pub fn register_action<T: Action>(
4999    view: &View<Editor>,
5000    cx: &mut WindowContext,
5001    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
5002) {
5003    let view = view.clone();
5004    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
5005        let action = action.downcast_ref().unwrap();
5006        if phase == DispatchPhase::Bubble {
5007            view.update(cx, |editor, cx| {
5008                listener(editor, action, cx);
5009            })
5010        }
5011    })
5012}
5013
5014fn compute_auto_height_layout(
5015    editor: &mut Editor,
5016    max_lines: usize,
5017    max_line_number_width: Pixels,
5018    known_dimensions: Size<Option<Pixels>>,
5019    cx: &mut ViewContext<Editor>,
5020) -> Option<Size<Pixels>> {
5021    let width = known_dimensions.width?;
5022    if let Some(height) = known_dimensions.height {
5023        return Some(size(width, height));
5024    }
5025
5026    let style = editor.style.as_ref().unwrap();
5027    let font_id = cx.text_system().resolve_font(&style.text.font());
5028    let font_size = style.text.font_size.to_pixels(cx.rem_size());
5029    let line_height = style.text.line_height_in_pixels(cx.rem_size());
5030    let em_width = cx
5031        .text_system()
5032        .typographic_bounds(font_id, font_size, 'm')
5033        .unwrap()
5034        .size
5035        .width;
5036
5037    let mut snapshot = editor.snapshot(cx);
5038    let gutter_dimensions =
5039        snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
5040
5041    editor.gutter_width = gutter_dimensions.width;
5042    let text_width = width - gutter_dimensions.width;
5043    let overscroll = size(em_width, px(0.));
5044
5045    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
5046    if editor.set_wrap_width(Some(editor_width), cx) {
5047        snapshot = editor.snapshot(cx);
5048    }
5049
5050    let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
5051    let height = scroll_height
5052        .max(line_height)
5053        .min(line_height * max_lines as f32);
5054
5055    Some(size(width, height))
5056}