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