element.rs

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