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