element.rs

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