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