element.rs

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