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