element.rs

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