element.rs

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