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