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