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) =
2838                    inline_completion_popover_text(edit_start, editor_snapshot, edits, cx);
2839
2840                let longest_row =
2841                    editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
2842                let longest_line_width = if visible_row_range.contains(&longest_row) {
2843                    line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
2844                } else {
2845                    layout_line(
2846                        longest_row,
2847                        editor_snapshot,
2848                        style,
2849                        editor_width,
2850                        |_| false,
2851                        cx,
2852                    )
2853                    .width
2854                };
2855
2856                let text = gpui::StyledText::new(text).with_highlights(&style.text, highlights);
2857
2858                let mut element = div()
2859                    .bg(cx.theme().colors().editor_background)
2860                    .border_1()
2861                    .border_color(cx.theme().colors().border)
2862                    .rounded_md()
2863                    .px_1()
2864                    .child(text)
2865                    .into_any();
2866
2867                let origin = text_bounds.origin
2868                    + point(
2869                        longest_line_width + PADDING_X - scroll_pixel_position.x,
2870                        edit_start.row().as_f32() * line_height - scroll_pixel_position.y,
2871                    );
2872                element.prepaint_as_root(origin, AvailableSpace::min_size(), cx);
2873                Some(element)
2874            }
2875        }
2876    }
2877
2878    fn layout_mouse_context_menu(
2879        &self,
2880        editor_snapshot: &EditorSnapshot,
2881        visible_range: Range<DisplayRow>,
2882        content_origin: gpui::Point<Pixels>,
2883        cx: &mut WindowContext,
2884    ) -> Option<AnyElement> {
2885        let position = self.editor.update(cx, |editor, cx| {
2886            let visible_start_point = editor.display_to_pixel_point(
2887                DisplayPoint::new(visible_range.start, 0),
2888                editor_snapshot,
2889                cx,
2890            )?;
2891            let visible_end_point = editor.display_to_pixel_point(
2892                DisplayPoint::new(visible_range.end, 0),
2893                editor_snapshot,
2894                cx,
2895            )?;
2896
2897            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
2898            let (source_display_point, position) = match mouse_context_menu.position {
2899                MenuPosition::PinnedToScreen(point) => (None, point),
2900                MenuPosition::PinnedToEditor { source, offset } => {
2901                    let source_display_point = source.to_display_point(editor_snapshot);
2902                    let source_point = editor.to_pixel_point(source, editor_snapshot, cx)?;
2903                    let position = content_origin + source_point + offset;
2904                    (Some(source_display_point), position)
2905                }
2906            };
2907
2908            let source_included = source_display_point.map_or(true, |source_display_point| {
2909                visible_range
2910                    .to_inclusive()
2911                    .contains(&source_display_point.row())
2912            });
2913            let position_included =
2914                visible_start_point.y <= position.y && position.y <= visible_end_point.y;
2915            if !source_included && !position_included {
2916                None
2917            } else {
2918                Some(position)
2919            }
2920        })?;
2921
2922        let mut element = self.editor.update(cx, |editor, _| {
2923            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
2924            let context_menu = mouse_context_menu.context_menu.clone();
2925
2926            Some(
2927                deferred(
2928                    anchored()
2929                        .position(position)
2930                        .child(context_menu)
2931                        .anchor(AnchorCorner::TopLeft)
2932                        .snap_to_window_with_margin(px(8.)),
2933                )
2934                .with_priority(1)
2935                .into_any(),
2936            )
2937        })?;
2938
2939        element.prepaint_as_root(position, AvailableSpace::min_size(), cx);
2940        Some(element)
2941    }
2942
2943    #[allow(clippy::too_many_arguments)]
2944    fn layout_hover_popovers(
2945        &self,
2946        snapshot: &EditorSnapshot,
2947        hitbox: &Hitbox,
2948        text_hitbox: &Hitbox,
2949        visible_display_row_range: Range<DisplayRow>,
2950        content_origin: gpui::Point<Pixels>,
2951        scroll_pixel_position: gpui::Point<Pixels>,
2952        line_layouts: &[LineWithInvisibles],
2953        line_height: Pixels,
2954        em_width: Pixels,
2955        cx: &mut WindowContext,
2956    ) {
2957        struct MeasuredHoverPopover {
2958            element: AnyElement,
2959            size: Size<Pixels>,
2960            horizontal_offset: Pixels,
2961        }
2962
2963        let max_size = size(
2964            (120. * em_width) // Default size
2965                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2966                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2967            (16. * line_height) // Default size
2968                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2969                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2970        );
2971
2972        let hover_popovers = self.editor.update(cx, |editor, cx| {
2973            editor
2974                .hover_state
2975                .render(snapshot, visible_display_row_range.clone(), max_size, cx)
2976        });
2977        let Some((position, hover_popovers)) = hover_popovers else {
2978            return;
2979        };
2980
2981        // This is safe because we check on layout whether the required row is available
2982        let hovered_row_layout =
2983            &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
2984
2985        // Compute Hovered Point
2986        let x =
2987            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
2988        let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
2989        let hovered_point = content_origin + point(x, y);
2990
2991        let mut overall_height = Pixels::ZERO;
2992        let mut measured_hover_popovers = Vec::new();
2993        for mut hover_popover in hover_popovers {
2994            let size = hover_popover.layout_as_root(AvailableSpace::min_size(), cx);
2995            let horizontal_offset =
2996                (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
2997
2998            overall_height += HOVER_POPOVER_GAP + size.height;
2999
3000            measured_hover_popovers.push(MeasuredHoverPopover {
3001                element: hover_popover,
3002                size,
3003                horizontal_offset,
3004            });
3005        }
3006        overall_height += HOVER_POPOVER_GAP;
3007
3008        fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
3009            let mut occlusion = div()
3010                .size_full()
3011                .occlude()
3012                .on_mouse_move(|_, cx| cx.stop_propagation())
3013                .into_any_element();
3014            occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), cx);
3015            cx.defer_draw(occlusion, origin, 2);
3016        }
3017
3018        if hovered_point.y > overall_height {
3019            // There is enough space above. Render popovers above the hovered point
3020            let mut current_y = hovered_point.y;
3021            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3022                let size = popover.size;
3023                let popover_origin = point(
3024                    hovered_point.x + popover.horizontal_offset,
3025                    current_y - size.height,
3026                );
3027
3028                cx.defer_draw(popover.element, popover_origin, 2);
3029                if position != itertools::Position::Last {
3030                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
3031                    draw_occluder(size.width, origin, cx);
3032                }
3033
3034                current_y = popover_origin.y - HOVER_POPOVER_GAP;
3035            }
3036        } else {
3037            // There is not enough space above. Render popovers below the hovered point
3038            let mut current_y = hovered_point.y + line_height;
3039            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3040                let size = popover.size;
3041                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
3042
3043                cx.defer_draw(popover.element, popover_origin, 2);
3044                if position != itertools::Position::Last {
3045                    let origin = point(popover_origin.x, popover_origin.y + size.height);
3046                    draw_occluder(size.width, origin, cx);
3047                }
3048
3049                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
3050            }
3051        }
3052    }
3053
3054    #[allow(clippy::too_many_arguments)]
3055    fn layout_signature_help(
3056        &self,
3057        hitbox: &Hitbox,
3058        content_origin: gpui::Point<Pixels>,
3059        scroll_pixel_position: gpui::Point<Pixels>,
3060        newest_selection_head: Option<DisplayPoint>,
3061        start_row: DisplayRow,
3062        line_layouts: &[LineWithInvisibles],
3063        line_height: Pixels,
3064        em_width: Pixels,
3065        cx: &mut WindowContext,
3066    ) {
3067        if !self.editor.focus_handle(cx).is_focused(cx) {
3068            return;
3069        }
3070        let Some(newest_selection_head) = newest_selection_head else {
3071            return;
3072        };
3073        let selection_row = newest_selection_head.row();
3074        if selection_row < start_row {
3075            return;
3076        }
3077        let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
3078        else {
3079            return;
3080        };
3081
3082        let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
3083            - scroll_pixel_position.x
3084            + content_origin.x;
3085        let start_y =
3086            selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
3087
3088        let max_size = size(
3089            (120. * em_width) // Default size
3090                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
3091                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3092            (16. * line_height) // Default size
3093                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
3094                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3095        );
3096
3097        let maybe_element = self.editor.update(cx, |editor, cx| {
3098            if let Some(popover) = editor.signature_help_state.popover_mut() {
3099                let element = popover.render(
3100                    &self.style,
3101                    max_size,
3102                    editor.workspace.as_ref().map(|(w, _)| w.clone()),
3103                    cx,
3104                );
3105                Some(element)
3106            } else {
3107                None
3108            }
3109        });
3110        if let Some(mut element) = maybe_element {
3111            let window_size = cx.viewport_size();
3112            let size = element.layout_as_root(Size::<AvailableSpace>::default(), cx);
3113            let mut point = point(start_x, start_y - size.height);
3114
3115            // Adjusting to ensure the popover does not overflow in the X-axis direction.
3116            if point.x + size.width >= window_size.width {
3117                point.x = window_size.width - size.width;
3118            }
3119
3120            cx.defer_draw(element, point, 1)
3121        }
3122    }
3123
3124    fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
3125        cx.paint_layer(layout.hitbox.bounds, |cx| {
3126            let scroll_top = layout.position_map.snapshot.scroll_position().y;
3127            let gutter_bg = cx.theme().colors().editor_gutter_background;
3128            cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
3129            cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
3130
3131            if let EditorMode::Full = layout.mode {
3132                let mut active_rows = layout.active_rows.iter().peekable();
3133                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
3134                    let mut end_row = start_row.0;
3135                    while active_rows
3136                        .peek()
3137                        .map_or(false, |(active_row, has_selection)| {
3138                            active_row.0 == end_row + 1
3139                                && *has_selection == contains_non_empty_selection
3140                        })
3141                    {
3142                        active_rows.next().unwrap();
3143                        end_row += 1;
3144                    }
3145
3146                    if !contains_non_empty_selection {
3147                        let highlight_h_range =
3148                            match layout.position_map.snapshot.current_line_highlight {
3149                                CurrentLineHighlight::Gutter => Some(Range {
3150                                    start: layout.hitbox.left(),
3151                                    end: layout.gutter_hitbox.right(),
3152                                }),
3153                                CurrentLineHighlight::Line => Some(Range {
3154                                    start: layout.text_hitbox.bounds.left(),
3155                                    end: layout.text_hitbox.bounds.right(),
3156                                }),
3157                                CurrentLineHighlight::All => Some(Range {
3158                                    start: layout.hitbox.left(),
3159                                    end: layout.hitbox.right(),
3160                                }),
3161                                CurrentLineHighlight::None => None,
3162                            };
3163                        if let Some(range) = highlight_h_range {
3164                            let active_line_bg = cx.theme().colors().editor_active_line_background;
3165                            let bounds = Bounds {
3166                                origin: point(
3167                                    range.start,
3168                                    layout.hitbox.origin.y
3169                                        + (start_row.as_f32() - scroll_top)
3170                                            * layout.position_map.line_height,
3171                                ),
3172                                size: size(
3173                                    range.end - range.start,
3174                                    layout.position_map.line_height
3175                                        * (end_row - start_row.0 + 1) as f32,
3176                                ),
3177                            };
3178                            cx.paint_quad(fill(bounds, active_line_bg));
3179                        }
3180                    }
3181                }
3182
3183                let mut paint_highlight =
3184                    |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
3185                        let origin = point(
3186                            layout.hitbox.origin.x,
3187                            layout.hitbox.origin.y
3188                                + (highlight_row_start.as_f32() - scroll_top)
3189                                    * layout.position_map.line_height,
3190                        );
3191                        let size = size(
3192                            layout.hitbox.size.width,
3193                            layout.position_map.line_height
3194                                * highlight_row_end.next_row().minus(highlight_row_start) as f32,
3195                        );
3196                        cx.paint_quad(fill(Bounds { origin, size }, color));
3197                    };
3198
3199                let mut current_paint: Option<(Hsla, Range<DisplayRow>)> = None;
3200                for (&new_row, &new_color) in &layout.highlighted_rows {
3201                    match &mut current_paint {
3202                        Some((current_color, current_range)) => {
3203                            let current_color = *current_color;
3204                            let new_range_started = current_color != new_color
3205                                || current_range.end.next_row() != new_row;
3206                            if new_range_started {
3207                                paint_highlight(
3208                                    current_range.start,
3209                                    current_range.end,
3210                                    current_color,
3211                                );
3212                                current_paint = Some((new_color, new_row..new_row));
3213                                continue;
3214                            } else {
3215                                current_range.end = current_range.end.next_row();
3216                            }
3217                        }
3218                        None => current_paint = Some((new_color, new_row..new_row)),
3219                    };
3220                }
3221                if let Some((color, range)) = current_paint {
3222                    paint_highlight(range.start, range.end, color);
3223                }
3224
3225                let scroll_left =
3226                    layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
3227
3228                for (wrap_position, active) in layout.wrap_guides.iter() {
3229                    let x = (layout.text_hitbox.origin.x
3230                        + *wrap_position
3231                        + layout.position_map.em_width / 2.)
3232                        - scroll_left;
3233
3234                    let show_scrollbars = layout
3235                        .scrollbar_layout
3236                        .as_ref()
3237                        .map_or(false, |scrollbar| scrollbar.visible);
3238                    if x < layout.text_hitbox.origin.x
3239                        || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
3240                    {
3241                        continue;
3242                    }
3243
3244                    let color = if *active {
3245                        cx.theme().colors().editor_active_wrap_guide
3246                    } else {
3247                        cx.theme().colors().editor_wrap_guide
3248                    };
3249                    cx.paint_quad(fill(
3250                        Bounds {
3251                            origin: point(x, layout.text_hitbox.origin.y),
3252                            size: size(px(1.), layout.text_hitbox.size.height),
3253                        },
3254                        color,
3255                    ));
3256                }
3257            }
3258        })
3259    }
3260
3261    fn paint_indent_guides(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3262        let Some(indent_guides) = &layout.indent_guides else {
3263            return;
3264        };
3265
3266        let faded_color = |color: Hsla, alpha: f32| {
3267            let mut faded = color;
3268            faded.a = alpha;
3269            faded
3270        };
3271
3272        for indent_guide in indent_guides {
3273            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
3274            let settings = indent_guide.settings;
3275
3276            // TODO fixed for now, expose them through themes later
3277            const INDENT_AWARE_ALPHA: f32 = 0.2;
3278            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
3279            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
3280            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
3281
3282            let line_color = match (settings.coloring, indent_guide.active) {
3283                (IndentGuideColoring::Disabled, _) => None,
3284                (IndentGuideColoring::Fixed, false) => {
3285                    Some(cx.theme().colors().editor_indent_guide)
3286                }
3287                (IndentGuideColoring::Fixed, true) => {
3288                    Some(cx.theme().colors().editor_indent_guide_active)
3289                }
3290                (IndentGuideColoring::IndentAware, false) => {
3291                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
3292                }
3293                (IndentGuideColoring::IndentAware, true) => {
3294                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
3295                }
3296            };
3297
3298            let background_color = match (settings.background_coloring, indent_guide.active) {
3299                (IndentGuideBackgroundColoring::Disabled, _) => None,
3300                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
3301                    indent_accent_colors,
3302                    INDENT_AWARE_BACKGROUND_ALPHA,
3303                )),
3304                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
3305                    indent_accent_colors,
3306                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
3307                )),
3308            };
3309
3310            let requested_line_width = if indent_guide.active {
3311                settings.active_line_width
3312            } else {
3313                settings.line_width
3314            }
3315            .clamp(1, 10);
3316            let mut line_indicator_width = 0.;
3317            if let Some(color) = line_color {
3318                cx.paint_quad(fill(
3319                    Bounds {
3320                        origin: indent_guide.origin,
3321                        size: size(px(requested_line_width as f32), indent_guide.length),
3322                    },
3323                    color,
3324                ));
3325                line_indicator_width = requested_line_width as f32;
3326            }
3327
3328            if let Some(color) = background_color {
3329                let width = indent_guide.single_indent_width - px(line_indicator_width);
3330                cx.paint_quad(fill(
3331                    Bounds {
3332                        origin: point(
3333                            indent_guide.origin.x + px(line_indicator_width),
3334                            indent_guide.origin.y,
3335                        ),
3336                        size: size(width, indent_guide.length),
3337                    },
3338                    color,
3339                ));
3340            }
3341        }
3342    }
3343
3344    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3345        let line_height = layout.position_map.line_height;
3346        let scroll_position = layout.position_map.snapshot.scroll_position();
3347        let scroll_top = scroll_position.y * line_height;
3348
3349        cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
3350
3351        for (ix, line) in layout.line_numbers.iter().enumerate() {
3352            if let Some(line) = line {
3353                let line_origin = layout.gutter_hitbox.origin
3354                    + point(
3355                        layout.gutter_hitbox.size.width
3356                            - line.width
3357                            - layout.gutter_dimensions.right_padding,
3358                        ix as f32 * line_height - (scroll_top % line_height),
3359                    );
3360
3361                line.paint(line_origin, line_height, cx).log_err();
3362            }
3363        }
3364    }
3365
3366    fn paint_diff_hunks(layout: &mut EditorLayout, cx: &mut WindowContext) {
3367        if layout.display_hunks.is_empty() {
3368            return;
3369        }
3370
3371        let line_height = layout.position_map.line_height;
3372        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3373            for (hunk, hitbox) in &layout.display_hunks {
3374                let hunk_to_paint = match hunk {
3375                    DisplayDiffHunk::Folded { .. } => {
3376                        let hunk_bounds = Self::diff_hunk_bounds(
3377                            &layout.position_map.snapshot,
3378                            line_height,
3379                            layout.gutter_hitbox.bounds,
3380                            hunk,
3381                        );
3382                        Some((
3383                            hunk_bounds,
3384                            cx.theme().status().modified,
3385                            Corners::all(px(0.)),
3386                        ))
3387                    }
3388                    DisplayDiffHunk::Unfolded { status, .. } => {
3389                        hitbox.as_ref().map(|hunk_hitbox| match status {
3390                            DiffHunkStatus::Added => (
3391                                hunk_hitbox.bounds,
3392                                cx.theme().status().created,
3393                                Corners::all(px(0.)),
3394                            ),
3395                            DiffHunkStatus::Modified => (
3396                                hunk_hitbox.bounds,
3397                                cx.theme().status().modified,
3398                                Corners::all(px(0.)),
3399                            ),
3400                            DiffHunkStatus::Removed => (
3401                                Bounds::new(
3402                                    point(
3403                                        hunk_hitbox.origin.x - hunk_hitbox.size.width,
3404                                        hunk_hitbox.origin.y,
3405                                    ),
3406                                    size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
3407                                ),
3408                                cx.theme().status().deleted,
3409                                Corners::all(1. * line_height),
3410                            ),
3411                        })
3412                    }
3413                };
3414
3415                if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
3416                    cx.paint_quad(quad(
3417                        hunk_bounds,
3418                        corner_radii,
3419                        background_color,
3420                        Edges::default(),
3421                        transparent_black(),
3422                    ));
3423                }
3424            }
3425        });
3426    }
3427
3428    pub(super) fn diff_hunk_bounds(
3429        snapshot: &EditorSnapshot,
3430        line_height: Pixels,
3431        gutter_bounds: Bounds<Pixels>,
3432        hunk: &DisplayDiffHunk,
3433    ) -> Bounds<Pixels> {
3434        let scroll_position = snapshot.scroll_position();
3435        let scroll_top = scroll_position.y * line_height;
3436
3437        match hunk {
3438            DisplayDiffHunk::Folded { display_row, .. } => {
3439                let start_y = display_row.as_f32() * line_height - scroll_top;
3440                let end_y = start_y + line_height;
3441
3442                let width = Self::diff_hunk_strip_width(line_height);
3443                let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3444                let highlight_size = size(width, end_y - start_y);
3445                Bounds::new(highlight_origin, highlight_size)
3446            }
3447            DisplayDiffHunk::Unfolded {
3448                display_row_range,
3449                status,
3450                ..
3451            } => match status {
3452                DiffHunkStatus::Added | DiffHunkStatus::Modified => {
3453                    let start_row = display_row_range.start;
3454                    let end_row = display_row_range.end;
3455                    // If we're in a multibuffer, row range span might include an
3456                    // excerpt header, so if we were to draw the marker straight away,
3457                    // the hunk might include the rows of that header.
3458                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
3459                    // Instead, we simply check whether the range we're dealing with includes
3460                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
3461                    let end_row_in_current_excerpt = snapshot
3462                        .blocks_in_range(start_row..end_row)
3463                        .find_map(|(start_row, block)| {
3464                            if matches!(block, Block::ExcerptBoundary { .. }) {
3465                                Some(start_row)
3466                            } else {
3467                                None
3468                            }
3469                        })
3470                        .unwrap_or(end_row);
3471
3472                    let start_y = start_row.as_f32() * line_height - scroll_top;
3473                    let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
3474
3475                    let width = Self::diff_hunk_strip_width(line_height);
3476                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3477                    let highlight_size = size(width, end_y - start_y);
3478                    Bounds::new(highlight_origin, highlight_size)
3479                }
3480                DiffHunkStatus::Removed => {
3481                    let row = display_row_range.start;
3482
3483                    let offset = line_height / 2.;
3484                    let start_y = row.as_f32() * line_height - offset - scroll_top;
3485                    let end_y = start_y + line_height;
3486
3487                    let width = (0.35 * line_height).floor();
3488                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3489                    let highlight_size = size(width, end_y - start_y);
3490                    Bounds::new(highlight_origin, highlight_size)
3491                }
3492            },
3493        }
3494    }
3495
3496    /// Returns the width of the diff strip that will be displayed in the gutter.
3497    pub(super) fn diff_hunk_strip_width(line_height: Pixels) -> Pixels {
3498        // We floor the value to prevent pixel rounding.
3499        (0.275 * line_height).floor()
3500    }
3501
3502    fn paint_gutter_indicators(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3503        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3504            cx.with_element_namespace("crease_toggles", |cx| {
3505                for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
3506                    crease_toggle.paint(cx);
3507                }
3508            });
3509
3510            for test_indicator in layout.test_indicators.iter_mut() {
3511                test_indicator.paint(cx);
3512            }
3513
3514            if let Some(indicator) = layout.code_actions_indicator.as_mut() {
3515                indicator.paint(cx);
3516            }
3517        });
3518    }
3519
3520    fn paint_gutter_highlights(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3521        for (_, hunk_hitbox) in &layout.display_hunks {
3522            if let Some(hunk_hitbox) = hunk_hitbox {
3523                cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
3524            }
3525        }
3526
3527        let show_git_gutter = layout
3528            .position_map
3529            .snapshot
3530            .show_git_diff_gutter
3531            .unwrap_or_else(|| {
3532                matches!(
3533                    ProjectSettings::get_global(cx).git.git_gutter,
3534                    Some(GitGutterSetting::TrackedFiles)
3535                )
3536            });
3537        if show_git_gutter {
3538            Self::paint_diff_hunks(layout, cx)
3539        }
3540
3541        let highlight_width = 0.275 * layout.position_map.line_height;
3542        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
3543        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3544            for (range, color) in &layout.highlighted_gutter_ranges {
3545                let start_row = if range.start.row() < layout.visible_display_row_range.start {
3546                    layout.visible_display_row_range.start - DisplayRow(1)
3547                } else {
3548                    range.start.row()
3549                };
3550                let end_row = if range.end.row() > layout.visible_display_row_range.end {
3551                    layout.visible_display_row_range.end + DisplayRow(1)
3552                } else {
3553                    range.end.row()
3554                };
3555
3556                let start_y = layout.gutter_hitbox.top()
3557                    + start_row.0 as f32 * layout.position_map.line_height
3558                    - layout.position_map.scroll_pixel_position.y;
3559                let end_y = layout.gutter_hitbox.top()
3560                    + (end_row.0 + 1) as f32 * layout.position_map.line_height
3561                    - layout.position_map.scroll_pixel_position.y;
3562                let bounds = Bounds::from_corners(
3563                    point(layout.gutter_hitbox.left(), start_y),
3564                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
3565                );
3566                cx.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
3567            }
3568        });
3569    }
3570
3571    fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3572        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
3573            return;
3574        };
3575
3576        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3577            for mut blame_element in blamed_display_rows.into_iter() {
3578                blame_element.paint(cx);
3579            }
3580        })
3581    }
3582
3583    fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3584        cx.with_content_mask(
3585            Some(ContentMask {
3586                bounds: layout.text_hitbox.bounds,
3587            }),
3588            |cx| {
3589                let cursor_style = if self
3590                    .editor
3591                    .read(cx)
3592                    .hovered_link_state
3593                    .as_ref()
3594                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
3595                {
3596                    CursorStyle::PointingHand
3597                } else {
3598                    CursorStyle::IBeam
3599                };
3600                cx.set_cursor_style(cursor_style, &layout.text_hitbox);
3601
3602                let invisible_display_ranges = self.paint_highlights(layout, cx);
3603                self.paint_lines(&invisible_display_ranges, layout, cx);
3604                self.paint_redactions(layout, cx);
3605                self.paint_cursors(layout, cx);
3606                self.paint_inline_blame(layout, cx);
3607                cx.with_element_namespace("crease_trailers", |cx| {
3608                    for trailer in layout.crease_trailers.iter_mut().flatten() {
3609                        trailer.element.paint(cx);
3610                    }
3611                });
3612            },
3613        )
3614    }
3615
3616    fn paint_highlights(
3617        &mut self,
3618        layout: &mut EditorLayout,
3619        cx: &mut WindowContext,
3620    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
3621        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3622            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
3623            let line_end_overshoot = 0.15 * layout.position_map.line_height;
3624            for (range, color) in &layout.highlighted_ranges {
3625                self.paint_highlighted_range(
3626                    range.clone(),
3627                    *color,
3628                    Pixels::ZERO,
3629                    line_end_overshoot,
3630                    layout,
3631                    cx,
3632                );
3633            }
3634
3635            let corner_radius = 0.15 * layout.position_map.line_height;
3636
3637            for (player_color, selections) in &layout.selections {
3638                for selection in selections.iter() {
3639                    self.paint_highlighted_range(
3640                        selection.range.clone(),
3641                        player_color.selection,
3642                        corner_radius,
3643                        corner_radius * 2.,
3644                        layout,
3645                        cx,
3646                    );
3647
3648                    if selection.is_local && !selection.range.is_empty() {
3649                        invisible_display_ranges.push(selection.range.clone());
3650                    }
3651                }
3652            }
3653            invisible_display_ranges
3654        })
3655    }
3656
3657    fn paint_lines(
3658        &mut self,
3659        invisible_display_ranges: &[Range<DisplayPoint>],
3660        layout: &mut EditorLayout,
3661        cx: &mut WindowContext,
3662    ) {
3663        let whitespace_setting = self
3664            .editor
3665            .read(cx)
3666            .buffer
3667            .read(cx)
3668            .settings_at(0, cx)
3669            .show_whitespaces;
3670
3671        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
3672            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
3673            line_with_invisibles.draw(
3674                layout,
3675                row,
3676                layout.content_origin,
3677                whitespace_setting,
3678                invisible_display_ranges,
3679                cx,
3680            )
3681        }
3682
3683        for line_element in &mut layout.line_elements {
3684            line_element.paint(cx);
3685        }
3686    }
3687
3688    fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3689        if layout.redacted_ranges.is_empty() {
3690            return;
3691        }
3692
3693        let line_end_overshoot = layout.line_end_overshoot();
3694
3695        // A softer than perfect black
3696        let redaction_color = gpui::rgb(0x0e1111);
3697
3698        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3699            for range in layout.redacted_ranges.iter() {
3700                self.paint_highlighted_range(
3701                    range.clone(),
3702                    redaction_color.into(),
3703                    Pixels::ZERO,
3704                    line_end_overshoot,
3705                    layout,
3706                    cx,
3707                );
3708            }
3709        });
3710    }
3711
3712    fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3713        for cursor in &mut layout.visible_cursors {
3714            cursor.paint(layout.content_origin, cx);
3715        }
3716    }
3717
3718    fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3719        let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
3720            return;
3721        };
3722
3723        let thumb_bounds = scrollbar_layout.thumb_bounds();
3724        if scrollbar_layout.visible {
3725            cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
3726                cx.paint_quad(quad(
3727                    scrollbar_layout.hitbox.bounds,
3728                    Corners::default(),
3729                    cx.theme().colors().scrollbar_track_background,
3730                    Edges {
3731                        top: Pixels::ZERO,
3732                        right: Pixels::ZERO,
3733                        bottom: Pixels::ZERO,
3734                        left: ScrollbarLayout::BORDER_WIDTH,
3735                    },
3736                    cx.theme().colors().scrollbar_track_border,
3737                ));
3738
3739                let fast_markers =
3740                    self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
3741                // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
3742                self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
3743
3744                let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
3745                for marker in markers.iter().chain(&fast_markers) {
3746                    let mut marker = marker.clone();
3747                    marker.bounds.origin += scrollbar_layout.hitbox.origin;
3748                    cx.paint_quad(marker);
3749                }
3750
3751                cx.paint_quad(quad(
3752                    thumb_bounds,
3753                    Corners::default(),
3754                    cx.theme().colors().scrollbar_thumb_background,
3755                    Edges {
3756                        top: Pixels::ZERO,
3757                        right: Pixels::ZERO,
3758                        bottom: Pixels::ZERO,
3759                        left: ScrollbarLayout::BORDER_WIDTH,
3760                    },
3761                    cx.theme().colors().scrollbar_thumb_border,
3762                ));
3763            });
3764        }
3765
3766        cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
3767
3768        let row_height = scrollbar_layout.row_height;
3769        let row_range = scrollbar_layout.visible_row_range.clone();
3770
3771        cx.on_mouse_event({
3772            let editor = self.editor.clone();
3773            let hitbox = scrollbar_layout.hitbox.clone();
3774            let mut mouse_position = cx.mouse_position();
3775            move |event: &MouseMoveEvent, phase, cx| {
3776                if phase == DispatchPhase::Capture {
3777                    return;
3778                }
3779
3780                editor.update(cx, |editor, cx| {
3781                    if event.pressed_button == Some(MouseButton::Left)
3782                        && editor.scroll_manager.is_dragging_scrollbar()
3783                    {
3784                        let y = mouse_position.y;
3785                        let new_y = event.position.y;
3786                        if (hitbox.top()..hitbox.bottom()).contains(&y) {
3787                            let mut position = editor.scroll_position(cx);
3788                            position.y += (new_y - y) / row_height;
3789                            if position.y < 0.0 {
3790                                position.y = 0.0;
3791                            }
3792                            editor.set_scroll_position(position, cx);
3793                        }
3794
3795                        cx.stop_propagation();
3796                    } else {
3797                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3798                        if hitbox.is_hovered(cx) {
3799                            editor.scroll_manager.show_scrollbar(cx);
3800                        }
3801                    }
3802                    mouse_position = event.position;
3803                })
3804            }
3805        });
3806
3807        if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
3808            cx.on_mouse_event({
3809                let editor = self.editor.clone();
3810                move |_: &MouseUpEvent, phase, cx| {
3811                    if phase == DispatchPhase::Capture {
3812                        return;
3813                    }
3814
3815                    editor.update(cx, |editor, cx| {
3816                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3817                        cx.stop_propagation();
3818                    });
3819                }
3820            });
3821        } else {
3822            cx.on_mouse_event({
3823                let editor = self.editor.clone();
3824                let hitbox = scrollbar_layout.hitbox.clone();
3825                move |event: &MouseDownEvent, phase, cx| {
3826                    if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
3827                        return;
3828                    }
3829
3830                    editor.update(cx, |editor, cx| {
3831                        editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
3832
3833                        let y = event.position.y;
3834                        if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
3835                            let center_row = ((y - hitbox.top()) / row_height).round() as u32;
3836                            let top_row = center_row
3837                                .saturating_sub((row_range.end - row_range.start) as u32 / 2);
3838                            let mut position = editor.scroll_position(cx);
3839                            position.y = top_row as f32;
3840                            editor.set_scroll_position(position, cx);
3841                        } else {
3842                            editor.scroll_manager.show_scrollbar(cx);
3843                        }
3844
3845                        cx.stop_propagation();
3846                    });
3847                }
3848            });
3849        }
3850    }
3851
3852    fn collect_fast_scrollbar_markers(
3853        &self,
3854        layout: &EditorLayout,
3855        scrollbar_layout: &ScrollbarLayout,
3856        cx: &mut WindowContext,
3857    ) -> Vec<PaintQuad> {
3858        const LIMIT: usize = 100;
3859        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
3860            return vec![];
3861        }
3862        let cursor_ranges = layout
3863            .cursors
3864            .iter()
3865            .map(|(point, color)| ColoredRange {
3866                start: point.row(),
3867                end: point.row(),
3868                color: *color,
3869            })
3870            .collect_vec();
3871        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
3872    }
3873
3874    fn refresh_slow_scrollbar_markers(
3875        &self,
3876        layout: &EditorLayout,
3877        scrollbar_layout: &ScrollbarLayout,
3878        cx: &mut WindowContext,
3879    ) {
3880        self.editor.update(cx, |editor, cx| {
3881            if !editor.is_singleton(cx)
3882                || !editor
3883                    .scrollbar_marker_state
3884                    .should_refresh(scrollbar_layout.hitbox.size)
3885            {
3886                return;
3887            }
3888
3889            let scrollbar_layout = scrollbar_layout.clone();
3890            let background_highlights = editor.background_highlights.clone();
3891            let snapshot = layout.position_map.snapshot.clone();
3892            let theme = cx.theme().clone();
3893            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
3894
3895            editor.scrollbar_marker_state.dirty = false;
3896            editor.scrollbar_marker_state.pending_refresh =
3897                Some(cx.spawn(|editor, mut cx| async move {
3898                    let scrollbar_size = scrollbar_layout.hitbox.size;
3899                    let scrollbar_markers = cx
3900                        .background_executor()
3901                        .spawn(async move {
3902                            let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
3903                            let mut marker_quads = Vec::new();
3904                            if scrollbar_settings.git_diff {
3905                                let marker_row_ranges = snapshot
3906                                    .diff_map
3907                                    .diff_hunks(&snapshot.buffer_snapshot)
3908                                    .map(|hunk| {
3909                                        let start_display_row =
3910                                            MultiBufferPoint::new(hunk.row_range.start.0, 0)
3911                                                .to_display_point(&snapshot.display_snapshot)
3912                                                .row();
3913                                        let mut end_display_row =
3914                                            MultiBufferPoint::new(hunk.row_range.end.0, 0)
3915                                                .to_display_point(&snapshot.display_snapshot)
3916                                                .row();
3917                                        if end_display_row != start_display_row {
3918                                            end_display_row.0 -= 1;
3919                                        }
3920                                        let color = match hunk_status(&hunk) {
3921                                            DiffHunkStatus::Added => theme.status().created,
3922                                            DiffHunkStatus::Modified => theme.status().modified,
3923                                            DiffHunkStatus::Removed => theme.status().deleted,
3924                                        };
3925                                        ColoredRange {
3926                                            start: start_display_row,
3927                                            end: end_display_row,
3928                                            color,
3929                                        }
3930                                    });
3931
3932                                marker_quads.extend(
3933                                    scrollbar_layout
3934                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
3935                                );
3936                            }
3937
3938                            for (background_highlight_id, (_, background_ranges)) in
3939                                background_highlights.iter()
3940                            {
3941                                let is_search_highlights = *background_highlight_id
3942                                    == TypeId::of::<BufferSearchHighlights>();
3943                                let is_symbol_occurrences = *background_highlight_id
3944                                    == TypeId::of::<DocumentHighlightRead>()
3945                                    || *background_highlight_id
3946                                        == TypeId::of::<DocumentHighlightWrite>();
3947                                if (is_search_highlights && scrollbar_settings.search_results)
3948                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
3949                                {
3950                                    let mut color = theme.status().info;
3951                                    if is_symbol_occurrences {
3952                                        color.fade_out(0.5);
3953                                    }
3954                                    let marker_row_ranges = background_ranges.iter().map(|range| {
3955                                        let display_start = range
3956                                            .start
3957                                            .to_display_point(&snapshot.display_snapshot);
3958                                        let display_end =
3959                                            range.end.to_display_point(&snapshot.display_snapshot);
3960                                        ColoredRange {
3961                                            start: display_start.row(),
3962                                            end: display_end.row(),
3963                                            color,
3964                                        }
3965                                    });
3966                                    marker_quads.extend(
3967                                        scrollbar_layout
3968                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
3969                                    );
3970                                }
3971                            }
3972
3973                            if scrollbar_settings.diagnostics {
3974                                let diagnostics = snapshot
3975                                    .buffer_snapshot
3976                                    .diagnostics_in_range::<_, Point>(
3977                                        Point::zero()..max_point,
3978                                        false,
3979                                    )
3980                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
3981                                    .sorted_by_key(|diagnostic| {
3982                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
3983                                    });
3984
3985                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
3986                                    let start_display = diagnostic
3987                                        .range
3988                                        .start
3989                                        .to_display_point(&snapshot.display_snapshot);
3990                                    let end_display = diagnostic
3991                                        .range
3992                                        .end
3993                                        .to_display_point(&snapshot.display_snapshot);
3994                                    let color = match diagnostic.diagnostic.severity {
3995                                        DiagnosticSeverity::ERROR => theme.status().error,
3996                                        DiagnosticSeverity::WARNING => theme.status().warning,
3997                                        DiagnosticSeverity::INFORMATION => theme.status().info,
3998                                        _ => theme.status().hint,
3999                                    };
4000                                    ColoredRange {
4001                                        start: start_display.row(),
4002                                        end: end_display.row(),
4003                                        color,
4004                                    }
4005                                });
4006                                marker_quads.extend(
4007                                    scrollbar_layout
4008                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
4009                                );
4010                            }
4011
4012                            Arc::from(marker_quads)
4013                        })
4014                        .await;
4015
4016                    editor.update(&mut cx, |editor, cx| {
4017                        editor.scrollbar_marker_state.markers = scrollbar_markers;
4018                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
4019                        editor.scrollbar_marker_state.pending_refresh = None;
4020                        cx.notify();
4021                    })?;
4022
4023                    Ok(())
4024                }));
4025        });
4026    }
4027
4028    #[allow(clippy::too_many_arguments)]
4029    fn paint_highlighted_range(
4030        &self,
4031        range: Range<DisplayPoint>,
4032        color: Hsla,
4033        corner_radius: Pixels,
4034        line_end_overshoot: Pixels,
4035        layout: &EditorLayout,
4036        cx: &mut WindowContext,
4037    ) {
4038        let start_row = layout.visible_display_row_range.start;
4039        let end_row = layout.visible_display_row_range.end;
4040        if range.start != range.end {
4041            let row_range = if range.end.column() == 0 {
4042                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
4043            } else {
4044                cmp::max(range.start.row(), start_row)
4045                    ..cmp::min(range.end.row().next_row(), end_row)
4046            };
4047
4048            let highlighted_range = HighlightedRange {
4049                color,
4050                line_height: layout.position_map.line_height,
4051                corner_radius,
4052                start_y: layout.content_origin.y
4053                    + row_range.start.as_f32() * layout.position_map.line_height
4054                    - layout.position_map.scroll_pixel_position.y,
4055                lines: row_range
4056                    .iter_rows()
4057                    .map(|row| {
4058                        let line_layout =
4059                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
4060                        HighlightedRangeLine {
4061                            start_x: if row == range.start.row() {
4062                                layout.content_origin.x
4063                                    + line_layout.x_for_index(range.start.column() as usize)
4064                                    - layout.position_map.scroll_pixel_position.x
4065                            } else {
4066                                layout.content_origin.x
4067                                    - layout.position_map.scroll_pixel_position.x
4068                            },
4069                            end_x: if row == range.end.row() {
4070                                layout.content_origin.x
4071                                    + line_layout.x_for_index(range.end.column() as usize)
4072                                    - layout.position_map.scroll_pixel_position.x
4073                            } else {
4074                                layout.content_origin.x + line_layout.width + line_end_overshoot
4075                                    - layout.position_map.scroll_pixel_position.x
4076                            },
4077                        }
4078                    })
4079                    .collect(),
4080            };
4081
4082            highlighted_range.paint(layout.text_hitbox.bounds, cx);
4083        }
4084    }
4085
4086    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4087        if let Some(mut inline_blame) = layout.inline_blame.take() {
4088            cx.paint_layer(layout.text_hitbox.bounds, |cx| {
4089                inline_blame.paint(cx);
4090            })
4091        }
4092    }
4093
4094    fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4095        for mut block in layout.blocks.drain(..) {
4096            block.element.paint(cx);
4097        }
4098    }
4099
4100    fn paint_inline_completion_popover(
4101        &mut self,
4102        layout: &mut EditorLayout,
4103        cx: &mut WindowContext,
4104    ) {
4105        if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
4106            inline_completion_popover.paint(cx);
4107        }
4108    }
4109
4110    fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4111        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
4112            mouse_context_menu.paint(cx);
4113        }
4114    }
4115
4116    fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
4117        cx.on_mouse_event({
4118            let position_map = layout.position_map.clone();
4119            let editor = self.editor.clone();
4120            let hitbox = layout.hitbox.clone();
4121            let mut delta = ScrollDelta::default();
4122
4123            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
4124            // accidentally turn off their scrolling.
4125            let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
4126
4127            move |event: &ScrollWheelEvent, phase, cx| {
4128                if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
4129                    delta = delta.coalesce(event.delta);
4130                    editor.update(cx, |editor, cx| {
4131                        let position_map: &PositionMap = &position_map;
4132
4133                        let line_height = position_map.line_height;
4134                        let max_glyph_width = position_map.em_width;
4135                        let (delta, axis) = match delta {
4136                            gpui::ScrollDelta::Pixels(mut pixels) => {
4137                                //Trackpad
4138                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
4139                                (pixels, axis)
4140                            }
4141
4142                            gpui::ScrollDelta::Lines(lines) => {
4143                                //Not trackpad
4144                                let pixels =
4145                                    point(lines.x * max_glyph_width, lines.y * line_height);
4146                                (pixels, None)
4147                            }
4148                        };
4149
4150                        let current_scroll_position = position_map.snapshot.scroll_position();
4151                        let x = (current_scroll_position.x * max_glyph_width
4152                            - (delta.x * scroll_sensitivity))
4153                            / max_glyph_width;
4154                        let y = (current_scroll_position.y * line_height
4155                            - (delta.y * scroll_sensitivity))
4156                            / line_height;
4157                        let mut scroll_position =
4158                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
4159                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
4160                        if forbid_vertical_scroll {
4161                            scroll_position.y = current_scroll_position.y;
4162                        }
4163
4164                        if scroll_position != current_scroll_position {
4165                            editor.scroll(scroll_position, axis, cx);
4166                            cx.stop_propagation();
4167                        } else if y < 0. {
4168                            // Due to clamping, we may fail to detect cases of overscroll to the top;
4169                            // We want the scroll manager to get an update in such cases and detect the change of direction
4170                            // on the next frame.
4171                            cx.notify();
4172                        }
4173                    });
4174                }
4175            }
4176        });
4177    }
4178
4179    fn paint_mouse_listeners(
4180        &mut self,
4181        layout: &EditorLayout,
4182        hovered_hunk: Option<HoveredHunk>,
4183        cx: &mut WindowContext,
4184    ) {
4185        self.paint_scroll_wheel_listener(layout, cx);
4186
4187        cx.on_mouse_event({
4188            let position_map = layout.position_map.clone();
4189            let editor = self.editor.clone();
4190            let text_hitbox = layout.text_hitbox.clone();
4191            let gutter_hitbox = layout.gutter_hitbox.clone();
4192
4193            move |event: &MouseDownEvent, phase, cx| {
4194                if phase == DispatchPhase::Bubble {
4195                    match event.button {
4196                        MouseButton::Left => editor.update(cx, |editor, cx| {
4197                            Self::mouse_left_down(
4198                                editor,
4199                                event,
4200                                hovered_hunk.clone(),
4201                                &position_map,
4202                                &text_hitbox,
4203                                &gutter_hitbox,
4204                                cx,
4205                            );
4206                        }),
4207                        MouseButton::Right => editor.update(cx, |editor, cx| {
4208                            Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
4209                        }),
4210                        MouseButton::Middle => editor.update(cx, |editor, cx| {
4211                            Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
4212                        }),
4213                        _ => {}
4214                    };
4215                }
4216            }
4217        });
4218
4219        cx.on_mouse_event({
4220            let editor = self.editor.clone();
4221            let position_map = layout.position_map.clone();
4222            let text_hitbox = layout.text_hitbox.clone();
4223
4224            move |event: &MouseUpEvent, phase, cx| {
4225                if phase == DispatchPhase::Bubble {
4226                    editor.update(cx, |editor, cx| {
4227                        Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
4228                    });
4229                }
4230            }
4231        });
4232        cx.on_mouse_event({
4233            let position_map = layout.position_map.clone();
4234            let editor = self.editor.clone();
4235            let text_hitbox = layout.text_hitbox.clone();
4236            let gutter_hitbox = layout.gutter_hitbox.clone();
4237
4238            move |event: &MouseMoveEvent, phase, cx| {
4239                if phase == DispatchPhase::Bubble {
4240                    editor.update(cx, |editor, cx| {
4241                        if editor.hover_state.focused(cx) {
4242                            return;
4243                        }
4244                        if event.pressed_button == Some(MouseButton::Left)
4245                            || event.pressed_button == Some(MouseButton::Middle)
4246                        {
4247                            Self::mouse_dragged(
4248                                editor,
4249                                event,
4250                                &position_map,
4251                                text_hitbox.bounds,
4252                                cx,
4253                            )
4254                        }
4255
4256                        Self::mouse_moved(
4257                            editor,
4258                            event,
4259                            &position_map,
4260                            &text_hitbox,
4261                            &gutter_hitbox,
4262                            cx,
4263                        )
4264                    });
4265                }
4266            }
4267        });
4268    }
4269
4270    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
4271        bounds.upper_right().x - self.style.scrollbar_width
4272    }
4273
4274    fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
4275        let style = &self.style;
4276        let font_size = style.text.font_size.to_pixels(cx.rem_size());
4277        let layout = cx
4278            .text_system()
4279            .shape_line(
4280                SharedString::from(" ".repeat(column)),
4281                font_size,
4282                &[TextRun {
4283                    len: column,
4284                    font: style.text.font(),
4285                    color: Hsla::default(),
4286                    background_color: None,
4287                    underline: None,
4288                    strikethrough: None,
4289                }],
4290            )
4291            .unwrap();
4292
4293        layout.width
4294    }
4295
4296    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
4297        let digit_count = (snapshot.widest_line_number() as f32).log10().floor() as usize + 1;
4298        self.column_pixels(digit_count, cx)
4299    }
4300}
4301
4302fn inline_completion_popover_text(
4303    edit_start: DisplayPoint,
4304    editor_snapshot: &EditorSnapshot,
4305    edits: &Vec<(Range<Anchor>, String)>,
4306    cx: &WindowContext,
4307) -> (String, Vec<(Range<usize>, HighlightStyle)>) {
4308    let mut text = String::new();
4309    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
4310    let mut highlights = Vec::new();
4311    for (old_range, new_text) in edits {
4312        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
4313        text.extend(
4314            editor_snapshot
4315                .buffer_snapshot
4316                .chunks(offset..old_offset_range.start, false)
4317                .map(|chunk| chunk.text),
4318        );
4319        offset = old_offset_range.end;
4320
4321        let start = text.len();
4322        text.push_str(new_text);
4323        let end = text.len();
4324        highlights.push((
4325            start..end,
4326            HighlightStyle {
4327                background_color: Some(cx.theme().status().created_background),
4328                ..Default::default()
4329            },
4330        ));
4331    }
4332    (text, highlights)
4333}
4334
4335fn all_edits_insertions_or_deletions(
4336    edits: &Vec<(Range<Anchor>, String)>,
4337    snapshot: &MultiBufferSnapshot,
4338) -> bool {
4339    let mut all_insertions = true;
4340    let mut all_deletions = true;
4341
4342    for (range, new_text) in edits.iter() {
4343        let range_is_empty = range.to_offset(&snapshot).is_empty();
4344        let text_is_empty = new_text.is_empty();
4345
4346        if range_is_empty != text_is_empty {
4347            if range_is_empty {
4348                all_deletions = false;
4349            } else {
4350                all_insertions = false;
4351            }
4352        } else {
4353            return false;
4354        }
4355
4356        if !all_insertions && !all_deletions {
4357            return false;
4358        }
4359    }
4360    all_insertions || all_deletions
4361}
4362
4363#[allow(clippy::too_many_arguments)]
4364fn prepaint_gutter_button(
4365    button: IconButton,
4366    row: DisplayRow,
4367    line_height: Pixels,
4368    gutter_dimensions: &GutterDimensions,
4369    scroll_pixel_position: gpui::Point<Pixels>,
4370    gutter_hitbox: &Hitbox,
4371    rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
4372    cx: &mut WindowContext<'_>,
4373) -> AnyElement {
4374    let mut button = button.into_any_element();
4375    let available_space = size(
4376        AvailableSpace::MinContent,
4377        AvailableSpace::Definite(line_height),
4378    );
4379    let indicator_size = button.layout_as_root(available_space, cx);
4380
4381    let blame_width = gutter_dimensions.git_blame_entries_width;
4382    let gutter_width = rows_with_hunk_bounds
4383        .get(&row)
4384        .map(|bounds| bounds.size.width);
4385    let left_offset = blame_width.max(gutter_width).unwrap_or_default();
4386
4387    let mut x = left_offset;
4388    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
4389        - indicator_size.width
4390        - left_offset;
4391    x += available_width / 2.;
4392
4393    let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
4394    y += (line_height - indicator_size.height) / 2.;
4395
4396    button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
4397    button
4398}
4399
4400fn render_inline_blame_entry(
4401    blame: &gpui::Model<GitBlame>,
4402    blame_entry: BlameEntry,
4403    style: &EditorStyle,
4404    workspace: Option<WeakView<Workspace>>,
4405    cx: &mut WindowContext<'_>,
4406) -> AnyElement {
4407    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
4408
4409    let author = blame_entry.author.as_deref().unwrap_or_default();
4410    let summary_enabled = ProjectSettings::get_global(cx)
4411        .git
4412        .show_inline_commit_summary();
4413
4414    let text = match blame_entry.summary.as_ref() {
4415        Some(summary) if summary_enabled => {
4416            format!("{}, {} - {}", author, relative_timestamp, summary)
4417        }
4418        _ => format!("{}, {}", author, relative_timestamp),
4419    };
4420
4421    let details = blame.read(cx).details_for_entry(&blame_entry);
4422
4423    let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
4424
4425    h_flex()
4426        .id("inline-blame")
4427        .w_full()
4428        .font_family(style.text.font().family)
4429        .text_color(cx.theme().status().hint)
4430        .line_height(style.text.line_height)
4431        .child(Icon::new(IconName::FileGit).color(Color::Hint))
4432        .child(text)
4433        .gap_2()
4434        .hoverable_tooltip(move |_| tooltip.clone().into())
4435        .into_any()
4436}
4437
4438fn render_blame_entry(
4439    ix: usize,
4440    blame: &gpui::Model<GitBlame>,
4441    blame_entry: BlameEntry,
4442    style: &EditorStyle,
4443    last_used_color: &mut Option<(PlayerColor, Oid)>,
4444    editor: View<Editor>,
4445    cx: &mut WindowContext<'_>,
4446) -> AnyElement {
4447    let mut sha_color = cx
4448        .theme()
4449        .players()
4450        .color_for_participant(blame_entry.sha.into());
4451    // If the last color we used is the same as the one we get for this line, but
4452    // the commit SHAs are different, then we try again to get a different color.
4453    match *last_used_color {
4454        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
4455            let index: u32 = blame_entry.sha.into();
4456            sha_color = cx.theme().players().color_for_participant(index + 1);
4457        }
4458        _ => {}
4459    };
4460    last_used_color.replace((sha_color, blame_entry.sha));
4461
4462    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
4463
4464    let short_commit_id = blame_entry.sha.display_short();
4465
4466    let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
4467    let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
4468
4469    let details = blame.read(cx).details_for_entry(&blame_entry);
4470
4471    let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
4472
4473    let tooltip = cx.new_view(|_| {
4474        BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
4475    });
4476
4477    h_flex()
4478        .w_full()
4479        .justify_between()
4480        .font_family(style.text.font().family)
4481        .line_height(style.text.line_height)
4482        .id(("blame", ix))
4483        .text_color(cx.theme().status().hint)
4484        .pr_2()
4485        .gap_2()
4486        .child(
4487            h_flex()
4488                .items_center()
4489                .gap_2()
4490                .child(div().text_color(sha_color.cursor).child(short_commit_id))
4491                .child(name),
4492        )
4493        .child(relative_timestamp)
4494        .on_mouse_down(MouseButton::Right, {
4495            let blame_entry = blame_entry.clone();
4496            let details = details.clone();
4497            move |event, cx| {
4498                deploy_blame_entry_context_menu(
4499                    &blame_entry,
4500                    details.as_ref(),
4501                    editor.clone(),
4502                    event.position,
4503                    cx,
4504                );
4505            }
4506        })
4507        .hover(|style| style.bg(cx.theme().colors().element_hover))
4508        .when_some(
4509            details.and_then(|details| details.permalink),
4510            |this, url| {
4511                let url = url.clone();
4512                this.cursor_pointer().on_click(move |_, cx| {
4513                    cx.stop_propagation();
4514                    cx.open_url(url.as_str())
4515                })
4516            },
4517        )
4518        .hoverable_tooltip(move |_| tooltip.clone().into())
4519        .into_any()
4520}
4521
4522fn deploy_blame_entry_context_menu(
4523    blame_entry: &BlameEntry,
4524    details: Option<&CommitDetails>,
4525    editor: View<Editor>,
4526    position: gpui::Point<Pixels>,
4527    cx: &mut WindowContext<'_>,
4528) {
4529    let context_menu = ContextMenu::build(cx, move |menu, _| {
4530        let sha = format!("{}", blame_entry.sha);
4531        menu.on_blur_subscription(Subscription::new(|| {}))
4532            .entry("Copy commit SHA", None, move |cx| {
4533                cx.write_to_clipboard(ClipboardItem::new_string(sha.clone()));
4534            })
4535            .when_some(
4536                details.and_then(|details| details.permalink.clone()),
4537                |this, url| this.entry("Open permalink", None, move |cx| cx.open_url(url.as_str())),
4538            )
4539    });
4540
4541    editor.update(cx, move |editor, cx| {
4542        editor.mouse_context_menu = Some(MouseContextMenu::new(
4543            MenuPosition::PinnedToScreen(position),
4544            context_menu,
4545            cx,
4546        ));
4547        cx.notify();
4548    });
4549}
4550
4551#[derive(Debug)]
4552pub(crate) struct LineWithInvisibles {
4553    fragments: SmallVec<[LineFragment; 1]>,
4554    invisibles: Vec<Invisible>,
4555    len: usize,
4556    width: Pixels,
4557    font_size: Pixels,
4558}
4559
4560#[allow(clippy::large_enum_variant)]
4561enum LineFragment {
4562    Text(ShapedLine),
4563    Element {
4564        element: Option<AnyElement>,
4565        size: Size<Pixels>,
4566        len: usize,
4567    },
4568}
4569
4570impl fmt::Debug for LineFragment {
4571    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4572        match self {
4573            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
4574            LineFragment::Element { size, len, .. } => f
4575                .debug_struct("Element")
4576                .field("size", size)
4577                .field("len", len)
4578                .finish(),
4579        }
4580    }
4581}
4582
4583impl LineWithInvisibles {
4584    #[allow(clippy::too_many_arguments)]
4585    fn from_chunks<'a>(
4586        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
4587        editor_style: &EditorStyle,
4588        max_line_len: usize,
4589        max_line_count: usize,
4590        editor_mode: EditorMode,
4591        text_width: Pixels,
4592        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
4593        cx: &mut WindowContext,
4594    ) -> Vec<Self> {
4595        let text_style = &editor_style.text;
4596        let mut layouts = Vec::with_capacity(max_line_count);
4597        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
4598        let mut line = String::new();
4599        let mut invisibles = Vec::new();
4600        let mut width = Pixels::ZERO;
4601        let mut len = 0;
4602        let mut styles = Vec::new();
4603        let mut non_whitespace_added = false;
4604        let mut row = 0;
4605        let mut line_exceeded_max_len = false;
4606        let font_size = text_style.font_size.to_pixels(cx.rem_size());
4607
4608        let ellipsis = SharedString::from("");
4609
4610        for highlighted_chunk in chunks.chain([HighlightedChunk {
4611            text: "\n",
4612            style: None,
4613            is_tab: false,
4614            replacement: None,
4615        }]) {
4616            if let Some(replacement) = highlighted_chunk.replacement {
4617                if !line.is_empty() {
4618                    let shaped_line = cx
4619                        .text_system()
4620                        .shape_line(line.clone().into(), font_size, &styles)
4621                        .unwrap();
4622                    width += shaped_line.width;
4623                    len += shaped_line.len;
4624                    fragments.push(LineFragment::Text(shaped_line));
4625                    line.clear();
4626                    styles.clear();
4627                }
4628
4629                match replacement {
4630                    ChunkReplacement::Renderer(renderer) => {
4631                        let available_width = if renderer.constrain_width {
4632                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
4633                                ellipsis.clone()
4634                            } else {
4635                                SharedString::from(Arc::from(highlighted_chunk.text))
4636                            };
4637                            let shaped_line = cx
4638                                .text_system()
4639                                .shape_line(
4640                                    chunk,
4641                                    font_size,
4642                                    &[text_style.to_run(highlighted_chunk.text.len())],
4643                                )
4644                                .unwrap();
4645                            AvailableSpace::Definite(shaped_line.width)
4646                        } else {
4647                            AvailableSpace::MinContent
4648                        };
4649
4650                        let mut element = (renderer.render)(&mut ChunkRendererContext {
4651                            context: cx,
4652                            max_width: text_width,
4653                        });
4654                        let line_height = text_style.line_height_in_pixels(cx.rem_size());
4655                        let size = element.layout_as_root(
4656                            size(available_width, AvailableSpace::Definite(line_height)),
4657                            cx,
4658                        );
4659
4660                        width += size.width;
4661                        len += highlighted_chunk.text.len();
4662                        fragments.push(LineFragment::Element {
4663                            element: Some(element),
4664                            size,
4665                            len: highlighted_chunk.text.len(),
4666                        });
4667                    }
4668                    ChunkReplacement::Str(x) => {
4669                        let text_style = if let Some(style) = highlighted_chunk.style {
4670                            Cow::Owned(text_style.clone().highlight(style))
4671                        } else {
4672                            Cow::Borrowed(text_style)
4673                        };
4674
4675                        let run = TextRun {
4676                            len: x.len(),
4677                            font: text_style.font(),
4678                            color: text_style.color,
4679                            background_color: text_style.background_color,
4680                            underline: text_style.underline,
4681                            strikethrough: text_style.strikethrough,
4682                        };
4683                        let line_layout = cx
4684                            .text_system()
4685                            .shape_line(x, font_size, &[run])
4686                            .unwrap()
4687                            .with_len(highlighted_chunk.text.len());
4688
4689                        width += line_layout.width;
4690                        len += highlighted_chunk.text.len();
4691                        fragments.push(LineFragment::Text(line_layout))
4692                    }
4693                }
4694            } else {
4695                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
4696                    if ix > 0 {
4697                        let shaped_line = cx
4698                            .text_system()
4699                            .shape_line(line.clone().into(), font_size, &styles)
4700                            .unwrap();
4701                        width += shaped_line.width;
4702                        len += shaped_line.len;
4703                        fragments.push(LineFragment::Text(shaped_line));
4704                        layouts.push(Self {
4705                            width: mem::take(&mut width),
4706                            len: mem::take(&mut len),
4707                            fragments: mem::take(&mut fragments),
4708                            invisibles: std::mem::take(&mut invisibles),
4709                            font_size,
4710                        });
4711
4712                        line.clear();
4713                        styles.clear();
4714                        row += 1;
4715                        line_exceeded_max_len = false;
4716                        non_whitespace_added = false;
4717                        if row == max_line_count {
4718                            return layouts;
4719                        }
4720                    }
4721
4722                    if !line_chunk.is_empty() && !line_exceeded_max_len {
4723                        let text_style = if let Some(style) = highlighted_chunk.style {
4724                            Cow::Owned(text_style.clone().highlight(style))
4725                        } else {
4726                            Cow::Borrowed(text_style)
4727                        };
4728
4729                        if line.len() + line_chunk.len() > max_line_len {
4730                            let mut chunk_len = max_line_len - line.len();
4731                            while !line_chunk.is_char_boundary(chunk_len) {
4732                                chunk_len -= 1;
4733                            }
4734                            line_chunk = &line_chunk[..chunk_len];
4735                            line_exceeded_max_len = true;
4736                        }
4737
4738                        styles.push(TextRun {
4739                            len: line_chunk.len(),
4740                            font: text_style.font(),
4741                            color: text_style.color,
4742                            background_color: text_style.background_color,
4743                            underline: text_style.underline,
4744                            strikethrough: text_style.strikethrough,
4745                        });
4746
4747                        if editor_mode == EditorMode::Full {
4748                            // Line wrap pads its contents with fake whitespaces,
4749                            // avoid printing them
4750                            let is_soft_wrapped = is_row_soft_wrapped(row);
4751                            if highlighted_chunk.is_tab {
4752                                if non_whitespace_added || !is_soft_wrapped {
4753                                    invisibles.push(Invisible::Tab {
4754                                        line_start_offset: line.len(),
4755                                        line_end_offset: line.len() + line_chunk.len(),
4756                                    });
4757                                }
4758                            } else {
4759                                invisibles.extend(
4760                                    line_chunk
4761                                        .bytes()
4762                                        .enumerate()
4763                                        .filter(|(_, line_byte)| {
4764                                            let is_whitespace =
4765                                                (*line_byte as char).is_whitespace();
4766                                            non_whitespace_added |= !is_whitespace;
4767                                            is_whitespace
4768                                                && (non_whitespace_added || !is_soft_wrapped)
4769                                        })
4770                                        .map(|(whitespace_index, _)| Invisible::Whitespace {
4771                                            line_offset: line.len() + whitespace_index,
4772                                        }),
4773                                )
4774                            }
4775                        }
4776
4777                        line.push_str(line_chunk);
4778                    }
4779                }
4780            }
4781        }
4782
4783        layouts
4784    }
4785
4786    fn prepaint(
4787        &mut self,
4788        line_height: Pixels,
4789        scroll_pixel_position: gpui::Point<Pixels>,
4790        row: DisplayRow,
4791        content_origin: gpui::Point<Pixels>,
4792        line_elements: &mut SmallVec<[AnyElement; 1]>,
4793        cx: &mut WindowContext,
4794    ) {
4795        let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
4796        let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
4797        for fragment in &mut self.fragments {
4798            match fragment {
4799                LineFragment::Text(line) => {
4800                    fragment_origin.x += line.width;
4801                }
4802                LineFragment::Element { element, size, .. } => {
4803                    let mut element = element
4804                        .take()
4805                        .expect("you can't prepaint LineWithInvisibles twice");
4806
4807                    // Center the element vertically within the line.
4808                    let mut element_origin = fragment_origin;
4809                    element_origin.y += (line_height - size.height) / 2.;
4810                    element.prepaint_at(element_origin, cx);
4811                    line_elements.push(element);
4812
4813                    fragment_origin.x += size.width;
4814                }
4815            }
4816        }
4817    }
4818
4819    fn draw(
4820        &self,
4821        layout: &EditorLayout,
4822        row: DisplayRow,
4823        content_origin: gpui::Point<Pixels>,
4824        whitespace_setting: ShowWhitespaceSetting,
4825        selection_ranges: &[Range<DisplayPoint>],
4826        cx: &mut WindowContext,
4827    ) {
4828        let line_height = layout.position_map.line_height;
4829        let line_y = line_height
4830            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
4831
4832        let mut fragment_origin =
4833            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
4834
4835        for fragment in &self.fragments {
4836            match fragment {
4837                LineFragment::Text(line) => {
4838                    line.paint(fragment_origin, line_height, cx).log_err();
4839                    fragment_origin.x += line.width;
4840                }
4841                LineFragment::Element { size, .. } => {
4842                    fragment_origin.x += size.width;
4843                }
4844            }
4845        }
4846
4847        self.draw_invisibles(
4848            selection_ranges,
4849            layout,
4850            content_origin,
4851            line_y,
4852            row,
4853            line_height,
4854            whitespace_setting,
4855            cx,
4856        );
4857    }
4858
4859    #[allow(clippy::too_many_arguments)]
4860    fn draw_invisibles(
4861        &self,
4862        selection_ranges: &[Range<DisplayPoint>],
4863        layout: &EditorLayout,
4864        content_origin: gpui::Point<Pixels>,
4865        line_y: Pixels,
4866        row: DisplayRow,
4867        line_height: Pixels,
4868        whitespace_setting: ShowWhitespaceSetting,
4869        cx: &mut WindowContext,
4870    ) {
4871        let extract_whitespace_info = |invisible: &Invisible| {
4872            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
4873                Invisible::Tab {
4874                    line_start_offset,
4875                    line_end_offset,
4876                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
4877                Invisible::Whitespace { line_offset } => {
4878                    (*line_offset, line_offset + 1, &layout.space_invisible)
4879                }
4880            };
4881
4882            let x_offset = self.x_for_index(token_offset);
4883            let invisible_offset =
4884                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
4885            let origin = content_origin
4886                + gpui::point(
4887                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
4888                    line_y,
4889                );
4890
4891            (
4892                [token_offset, token_end_offset],
4893                Box::new(move |cx: &mut WindowContext| {
4894                    invisible_symbol.paint(origin, line_height, cx).log_err();
4895                }),
4896            )
4897        };
4898
4899        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
4900        match whitespace_setting {
4901            ShowWhitespaceSetting::None => (),
4902            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(cx)),
4903            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
4904                let invisible_point = DisplayPoint::new(row, start as u32);
4905                if !selection_ranges
4906                    .iter()
4907                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
4908                {
4909                    return;
4910                }
4911
4912                paint(cx);
4913            }),
4914
4915            // For a whitespace to be on a boundary, any of the following conditions need to be met:
4916            // - It is a tab
4917            // - It is adjacent to an edge (start or end)
4918            // - It is adjacent to a whitespace (left or right)
4919            ShowWhitespaceSetting::Boundary => {
4920                // 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
4921                // the above cases.
4922                // Note: We zip in the original `invisibles` to check for tab equality
4923                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut WindowContext)>)> = None;
4924                for (([start, end], paint), invisible) in
4925                    invisible_iter.zip_eq(self.invisibles.iter())
4926                {
4927                    let should_render = match (&last_seen, invisible) {
4928                        (_, Invisible::Tab { .. }) => true,
4929                        (Some((_, last_end, _)), _) => *last_end == start,
4930                        _ => false,
4931                    };
4932
4933                    if should_render || start == 0 || end == self.len {
4934                        paint(cx);
4935
4936                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
4937                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
4938                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
4939                            // Note that we need to make sure that the last one is actually adjacent
4940                            if !should_render_last && last_end == start {
4941                                paint_last(cx);
4942                            }
4943                        }
4944                    }
4945
4946                    // Manually render anything within a selection
4947                    let invisible_point = DisplayPoint::new(row, start as u32);
4948                    if selection_ranges.iter().any(|region| {
4949                        region.start <= invisible_point && invisible_point < region.end
4950                    }) {
4951                        paint(cx);
4952                    }
4953
4954                    last_seen = Some((should_render, end, paint));
4955                }
4956            }
4957        }
4958    }
4959
4960    pub fn x_for_index(&self, index: usize) -> Pixels {
4961        let mut fragment_start_x = Pixels::ZERO;
4962        let mut fragment_start_index = 0;
4963
4964        for fragment in &self.fragments {
4965            match fragment {
4966                LineFragment::Text(shaped_line) => {
4967                    let fragment_end_index = fragment_start_index + shaped_line.len;
4968                    if index < fragment_end_index {
4969                        return fragment_start_x
4970                            + shaped_line.x_for_index(index - fragment_start_index);
4971                    }
4972                    fragment_start_x += shaped_line.width;
4973                    fragment_start_index = fragment_end_index;
4974                }
4975                LineFragment::Element { len, size, .. } => {
4976                    let fragment_end_index = fragment_start_index + len;
4977                    if index < fragment_end_index {
4978                        return fragment_start_x;
4979                    }
4980                    fragment_start_x += size.width;
4981                    fragment_start_index = fragment_end_index;
4982                }
4983            }
4984        }
4985
4986        fragment_start_x
4987    }
4988
4989    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
4990        let mut fragment_start_x = Pixels::ZERO;
4991        let mut fragment_start_index = 0;
4992
4993        for fragment in &self.fragments {
4994            match fragment {
4995                LineFragment::Text(shaped_line) => {
4996                    let fragment_end_x = fragment_start_x + shaped_line.width;
4997                    if x < fragment_end_x {
4998                        return Some(
4999                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
5000                        );
5001                    }
5002                    fragment_start_x = fragment_end_x;
5003                    fragment_start_index += shaped_line.len;
5004                }
5005                LineFragment::Element { len, size, .. } => {
5006                    let fragment_end_x = fragment_start_x + size.width;
5007                    if x < fragment_end_x {
5008                        return Some(fragment_start_index);
5009                    }
5010                    fragment_start_index += len;
5011                    fragment_start_x = fragment_end_x;
5012                }
5013            }
5014        }
5015
5016        None
5017    }
5018
5019    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
5020        let mut fragment_start_index = 0;
5021
5022        for fragment in &self.fragments {
5023            match fragment {
5024                LineFragment::Text(shaped_line) => {
5025                    let fragment_end_index = fragment_start_index + shaped_line.len;
5026                    if index < fragment_end_index {
5027                        return shaped_line.font_id_for_index(index - fragment_start_index);
5028                    }
5029                    fragment_start_index = fragment_end_index;
5030                }
5031                LineFragment::Element { len, .. } => {
5032                    let fragment_end_index = fragment_start_index + len;
5033                    if index < fragment_end_index {
5034                        return None;
5035                    }
5036                    fragment_start_index = fragment_end_index;
5037                }
5038            }
5039        }
5040
5041        None
5042    }
5043}
5044
5045#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5046enum Invisible {
5047    /// A tab character
5048    ///
5049    /// A tab character is internally represented by spaces (configured by the user's tab width)
5050    /// aligned to the nearest column, so it's necessary to store the start and end offset for
5051    /// adjacency checks.
5052    Tab {
5053        line_start_offset: usize,
5054        line_end_offset: usize,
5055    },
5056    Whitespace {
5057        line_offset: usize,
5058    },
5059}
5060
5061impl EditorElement {
5062    /// Returns the rem size to use when rendering the [`EditorElement`].
5063    ///
5064    /// This allows UI elements to scale based on the `buffer_font_size`.
5065    fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
5066        match self.editor.read(cx).mode {
5067            EditorMode::Full => {
5068                let buffer_font_size = self.style.text.font_size;
5069                match buffer_font_size {
5070                    AbsoluteLength::Pixels(pixels) => {
5071                        let rem_size_scale = {
5072                            // Our default UI font size is 14px on a 16px base scale.
5073                            // This means the default UI font size is 0.875rems.
5074                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
5075
5076                            // We then determine the delta between a single rem and the default font
5077                            // size scale.
5078                            let default_font_size_delta = 1. - default_font_size_scale;
5079
5080                            // Finally, we add this delta to 1rem to get the scale factor that
5081                            // should be used to scale up the UI.
5082                            1. + default_font_size_delta
5083                        };
5084
5085                        Some(pixels * rem_size_scale)
5086                    }
5087                    AbsoluteLength::Rems(rems) => {
5088                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
5089                    }
5090                }
5091            }
5092            // We currently use single-line and auto-height editors in UI contexts,
5093            // so we don't want to scale everything with the buffer font size, as it
5094            // ends up looking off.
5095            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
5096        }
5097    }
5098}
5099
5100impl Element for EditorElement {
5101    type RequestLayoutState = ();
5102    type PrepaintState = EditorLayout;
5103
5104    fn id(&self) -> Option<ElementId> {
5105        None
5106    }
5107
5108    fn request_layout(
5109        &mut self,
5110        _: Option<&GlobalElementId>,
5111        cx: &mut WindowContext,
5112    ) -> (gpui::LayoutId, ()) {
5113        let rem_size = self.rem_size(cx);
5114        cx.with_rem_size(rem_size, |cx| {
5115            self.editor.update(cx, |editor, cx| {
5116                editor.set_style(self.style.clone(), cx);
5117
5118                let layout_id = match editor.mode {
5119                    EditorMode::SingleLine { auto_width } => {
5120                        let rem_size = cx.rem_size();
5121
5122                        let height = self.style.text.line_height_in_pixels(rem_size);
5123                        if auto_width {
5124                            let editor_handle = cx.view().clone();
5125                            let style = self.style.clone();
5126                            cx.request_measured_layout(Style::default(), move |_, _, cx| {
5127                                let editor_snapshot =
5128                                    editor_handle.update(cx, |editor, cx| editor.snapshot(cx));
5129                                let line = Self::layout_lines(
5130                                    DisplayRow(0)..DisplayRow(1),
5131                                    &editor_snapshot,
5132                                    &style,
5133                                    px(f32::MAX),
5134                                    |_| false, // Single lines never soft wrap
5135                                    cx,
5136                                )
5137                                .pop()
5138                                .unwrap();
5139
5140                                let font_id = cx.text_system().resolve_font(&style.text.font());
5141                                let font_size = style.text.font_size.to_pixels(cx.rem_size());
5142                                let em_width = cx
5143                                    .text_system()
5144                                    .typographic_bounds(font_id, font_size, 'm')
5145                                    .unwrap()
5146                                    .size
5147                                    .width;
5148
5149                                size(line.width + em_width, height)
5150                            })
5151                        } else {
5152                            let mut style = Style::default();
5153                            style.size.height = height.into();
5154                            style.size.width = relative(1.).into();
5155                            cx.request_layout(style, None)
5156                        }
5157                    }
5158                    EditorMode::AutoHeight { max_lines } => {
5159                        let editor_handle = cx.view().clone();
5160                        let max_line_number_width =
5161                            self.max_line_number_width(&editor.snapshot(cx), cx);
5162                        cx.request_measured_layout(
5163                            Style::default(),
5164                            move |known_dimensions, available_space, cx| {
5165                                editor_handle
5166                                    .update(cx, |editor, cx| {
5167                                        compute_auto_height_layout(
5168                                            editor,
5169                                            max_lines,
5170                                            max_line_number_width,
5171                                            known_dimensions,
5172                                            available_space.width,
5173                                            cx,
5174                                        )
5175                                    })
5176                                    .unwrap_or_default()
5177                            },
5178                        )
5179                    }
5180                    EditorMode::Full => {
5181                        let mut style = Style::default();
5182                        style.size.width = relative(1.).into();
5183                        style.size.height = relative(1.).into();
5184                        cx.request_layout(style, None)
5185                    }
5186                };
5187
5188                (layout_id, ())
5189            })
5190        })
5191    }
5192
5193    fn prepaint(
5194        &mut self,
5195        _: Option<&GlobalElementId>,
5196        bounds: Bounds<Pixels>,
5197        _: &mut Self::RequestLayoutState,
5198        cx: &mut WindowContext,
5199    ) -> Self::PrepaintState {
5200        let text_style = TextStyleRefinement {
5201            font_size: Some(self.style.text.font_size),
5202            line_height: Some(self.style.text.line_height),
5203            ..Default::default()
5204        };
5205        let focus_handle = self.editor.focus_handle(cx);
5206        cx.set_view_id(self.editor.entity_id());
5207        cx.set_focus_handle(&focus_handle);
5208
5209        let rem_size = self.rem_size(cx);
5210        cx.with_rem_size(rem_size, |cx| {
5211            cx.with_text_style(Some(text_style), |cx| {
5212                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5213                    let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
5214                    let style = self.style.clone();
5215
5216                    let font_id = cx.text_system().resolve_font(&style.text.font());
5217                    let font_size = style.text.font_size.to_pixels(cx.rem_size());
5218                    let line_height = style.text.line_height_in_pixels(cx.rem_size());
5219                    let em_width = cx
5220                        .text_system()
5221                        .typographic_bounds(font_id, font_size, 'm')
5222                        .unwrap()
5223                        .size
5224                        .width;
5225                    let em_advance = cx
5226                        .text_system()
5227                        .advance(font_id, font_size, 'm')
5228                        .unwrap()
5229                        .width;
5230
5231                    let gutter_dimensions = snapshot.gutter_dimensions(
5232                        font_id,
5233                        font_size,
5234                        em_width,
5235                        em_advance,
5236                        self.max_line_number_width(&snapshot, cx),
5237                        cx,
5238                    );
5239                    let text_width = bounds.size.width - gutter_dimensions.width;
5240
5241                    let right_margin = if snapshot.mode == EditorMode::Full {
5242                        EditorElement::SCROLLBAR_WIDTH
5243                    } else {
5244                        px(0.)
5245                    };
5246                    let overscroll = size(em_width + right_margin, px(0.));
5247
5248                    let editor_width =
5249                        text_width - gutter_dimensions.margin - overscroll.width - em_width;
5250
5251                    snapshot = self.editor.update(cx, |editor, cx| {
5252                        editor.last_bounds = Some(bounds);
5253                        editor.gutter_dimensions = gutter_dimensions;
5254                        editor.set_visible_line_count(bounds.size.height / line_height, cx);
5255
5256                        if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
5257                            snapshot
5258                        } else {
5259                            let wrap_width = match editor.soft_wrap_mode(cx) {
5260                                SoftWrap::GitDiff => None,
5261                                SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
5262                                SoftWrap::EditorWidth => Some(editor_width),
5263                                SoftWrap::Column(column) => Some(column as f32 * em_advance),
5264                                SoftWrap::Bounded(column) => {
5265                                    Some(editor_width.min(column as f32 * em_advance))
5266                                }
5267                            };
5268
5269                            if editor.set_wrap_width(wrap_width, cx) {
5270                                editor.snapshot(cx)
5271                            } else {
5272                                snapshot
5273                            }
5274                        }
5275                    });
5276
5277                    let wrap_guides = self
5278                        .editor
5279                        .read(cx)
5280                        .wrap_guides(cx)
5281                        .iter()
5282                        .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
5283                        .collect::<SmallVec<[_; 2]>>();
5284
5285                    let hitbox = cx.insert_hitbox(bounds, false);
5286                    let gutter_hitbox =
5287                        cx.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
5288                    let text_hitbox = cx.insert_hitbox(
5289                        Bounds {
5290                            origin: gutter_hitbox.upper_right(),
5291                            size: size(text_width, bounds.size.height),
5292                        },
5293                        false,
5294                    );
5295                    // Offset the content_bounds from the text_bounds by the gutter margin (which
5296                    // is roughly half a character wide) to make hit testing work more like how we want.
5297                    let content_origin =
5298                        text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
5299
5300                    let height_in_lines = bounds.size.height / line_height;
5301                    let max_row = snapshot.max_point().row().as_f32();
5302                    let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
5303                        (max_row - height_in_lines + 1.).max(0.)
5304                    } else {
5305                        let settings = EditorSettings::get_global(cx);
5306                        match settings.scroll_beyond_last_line {
5307                            ScrollBeyondLastLine::OnePage => max_row,
5308                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
5309                            ScrollBeyondLastLine::VerticalScrollMargin => {
5310                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
5311                                    .max(0.)
5312                            }
5313                        }
5314                    };
5315
5316                    let mut autoscroll_request = None;
5317                    let mut autoscroll_containing_element = false;
5318                    let mut autoscroll_horizontally = false;
5319                    self.editor.update(cx, |editor, cx| {
5320                        autoscroll_request = editor.autoscroll_request();
5321                        autoscroll_containing_element =
5322                            autoscroll_request.is_some() || editor.has_pending_selection();
5323                        autoscroll_horizontally =
5324                            editor.autoscroll_vertically(bounds, line_height, max_scroll_top, cx);
5325                        snapshot = editor.snapshot(cx);
5326                    });
5327
5328                    let mut scroll_position = snapshot.scroll_position();
5329                    // The scroll position is a fractional point, the whole number of which represents
5330                    // the top of the window in terms of display rows.
5331                    let start_row = DisplayRow(scroll_position.y as u32);
5332                    let max_row = snapshot.max_point().row();
5333                    let end_row = cmp::min(
5334                        (scroll_position.y + height_in_lines).ceil() as u32,
5335                        max_row.next_row().0,
5336                    );
5337                    let end_row = DisplayRow(end_row);
5338
5339                    let buffer_rows = snapshot
5340                        .buffer_rows(start_row)
5341                        .take((start_row..end_row).len())
5342                        .collect::<Vec<_>>();
5343                    let is_row_soft_wrapped =
5344                        |row| buffer_rows.get(row).copied().flatten().is_none();
5345
5346                    let start_anchor = if start_row == Default::default() {
5347                        Anchor::min()
5348                    } else {
5349                        snapshot.buffer_snapshot.anchor_before(
5350                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
5351                        )
5352                    };
5353                    let end_anchor = if end_row > max_row {
5354                        Anchor::max()
5355                    } else {
5356                        snapshot.buffer_snapshot.anchor_before(
5357                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
5358                        )
5359                    };
5360
5361                    let highlighted_rows = self
5362                        .editor
5363                        .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
5364                    let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
5365                        start_anchor..end_anchor,
5366                        &snapshot.display_snapshot,
5367                        cx.theme().colors(),
5368                    );
5369                    let highlighted_gutter_ranges =
5370                        self.editor.read(cx).gutter_highlights_in_range(
5371                            start_anchor..end_anchor,
5372                            &snapshot.display_snapshot,
5373                            cx,
5374                        );
5375
5376                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
5377                        start_anchor..end_anchor,
5378                        &snapshot.display_snapshot,
5379                        cx,
5380                    );
5381
5382                    let local_selections: Vec<Selection<Point>> =
5383                        self.editor.update(cx, |editor, cx| {
5384                            let mut selections = editor
5385                                .selections
5386                                .disjoint_in_range(start_anchor..end_anchor, cx);
5387                            selections.extend(editor.selections.pending(cx));
5388                            selections
5389                        });
5390
5391                    let (selections, active_rows, newest_selection_head) = self.layout_selections(
5392                        start_anchor,
5393                        end_anchor,
5394                        &local_selections,
5395                        &snapshot,
5396                        start_row,
5397                        end_row,
5398                        cx,
5399                    );
5400
5401                    let line_numbers = self.layout_line_numbers(
5402                        start_row..end_row,
5403                        buffer_rows.iter().copied(),
5404                        &active_rows,
5405                        newest_selection_head,
5406                        &snapshot,
5407                        cx,
5408                    );
5409
5410                    let mut crease_toggles = cx.with_element_namespace("crease_toggles", |cx| {
5411                        self.layout_crease_toggles(
5412                            start_row..end_row,
5413                            buffer_rows.iter().copied(),
5414                            &active_rows,
5415                            &snapshot,
5416                            cx,
5417                        )
5418                    });
5419                    let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
5420                        self.layout_crease_trailers(buffer_rows.iter().copied(), &snapshot, cx)
5421                    });
5422
5423                    let display_hunks = self.layout_gutter_git_hunks(
5424                        line_height,
5425                        &gutter_hitbox,
5426                        start_row..end_row,
5427                        start_anchor..end_anchor,
5428                        &snapshot,
5429                        cx,
5430                    );
5431
5432                    let mut max_visible_line_width = Pixels::ZERO;
5433                    let mut line_layouts = Self::layout_lines(
5434                        start_row..end_row,
5435                        &snapshot,
5436                        &self.style,
5437                        editor_width,
5438                        is_row_soft_wrapped,
5439                        cx,
5440                    );
5441                    for line_with_invisibles in &line_layouts {
5442                        if line_with_invisibles.width > max_visible_line_width {
5443                            max_visible_line_width = line_with_invisibles.width;
5444                        }
5445                    }
5446
5447                    let longest_line_width = layout_line(
5448                        snapshot.longest_row(),
5449                        &snapshot,
5450                        &style,
5451                        editor_width,
5452                        is_row_soft_wrapped,
5453                        cx,
5454                    )
5455                    .width;
5456                    let mut scroll_width =
5457                        longest_line_width.max(max_visible_line_width) + overscroll.width;
5458
5459                    let blocks = cx.with_element_namespace("blocks", |cx| {
5460                        self.render_blocks(
5461                            start_row..end_row,
5462                            &snapshot,
5463                            &hitbox,
5464                            &text_hitbox,
5465                            editor_width,
5466                            &mut scroll_width,
5467                            &gutter_dimensions,
5468                            em_width,
5469                            gutter_dimensions.full_width(),
5470                            line_height,
5471                            &line_layouts,
5472                            &local_selections,
5473                            is_row_soft_wrapped,
5474                            cx,
5475                        )
5476                    });
5477                    let mut blocks = match blocks {
5478                        Ok(blocks) => blocks,
5479                        Err(resized_blocks) => {
5480                            self.editor.update(cx, |editor, cx| {
5481                                editor.resize_blocks(resized_blocks, autoscroll_request, cx)
5482                            });
5483                            return self.prepaint(None, bounds, &mut (), cx);
5484                        }
5485                    };
5486
5487                    let start_buffer_row =
5488                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
5489                    let end_buffer_row =
5490                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
5491
5492                    let scroll_max = point(
5493                        ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
5494                        max_row.as_f32(),
5495                    );
5496
5497                    self.editor.update(cx, |editor, cx| {
5498                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
5499
5500                        let autoscrolled = if autoscroll_horizontally {
5501                            editor.autoscroll_horizontally(
5502                                start_row,
5503                                text_hitbox.size.width,
5504                                scroll_width,
5505                                em_width,
5506                                &line_layouts,
5507                                cx,
5508                            )
5509                        } else {
5510                            false
5511                        };
5512
5513                        if clamped || autoscrolled {
5514                            snapshot = editor.snapshot(cx);
5515                            scroll_position = snapshot.scroll_position();
5516                        }
5517                    });
5518
5519                    let scroll_pixel_position = point(
5520                        scroll_position.x * em_width,
5521                        scroll_position.y * line_height,
5522                    );
5523
5524                    let indent_guides = self.layout_indent_guides(
5525                        content_origin,
5526                        text_hitbox.origin,
5527                        start_buffer_row..end_buffer_row,
5528                        scroll_pixel_position,
5529                        line_height,
5530                        &snapshot,
5531                        cx,
5532                    );
5533
5534                    let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
5535                        self.prepaint_crease_trailers(
5536                            crease_trailers,
5537                            &line_layouts,
5538                            line_height,
5539                            content_origin,
5540                            scroll_pixel_position,
5541                            em_width,
5542                            cx,
5543                        )
5544                    });
5545
5546                    let mut inline_blame = None;
5547                    if let Some(newest_selection_head) = newest_selection_head {
5548                        let display_row = newest_selection_head.row();
5549                        if (start_row..end_row).contains(&display_row) {
5550                            let line_ix = display_row.minus(start_row) as usize;
5551                            let line_layout = &line_layouts[line_ix];
5552                            let crease_trailer_layout = crease_trailers[line_ix].as_ref();
5553                            inline_blame = self.layout_inline_blame(
5554                                display_row,
5555                                &snapshot.display_snapshot,
5556                                line_layout,
5557                                crease_trailer_layout,
5558                                em_width,
5559                                content_origin,
5560                                scroll_pixel_position,
5561                                line_height,
5562                                cx,
5563                            );
5564                        }
5565                    }
5566
5567                    let blamed_display_rows = self.layout_blame_entries(
5568                        buffer_rows.into_iter(),
5569                        em_width,
5570                        scroll_position,
5571                        line_height,
5572                        &gutter_hitbox,
5573                        gutter_dimensions.git_blame_entries_width,
5574                        cx,
5575                    );
5576
5577                    let scroll_max = point(
5578                        ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
5579                        max_scroll_top,
5580                    );
5581
5582                    self.editor.update(cx, |editor, cx| {
5583                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
5584
5585                        let autoscrolled = if autoscroll_horizontally {
5586                            editor.autoscroll_horizontally(
5587                                start_row,
5588                                text_hitbox.size.width,
5589                                scroll_width,
5590                                em_width,
5591                                &line_layouts,
5592                                cx,
5593                            )
5594                        } else {
5595                            false
5596                        };
5597
5598                        if clamped || autoscrolled {
5599                            snapshot = editor.snapshot(cx);
5600                            scroll_position = snapshot.scroll_position();
5601                        }
5602                    });
5603
5604                    let line_elements = self.prepaint_lines(
5605                        start_row,
5606                        &mut line_layouts,
5607                        line_height,
5608                        scroll_pixel_position,
5609                        content_origin,
5610                        cx,
5611                    );
5612
5613                    let mut block_start_rows = HashSet::default();
5614                    cx.with_element_namespace("blocks", |cx| {
5615                        self.layout_blocks(
5616                            &mut blocks,
5617                            &mut block_start_rows,
5618                            &hitbox,
5619                            line_height,
5620                            scroll_pixel_position,
5621                            cx,
5622                        );
5623                    });
5624
5625                    let cursors = self.collect_cursors(&snapshot, cx);
5626                    let visible_row_range = start_row..end_row;
5627                    let non_visible_cursors = cursors
5628                        .iter()
5629                        .any(move |c| !visible_row_range.contains(&c.0.row()));
5630
5631                    let visible_cursors = self.layout_visible_cursors(
5632                        &snapshot,
5633                        &selections,
5634                        &block_start_rows,
5635                        start_row..end_row,
5636                        &line_layouts,
5637                        &text_hitbox,
5638                        content_origin,
5639                        scroll_position,
5640                        scroll_pixel_position,
5641                        line_height,
5642                        em_width,
5643                        autoscroll_containing_element,
5644                        cx,
5645                    );
5646
5647                    let scrollbar_layout = self.layout_scrollbar(
5648                        &snapshot,
5649                        bounds,
5650                        scroll_position,
5651                        height_in_lines,
5652                        non_visible_cursors,
5653                        cx,
5654                    );
5655
5656                    let gutter_settings = EditorSettings::get_global(cx).gutter;
5657
5658                    let expanded_add_hunks_by_rows = self.editor.update(cx, |editor, _| {
5659                        editor
5660                            .diff_map
5661                            .hunks(false)
5662                            .filter(|hunk| hunk.status == DiffHunkStatus::Added)
5663                            .map(|expanded_hunk| {
5664                                let start_row = expanded_hunk
5665                                    .hunk_range
5666                                    .start
5667                                    .to_display_point(&snapshot)
5668                                    .row();
5669                                (start_row, expanded_hunk.clone())
5670                            })
5671                            .collect::<HashMap<_, _>>()
5672                    });
5673
5674                    let rows_with_hunk_bounds = display_hunks
5675                        .iter()
5676                        .filter_map(|(hunk, hitbox)| Some((hunk, hitbox.as_ref()?.bounds)))
5677                        .fold(
5678                            HashMap::default(),
5679                            |mut rows_with_hunk_bounds, (hunk, bounds)| {
5680                                match hunk {
5681                                    DisplayDiffHunk::Folded { display_row } => {
5682                                        rows_with_hunk_bounds.insert(*display_row, bounds);
5683                                    }
5684                                    DisplayDiffHunk::Unfolded {
5685                                        display_row_range, ..
5686                                    } => {
5687                                        for display_row in display_row_range.iter_rows() {
5688                                            rows_with_hunk_bounds.insert(display_row, bounds);
5689                                        }
5690                                    }
5691                                }
5692                                rows_with_hunk_bounds
5693                            },
5694                        );
5695                    let mut _context_menu_visible = false;
5696                    let mut code_actions_indicator = None;
5697                    if let Some(newest_selection_head) = newest_selection_head {
5698                        if (start_row..end_row).contains(&newest_selection_head.row()) {
5699                            _context_menu_visible = self.layout_context_menu(
5700                                line_height,
5701                                &hitbox,
5702                                &text_hitbox,
5703                                content_origin,
5704                                start_row,
5705                                scroll_pixel_position,
5706                                &line_layouts,
5707                                newest_selection_head,
5708                                gutter_dimensions.width - gutter_dimensions.left_padding,
5709                                cx,
5710                            );
5711
5712                            let show_code_actions = snapshot
5713                                .show_code_actions
5714                                .unwrap_or(gutter_settings.code_actions);
5715                            if show_code_actions {
5716                                let newest_selection_point =
5717                                    newest_selection_head.to_point(&snapshot.display_snapshot);
5718                                let newest_selection_display_row =
5719                                    newest_selection_point.to_display_point(&snapshot).row();
5720                                if !expanded_add_hunks_by_rows
5721                                    .contains_key(&newest_selection_display_row)
5722                                {
5723                                    let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
5724                                        MultiBufferRow(newest_selection_point.row),
5725                                    );
5726                                    if let Some((buffer, range)) = buffer {
5727                                        let buffer_id = buffer.remote_id();
5728                                        let row = range.start.row;
5729                                        let has_test_indicator = self
5730                                            .editor
5731                                            .read(cx)
5732                                            .tasks
5733                                            .contains_key(&(buffer_id, row));
5734
5735                                        if !has_test_indicator {
5736                                            code_actions_indicator = self
5737                                                .layout_code_actions_indicator(
5738                                                    line_height,
5739                                                    newest_selection_head,
5740                                                    scroll_pixel_position,
5741                                                    &gutter_dimensions,
5742                                                    &gutter_hitbox,
5743                                                    &rows_with_hunk_bounds,
5744                                                    cx,
5745                                                );
5746                                        }
5747                                    }
5748                                }
5749                            }
5750                        }
5751                    }
5752
5753                    let test_indicators = if gutter_settings.runnables {
5754                        self.layout_run_indicators(
5755                            line_height,
5756                            start_row..end_row,
5757                            scroll_pixel_position,
5758                            &gutter_dimensions,
5759                            &gutter_hitbox,
5760                            &rows_with_hunk_bounds,
5761                            &snapshot,
5762                            cx,
5763                        )
5764                    } else {
5765                        Vec::new()
5766                    };
5767
5768                    self.layout_signature_help(
5769                        &hitbox,
5770                        content_origin,
5771                        scroll_pixel_position,
5772                        newest_selection_head,
5773                        start_row,
5774                        &line_layouts,
5775                        line_height,
5776                        em_width,
5777                        cx,
5778                    );
5779
5780                    if !cx.has_active_drag() {
5781                        self.layout_hover_popovers(
5782                            &snapshot,
5783                            &hitbox,
5784                            &text_hitbox,
5785                            start_row..end_row,
5786                            content_origin,
5787                            scroll_pixel_position,
5788                            &line_layouts,
5789                            line_height,
5790                            em_width,
5791                            cx,
5792                        );
5793                    }
5794
5795                    let inline_completion_popover = self.layout_inline_completion_popover(
5796                        &text_hitbox.bounds,
5797                        &snapshot,
5798                        start_row..end_row,
5799                        scroll_position.y,
5800                        scroll_position.y + height_in_lines,
5801                        &line_layouts,
5802                        line_height,
5803                        scroll_pixel_position,
5804                        editor_width,
5805                        &style,
5806                        cx,
5807                    );
5808
5809                    let mouse_context_menu = self.layout_mouse_context_menu(
5810                        &snapshot,
5811                        start_row..end_row,
5812                        content_origin,
5813                        cx,
5814                    );
5815
5816                    cx.with_element_namespace("crease_toggles", |cx| {
5817                        self.prepaint_crease_toggles(
5818                            &mut crease_toggles,
5819                            line_height,
5820                            &gutter_dimensions,
5821                            gutter_settings,
5822                            scroll_pixel_position,
5823                            &gutter_hitbox,
5824                            cx,
5825                        )
5826                    });
5827
5828                    let invisible_symbol_font_size = font_size / 2.;
5829                    let tab_invisible = cx
5830                        .text_system()
5831                        .shape_line(
5832                            "".into(),
5833                            invisible_symbol_font_size,
5834                            &[TextRun {
5835                                len: "".len(),
5836                                font: self.style.text.font(),
5837                                color: cx.theme().colors().editor_invisible,
5838                                background_color: None,
5839                                underline: None,
5840                                strikethrough: None,
5841                            }],
5842                        )
5843                        .unwrap();
5844                    let space_invisible = cx
5845                        .text_system()
5846                        .shape_line(
5847                            "".into(),
5848                            invisible_symbol_font_size,
5849                            &[TextRun {
5850                                len: "".len(),
5851                                font: self.style.text.font(),
5852                                color: cx.theme().colors().editor_invisible,
5853                                background_color: None,
5854                                underline: None,
5855                                strikethrough: None,
5856                            }],
5857                        )
5858                        .unwrap();
5859
5860                    EditorLayout {
5861                        mode: snapshot.mode,
5862                        position_map: Rc::new(PositionMap {
5863                            size: bounds.size,
5864                            scroll_pixel_position,
5865                            scroll_max,
5866                            line_layouts,
5867                            line_height,
5868                            em_width,
5869                            em_advance,
5870                            snapshot,
5871                        }),
5872                        visible_display_row_range: start_row..end_row,
5873                        wrap_guides,
5874                        indent_guides,
5875                        hitbox,
5876                        text_hitbox,
5877                        gutter_hitbox,
5878                        gutter_dimensions,
5879                        display_hunks,
5880                        content_origin,
5881                        scrollbar_layout,
5882                        active_rows,
5883                        highlighted_rows,
5884                        highlighted_ranges,
5885                        highlighted_gutter_ranges,
5886                        redacted_ranges,
5887                        line_elements,
5888                        line_numbers,
5889                        blamed_display_rows,
5890                        inline_blame,
5891                        blocks,
5892                        cursors,
5893                        visible_cursors,
5894                        selections,
5895                        inline_completion_popover,
5896                        mouse_context_menu,
5897                        test_indicators,
5898                        code_actions_indicator,
5899                        crease_toggles,
5900                        crease_trailers,
5901                        tab_invisible,
5902                        space_invisible,
5903                    }
5904                })
5905            })
5906        })
5907    }
5908
5909    fn paint(
5910        &mut self,
5911        _: Option<&GlobalElementId>,
5912        bounds: Bounds<gpui::Pixels>,
5913        _: &mut Self::RequestLayoutState,
5914        layout: &mut Self::PrepaintState,
5915        cx: &mut WindowContext,
5916    ) {
5917        let focus_handle = self.editor.focus_handle(cx);
5918        let key_context = self.editor.update(cx, |editor, cx| editor.key_context(cx));
5919        cx.set_key_context(key_context);
5920        cx.handle_input(
5921            &focus_handle,
5922            ElementInputHandler::new(bounds, self.editor.clone()),
5923        );
5924        self.register_actions(cx);
5925        self.register_key_listeners(cx, layout);
5926
5927        let text_style = TextStyleRefinement {
5928            font_size: Some(self.style.text.font_size),
5929            line_height: Some(self.style.text.line_height),
5930            ..Default::default()
5931        };
5932        let hovered_hunk = layout
5933            .display_hunks
5934            .iter()
5935            .find_map(|(hunk, hunk_hitbox)| match hunk {
5936                DisplayDiffHunk::Folded { .. } => None,
5937                DisplayDiffHunk::Unfolded {
5938                    diff_base_byte_range,
5939                    multi_buffer_range,
5940                    status,
5941                    ..
5942                } => {
5943                    if hunk_hitbox
5944                        .as_ref()
5945                        .map(|hitbox| hitbox.is_hovered(cx))
5946                        .unwrap_or(false)
5947                    {
5948                        Some(HoveredHunk {
5949                            status: *status,
5950                            multi_buffer_range: multi_buffer_range.clone(),
5951                            diff_base_byte_range: diff_base_byte_range.clone(),
5952                        })
5953                    } else {
5954                        None
5955                    }
5956                }
5957            });
5958        let rem_size = self.rem_size(cx);
5959        cx.with_rem_size(rem_size, |cx| {
5960            cx.with_text_style(Some(text_style), |cx| {
5961                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5962                    self.paint_mouse_listeners(layout, hovered_hunk, cx);
5963                    self.paint_background(layout, cx);
5964                    self.paint_indent_guides(layout, cx);
5965
5966                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
5967                        self.paint_blamed_display_rows(layout, cx);
5968                        self.paint_line_numbers(layout, cx);
5969                    }
5970
5971                    self.paint_text(layout, cx);
5972
5973                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
5974                        self.paint_gutter_highlights(layout, cx);
5975                        self.paint_gutter_indicators(layout, cx);
5976                    }
5977
5978                    if !layout.blocks.is_empty() {
5979                        cx.with_element_namespace("blocks", |cx| {
5980                            self.paint_blocks(layout, cx);
5981                        });
5982                    }
5983
5984                    self.paint_scrollbar(layout, cx);
5985                    self.paint_inline_completion_popover(layout, cx);
5986                    self.paint_mouse_context_menu(layout, cx);
5987                });
5988            })
5989        })
5990    }
5991}
5992
5993pub(super) fn gutter_bounds(
5994    editor_bounds: Bounds<Pixels>,
5995    gutter_dimensions: GutterDimensions,
5996) -> Bounds<Pixels> {
5997    Bounds {
5998        origin: editor_bounds.origin,
5999        size: size(gutter_dimensions.width, editor_bounds.size.height),
6000    }
6001}
6002
6003impl IntoElement for EditorElement {
6004    type Element = Self;
6005
6006    fn into_element(self) -> Self::Element {
6007        self
6008    }
6009}
6010
6011pub struct EditorLayout {
6012    position_map: Rc<PositionMap>,
6013    hitbox: Hitbox,
6014    text_hitbox: Hitbox,
6015    gutter_hitbox: Hitbox,
6016    gutter_dimensions: GutterDimensions,
6017    content_origin: gpui::Point<Pixels>,
6018    scrollbar_layout: Option<ScrollbarLayout>,
6019    mode: EditorMode,
6020    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
6021    indent_guides: Option<Vec<IndentGuideLayout>>,
6022    visible_display_row_range: Range<DisplayRow>,
6023    active_rows: BTreeMap<DisplayRow, bool>,
6024    highlighted_rows: BTreeMap<DisplayRow, Hsla>,
6025    line_elements: SmallVec<[AnyElement; 1]>,
6026    line_numbers: Vec<Option<ShapedLine>>,
6027    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
6028    blamed_display_rows: Option<Vec<AnyElement>>,
6029    inline_blame: Option<AnyElement>,
6030    blocks: Vec<BlockLayout>,
6031    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
6032    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
6033    redacted_ranges: Vec<Range<DisplayPoint>>,
6034    cursors: Vec<(DisplayPoint, Hsla)>,
6035    visible_cursors: Vec<CursorLayout>,
6036    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
6037    code_actions_indicator: Option<AnyElement>,
6038    test_indicators: Vec<AnyElement>,
6039    crease_toggles: Vec<Option<AnyElement>>,
6040    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
6041    inline_completion_popover: Option<AnyElement>,
6042    mouse_context_menu: Option<AnyElement>,
6043    tab_invisible: ShapedLine,
6044    space_invisible: ShapedLine,
6045}
6046
6047impl EditorLayout {
6048    fn line_end_overshoot(&self) -> Pixels {
6049        0.15 * self.position_map.line_height
6050    }
6051}
6052
6053struct ColoredRange<T> {
6054    start: T,
6055    end: T,
6056    color: Hsla,
6057}
6058
6059#[derive(Clone)]
6060struct ScrollbarLayout {
6061    hitbox: Hitbox,
6062    visible_row_range: Range<f32>,
6063    visible: bool,
6064    row_height: Pixels,
6065    thumb_height: Pixels,
6066}
6067
6068impl ScrollbarLayout {
6069    const BORDER_WIDTH: Pixels = px(1.0);
6070    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
6071    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
6072    const MIN_THUMB_HEIGHT: Pixels = px(20.0);
6073
6074    fn thumb_bounds(&self) -> Bounds<Pixels> {
6075        let thumb_top = self.y_for_row(self.visible_row_range.start);
6076        let thumb_bottom = thumb_top + self.thumb_height;
6077        Bounds::from_corners(
6078            point(self.hitbox.left(), thumb_top),
6079            point(self.hitbox.right(), thumb_bottom),
6080        )
6081    }
6082
6083    fn y_for_row(&self, row: f32) -> Pixels {
6084        self.hitbox.top() + row * self.row_height
6085    }
6086
6087    fn marker_quads_for_ranges(
6088        &self,
6089        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
6090        column: Option<usize>,
6091    ) -> Vec<PaintQuad> {
6092        struct MinMax {
6093            min: Pixels,
6094            max: Pixels,
6095        }
6096        let (x_range, height_limit) = if let Some(column) = column {
6097            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
6098            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
6099            let end = start + column_width;
6100            (
6101                Range { start, end },
6102                MinMax {
6103                    min: Self::MIN_MARKER_HEIGHT,
6104                    max: px(f32::MAX),
6105                },
6106            )
6107        } else {
6108            (
6109                Range {
6110                    start: Self::BORDER_WIDTH,
6111                    end: self.hitbox.size.width,
6112                },
6113                MinMax {
6114                    min: Self::LINE_MARKER_HEIGHT,
6115                    max: Self::LINE_MARKER_HEIGHT,
6116                },
6117            )
6118        };
6119
6120        let row_to_y = |row: DisplayRow| row.as_f32() * self.row_height;
6121        let mut pixel_ranges = row_ranges
6122            .into_iter()
6123            .map(|range| {
6124                let start_y = row_to_y(range.start);
6125                let end_y = row_to_y(range.end)
6126                    + self.row_height.max(height_limit.min).min(height_limit.max);
6127                ColoredRange {
6128                    start: start_y,
6129                    end: end_y,
6130                    color: range.color,
6131                }
6132            })
6133            .peekable();
6134
6135        let mut quads = Vec::new();
6136        while let Some(mut pixel_range) = pixel_ranges.next() {
6137            while let Some(next_pixel_range) = pixel_ranges.peek() {
6138                if pixel_range.end >= next_pixel_range.start - px(1.0)
6139                    && pixel_range.color == next_pixel_range.color
6140                {
6141                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
6142                    pixel_ranges.next();
6143                } else {
6144                    break;
6145                }
6146            }
6147
6148            let bounds = Bounds::from_corners(
6149                point(x_range.start, pixel_range.start),
6150                point(x_range.end, pixel_range.end),
6151            );
6152            quads.push(quad(
6153                bounds,
6154                Corners::default(),
6155                pixel_range.color,
6156                Edges::default(),
6157                Hsla::transparent_black(),
6158            ));
6159        }
6160
6161        quads
6162    }
6163}
6164
6165struct CreaseTrailerLayout {
6166    element: AnyElement,
6167    bounds: Bounds<Pixels>,
6168}
6169
6170struct PositionMap {
6171    size: Size<Pixels>,
6172    line_height: Pixels,
6173    scroll_pixel_position: gpui::Point<Pixels>,
6174    scroll_max: gpui::Point<f32>,
6175    em_width: Pixels,
6176    em_advance: Pixels,
6177    line_layouts: Vec<LineWithInvisibles>,
6178    snapshot: EditorSnapshot,
6179}
6180
6181#[derive(Debug, Copy, Clone)]
6182pub struct PointForPosition {
6183    pub previous_valid: DisplayPoint,
6184    pub next_valid: DisplayPoint,
6185    pub exact_unclipped: DisplayPoint,
6186    pub column_overshoot_after_line_end: u32,
6187}
6188
6189impl PointForPosition {
6190    pub fn as_valid(&self) -> Option<DisplayPoint> {
6191        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
6192            Some(self.previous_valid)
6193        } else {
6194            None
6195        }
6196    }
6197}
6198
6199impl PositionMap {
6200    fn point_for_position(
6201        &self,
6202        text_bounds: Bounds<Pixels>,
6203        position: gpui::Point<Pixels>,
6204    ) -> PointForPosition {
6205        let scroll_position = self.snapshot.scroll_position();
6206        let position = position - text_bounds.origin;
6207        let y = position.y.max(px(0.)).min(self.size.height);
6208        let x = position.x + (scroll_position.x * self.em_width);
6209        let row = ((y / self.line_height) + scroll_position.y) as u32;
6210
6211        let (column, x_overshoot_after_line_end) = if let Some(line) = self
6212            .line_layouts
6213            .get(row as usize - scroll_position.y as usize)
6214        {
6215            if let Some(ix) = line.index_for_x(x) {
6216                (ix as u32, px(0.))
6217            } else {
6218                (line.len as u32, px(0.).max(x - line.width))
6219            }
6220        } else {
6221            (0, x)
6222        };
6223
6224        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
6225        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
6226        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
6227
6228        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
6229        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
6230        PointForPosition {
6231            previous_valid,
6232            next_valid,
6233            exact_unclipped,
6234            column_overshoot_after_line_end,
6235        }
6236    }
6237}
6238
6239struct BlockLayout {
6240    id: BlockId,
6241    row: Option<DisplayRow>,
6242    element: AnyElement,
6243    available_space: Size<AvailableSpace>,
6244    style: BlockStyle,
6245}
6246
6247fn layout_line(
6248    row: DisplayRow,
6249    snapshot: &EditorSnapshot,
6250    style: &EditorStyle,
6251    text_width: Pixels,
6252    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6253    cx: &mut WindowContext,
6254) -> LineWithInvisibles {
6255    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
6256    LineWithInvisibles::from_chunks(
6257        chunks,
6258        &style,
6259        MAX_LINE_LEN,
6260        1,
6261        snapshot.mode,
6262        text_width,
6263        is_row_soft_wrapped,
6264        cx,
6265    )
6266    .pop()
6267    .unwrap()
6268}
6269
6270#[derive(Debug)]
6271pub struct IndentGuideLayout {
6272    origin: gpui::Point<Pixels>,
6273    length: Pixels,
6274    single_indent_width: Pixels,
6275    depth: u32,
6276    active: bool,
6277    settings: IndentGuideSettings,
6278}
6279
6280pub struct CursorLayout {
6281    origin: gpui::Point<Pixels>,
6282    block_width: Pixels,
6283    line_height: Pixels,
6284    color: Hsla,
6285    shape: CursorShape,
6286    block_text: Option<ShapedLine>,
6287    cursor_name: Option<AnyElement>,
6288}
6289
6290#[derive(Debug)]
6291pub struct CursorName {
6292    string: SharedString,
6293    color: Hsla,
6294    is_top_row: bool,
6295}
6296
6297impl CursorLayout {
6298    pub fn new(
6299        origin: gpui::Point<Pixels>,
6300        block_width: Pixels,
6301        line_height: Pixels,
6302        color: Hsla,
6303        shape: CursorShape,
6304        block_text: Option<ShapedLine>,
6305    ) -> CursorLayout {
6306        CursorLayout {
6307            origin,
6308            block_width,
6309            line_height,
6310            color,
6311            shape,
6312            block_text,
6313            cursor_name: None,
6314        }
6315    }
6316
6317    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
6318        Bounds {
6319            origin: self.origin + origin,
6320            size: size(self.block_width, self.line_height),
6321        }
6322    }
6323
6324    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
6325        match self.shape {
6326            CursorShape::Bar => Bounds {
6327                origin: self.origin + origin,
6328                size: size(px(2.0), self.line_height),
6329            },
6330            CursorShape::Block | CursorShape::Hollow => Bounds {
6331                origin: self.origin + origin,
6332                size: size(self.block_width, self.line_height),
6333            },
6334            CursorShape::Underline => Bounds {
6335                origin: self.origin
6336                    + origin
6337                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
6338                size: size(self.block_width, px(2.0)),
6339            },
6340        }
6341    }
6342
6343    pub fn layout(
6344        &mut self,
6345        origin: gpui::Point<Pixels>,
6346        cursor_name: Option<CursorName>,
6347        cx: &mut WindowContext,
6348    ) {
6349        if let Some(cursor_name) = cursor_name {
6350            let bounds = self.bounds(origin);
6351            let text_size = self.line_height / 1.5;
6352
6353            let name_origin = if cursor_name.is_top_row {
6354                point(bounds.right() - px(1.), bounds.top())
6355            } else {
6356                point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
6357            };
6358            let mut name_element = div()
6359                .bg(self.color)
6360                .text_size(text_size)
6361                .px_0p5()
6362                .line_height(text_size + px(2.))
6363                .text_color(cursor_name.color)
6364                .child(cursor_name.string.clone())
6365                .into_any_element();
6366
6367            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), cx);
6368
6369            self.cursor_name = Some(name_element);
6370        }
6371    }
6372
6373    pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
6374        let bounds = self.bounds(origin);
6375
6376        //Draw background or border quad
6377        let cursor = if matches!(self.shape, CursorShape::Hollow) {
6378            outline(bounds, self.color)
6379        } else {
6380            fill(bounds, self.color)
6381        };
6382
6383        if let Some(name) = &mut self.cursor_name {
6384            name.paint(cx);
6385        }
6386
6387        cx.paint_quad(cursor);
6388
6389        if let Some(block_text) = &self.block_text {
6390            block_text
6391                .paint(self.origin + origin, self.line_height, cx)
6392                .log_err();
6393        }
6394    }
6395
6396    pub fn shape(&self) -> CursorShape {
6397        self.shape
6398    }
6399}
6400
6401#[derive(Debug)]
6402pub struct HighlightedRange {
6403    pub start_y: Pixels,
6404    pub line_height: Pixels,
6405    pub lines: Vec<HighlightedRangeLine>,
6406    pub color: Hsla,
6407    pub corner_radius: Pixels,
6408}
6409
6410#[derive(Debug)]
6411pub struct HighlightedRangeLine {
6412    pub start_x: Pixels,
6413    pub end_x: Pixels,
6414}
6415
6416impl HighlightedRange {
6417    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
6418        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
6419            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
6420            self.paint_lines(
6421                self.start_y + self.line_height,
6422                &self.lines[1..],
6423                bounds,
6424                cx,
6425            );
6426        } else {
6427            self.paint_lines(self.start_y, &self.lines, bounds, cx);
6428        }
6429    }
6430
6431    fn paint_lines(
6432        &self,
6433        start_y: Pixels,
6434        lines: &[HighlightedRangeLine],
6435        _bounds: Bounds<Pixels>,
6436        cx: &mut WindowContext,
6437    ) {
6438        if lines.is_empty() {
6439            return;
6440        }
6441
6442        let first_line = lines.first().unwrap();
6443        let last_line = lines.last().unwrap();
6444
6445        let first_top_left = point(first_line.start_x, start_y);
6446        let first_top_right = point(first_line.end_x, start_y);
6447
6448        let curve_height = point(Pixels::ZERO, self.corner_radius);
6449        let curve_width = |start_x: Pixels, end_x: Pixels| {
6450            let max = (end_x - start_x) / 2.;
6451            let width = if max < self.corner_radius {
6452                max
6453            } else {
6454                self.corner_radius
6455            };
6456
6457            point(width, Pixels::ZERO)
6458        };
6459
6460        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
6461        let mut path = gpui::Path::new(first_top_right - top_curve_width);
6462        path.curve_to(first_top_right + curve_height, first_top_right);
6463
6464        let mut iter = lines.iter().enumerate().peekable();
6465        while let Some((ix, line)) = iter.next() {
6466            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
6467
6468            if let Some((_, next_line)) = iter.peek() {
6469                let next_top_right = point(next_line.end_x, bottom_right.y);
6470
6471                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
6472                    Ordering::Equal => {
6473                        path.line_to(bottom_right);
6474                    }
6475                    Ordering::Less => {
6476                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
6477                        path.line_to(bottom_right - curve_height);
6478                        if self.corner_radius > Pixels::ZERO {
6479                            path.curve_to(bottom_right - curve_width, bottom_right);
6480                        }
6481                        path.line_to(next_top_right + curve_width);
6482                        if self.corner_radius > Pixels::ZERO {
6483                            path.curve_to(next_top_right + curve_height, next_top_right);
6484                        }
6485                    }
6486                    Ordering::Greater => {
6487                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
6488                        path.line_to(bottom_right - curve_height);
6489                        if self.corner_radius > Pixels::ZERO {
6490                            path.curve_to(bottom_right + curve_width, bottom_right);
6491                        }
6492                        path.line_to(next_top_right - curve_width);
6493                        if self.corner_radius > Pixels::ZERO {
6494                            path.curve_to(next_top_right + curve_height, next_top_right);
6495                        }
6496                    }
6497                }
6498            } else {
6499                let curve_width = curve_width(line.start_x, line.end_x);
6500                path.line_to(bottom_right - curve_height);
6501                if self.corner_radius > Pixels::ZERO {
6502                    path.curve_to(bottom_right - curve_width, bottom_right);
6503                }
6504
6505                let bottom_left = point(line.start_x, bottom_right.y);
6506                path.line_to(bottom_left + curve_width);
6507                if self.corner_radius > Pixels::ZERO {
6508                    path.curve_to(bottom_left - curve_height, bottom_left);
6509                }
6510            }
6511        }
6512
6513        if first_line.start_x > last_line.start_x {
6514            let curve_width = curve_width(last_line.start_x, first_line.start_x);
6515            let second_top_left = point(last_line.start_x, start_y + self.line_height);
6516            path.line_to(second_top_left + curve_height);
6517            if self.corner_radius > Pixels::ZERO {
6518                path.curve_to(second_top_left + curve_width, second_top_left);
6519            }
6520            let first_bottom_left = point(first_line.start_x, second_top_left.y);
6521            path.line_to(first_bottom_left - curve_width);
6522            if self.corner_radius > Pixels::ZERO {
6523                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
6524            }
6525        }
6526
6527        path.line_to(first_top_left + curve_height);
6528        if self.corner_radius > Pixels::ZERO {
6529            path.curve_to(first_top_left + top_curve_width, first_top_left);
6530        }
6531        path.line_to(first_top_right - top_curve_width);
6532
6533        cx.paint_path(path, self.color);
6534    }
6535}
6536
6537pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
6538    (delta.pow(1.5) / 100.0).into()
6539}
6540
6541fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
6542    (delta.pow(1.2) / 300.0).into()
6543}
6544
6545pub fn register_action<T: Action>(
6546    view: &View<Editor>,
6547    cx: &mut WindowContext,
6548    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
6549) {
6550    let view = view.clone();
6551    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
6552        let action = action.downcast_ref().unwrap();
6553        if phase == DispatchPhase::Bubble {
6554            view.update(cx, |editor, cx| {
6555                listener(editor, action, cx);
6556            })
6557        }
6558    })
6559}
6560
6561fn compute_auto_height_layout(
6562    editor: &mut Editor,
6563    max_lines: usize,
6564    max_line_number_width: Pixels,
6565    known_dimensions: Size<Option<Pixels>>,
6566    available_width: AvailableSpace,
6567    cx: &mut ViewContext<Editor>,
6568) -> Option<Size<Pixels>> {
6569    let width = known_dimensions.width.or({
6570        if let AvailableSpace::Definite(available_width) = available_width {
6571            Some(available_width)
6572        } else {
6573            None
6574        }
6575    })?;
6576    if let Some(height) = known_dimensions.height {
6577        return Some(size(width, height));
6578    }
6579
6580    let style = editor.style.as_ref().unwrap();
6581    let font_id = cx.text_system().resolve_font(&style.text.font());
6582    let font_size = style.text.font_size.to_pixels(cx.rem_size());
6583    let line_height = style.text.line_height_in_pixels(cx.rem_size());
6584    let em_width = cx
6585        .text_system()
6586        .typographic_bounds(font_id, font_size, 'm')
6587        .unwrap()
6588        .size
6589        .width;
6590    let em_advance = cx
6591        .text_system()
6592        .advance(font_id, font_size, 'm')
6593        .unwrap()
6594        .width;
6595
6596    let mut snapshot = editor.snapshot(cx);
6597    let gutter_dimensions = snapshot.gutter_dimensions(
6598        font_id,
6599        font_size,
6600        em_width,
6601        em_advance,
6602        max_line_number_width,
6603        cx,
6604    );
6605
6606    editor.gutter_dimensions = gutter_dimensions;
6607    let text_width = width - gutter_dimensions.width;
6608    let overscroll = size(em_width, px(0.));
6609
6610    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
6611    if editor.set_wrap_width(Some(editor_width), cx) {
6612        snapshot = editor.snapshot(cx);
6613    }
6614
6615    let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
6616    let height = scroll_height
6617        .max(line_height)
6618        .min(line_height * max_lines as f32);
6619
6620    Some(size(width, height))
6621}
6622
6623#[cfg(test)]
6624mod tests {
6625    use super::*;
6626    use crate::{
6627        display_map::{BlockPlacement, BlockProperties},
6628        editor_tests::{init_test, update_test_language_settings},
6629        Editor, MultiBuffer,
6630    };
6631    use gpui::{TestAppContext, VisualTestContext};
6632    use language::language_settings;
6633    use log::info;
6634    use std::num::NonZeroU32;
6635    use ui::Context;
6636    use util::test::sample_text;
6637
6638    #[gpui::test]
6639    fn test_shape_line_numbers(cx: &mut TestAppContext) {
6640        init_test(cx, |_| {});
6641        let window = cx.add_window(|cx| {
6642            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
6643            Editor::new(EditorMode::Full, buffer, None, true, cx)
6644        });
6645
6646        let editor = window.root(cx).unwrap();
6647        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6648        let element = EditorElement::new(&editor, style);
6649        let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
6650
6651        let layouts = cx
6652            .update_window(*window, |_, cx| {
6653                element.layout_line_numbers(
6654                    DisplayRow(0)..DisplayRow(6),
6655                    (0..6).map(MultiBufferRow).map(Some),
6656                    &Default::default(),
6657                    Some(DisplayPoint::new(DisplayRow(0), 0)),
6658                    &snapshot,
6659                    cx,
6660                )
6661            })
6662            .unwrap();
6663        assert_eq!(layouts.len(), 6);
6664
6665        let relative_rows = window
6666            .update(cx, |editor, cx| {
6667                let snapshot = editor.snapshot(cx);
6668                element.calculate_relative_line_numbers(
6669                    &snapshot,
6670                    &(DisplayRow(0)..DisplayRow(6)),
6671                    Some(DisplayRow(3)),
6672                )
6673            })
6674            .unwrap();
6675        assert_eq!(relative_rows[&DisplayRow(0)], 3);
6676        assert_eq!(relative_rows[&DisplayRow(1)], 2);
6677        assert_eq!(relative_rows[&DisplayRow(2)], 1);
6678        // current line has no relative number
6679        assert_eq!(relative_rows[&DisplayRow(4)], 1);
6680        assert_eq!(relative_rows[&DisplayRow(5)], 2);
6681
6682        // works if cursor is before screen
6683        let relative_rows = window
6684            .update(cx, |editor, cx| {
6685                let snapshot = editor.snapshot(cx);
6686                element.calculate_relative_line_numbers(
6687                    &snapshot,
6688                    &(DisplayRow(3)..DisplayRow(6)),
6689                    Some(DisplayRow(1)),
6690                )
6691            })
6692            .unwrap();
6693        assert_eq!(relative_rows.len(), 3);
6694        assert_eq!(relative_rows[&DisplayRow(3)], 2);
6695        assert_eq!(relative_rows[&DisplayRow(4)], 3);
6696        assert_eq!(relative_rows[&DisplayRow(5)], 4);
6697
6698        // works if cursor is after screen
6699        let relative_rows = window
6700            .update(cx, |editor, cx| {
6701                let snapshot = editor.snapshot(cx);
6702                element.calculate_relative_line_numbers(
6703                    &snapshot,
6704                    &(DisplayRow(0)..DisplayRow(3)),
6705                    Some(DisplayRow(6)),
6706                )
6707            })
6708            .unwrap();
6709        assert_eq!(relative_rows.len(), 3);
6710        assert_eq!(relative_rows[&DisplayRow(0)], 5);
6711        assert_eq!(relative_rows[&DisplayRow(1)], 4);
6712        assert_eq!(relative_rows[&DisplayRow(2)], 3);
6713    }
6714
6715    #[gpui::test]
6716    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
6717        init_test(cx, |_| {});
6718
6719        let window = cx.add_window(|cx| {
6720            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
6721            Editor::new(EditorMode::Full, buffer, None, true, cx)
6722        });
6723        let cx = &mut VisualTestContext::from_window(*window, cx);
6724        let editor = window.root(cx).unwrap();
6725        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6726
6727        window
6728            .update(cx, |editor, cx| {
6729                editor.cursor_shape = CursorShape::Block;
6730                editor.change_selections(None, cx, |s| {
6731                    s.select_ranges([
6732                        Point::new(0, 0)..Point::new(1, 0),
6733                        Point::new(3, 2)..Point::new(3, 3),
6734                        Point::new(5, 6)..Point::new(6, 0),
6735                    ]);
6736                });
6737            })
6738            .unwrap();
6739
6740        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6741            EditorElement::new(&editor, style)
6742        });
6743
6744        assert_eq!(state.selections.len(), 1);
6745        let local_selections = &state.selections[0].1;
6746        assert_eq!(local_selections.len(), 3);
6747        // moves cursor back one line
6748        assert_eq!(
6749            local_selections[0].head,
6750            DisplayPoint::new(DisplayRow(0), 6)
6751        );
6752        assert_eq!(
6753            local_selections[0].range,
6754            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
6755        );
6756
6757        // moves cursor back one column
6758        assert_eq!(
6759            local_selections[1].range,
6760            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
6761        );
6762        assert_eq!(
6763            local_selections[1].head,
6764            DisplayPoint::new(DisplayRow(3), 2)
6765        );
6766
6767        // leaves cursor on the max point
6768        assert_eq!(
6769            local_selections[2].range,
6770            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
6771        );
6772        assert_eq!(
6773            local_selections[2].head,
6774            DisplayPoint::new(DisplayRow(6), 0)
6775        );
6776
6777        // active lines does not include 1 (even though the range of the selection does)
6778        assert_eq!(
6779            state.active_rows.keys().cloned().collect::<Vec<_>>(),
6780            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
6781        );
6782
6783        // multi-buffer support
6784        // in DisplayPoint coordinates, this is what we're dealing with:
6785        //  0: [[file
6786        //  1:   header
6787        //  2:   section]]
6788        //  3: aaaaaa
6789        //  4: bbbbbb
6790        //  5: cccccc
6791        //  6:
6792        //  7: [[footer]]
6793        //  8: [[header]]
6794        //  9: ffffff
6795        // 10: gggggg
6796        // 11: hhhhhh
6797        // 12:
6798        // 13: [[footer]]
6799        // 14: [[file
6800        // 15:   header
6801        // 16:   section]]
6802        // 17: bbbbbb
6803        // 18: cccccc
6804        // 19: dddddd
6805        // 20: [[footer]]
6806        let window = cx.add_window(|cx| {
6807            let buffer = MultiBuffer::build_multi(
6808                [
6809                    (
6810                        &(sample_text(8, 6, 'a') + "\n"),
6811                        vec![
6812                            Point::new(0, 0)..Point::new(3, 0),
6813                            Point::new(4, 0)..Point::new(7, 0),
6814                        ],
6815                    ),
6816                    (
6817                        &(sample_text(8, 6, 'a') + "\n"),
6818                        vec![Point::new(1, 0)..Point::new(3, 0)],
6819                    ),
6820                ],
6821                cx,
6822            );
6823            Editor::new(EditorMode::Full, buffer, None, true, cx)
6824        });
6825        let editor = window.root(cx).unwrap();
6826        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6827        let _state = window.update(cx, |editor, cx| {
6828            editor.cursor_shape = CursorShape::Block;
6829            editor.change_selections(None, cx, |s| {
6830                s.select_display_ranges([
6831                    DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
6832                    DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
6833                ]);
6834            });
6835        });
6836
6837        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6838            EditorElement::new(&editor, style)
6839        });
6840        assert_eq!(state.selections.len(), 1);
6841        let local_selections = &state.selections[0].1;
6842        assert_eq!(local_selections.len(), 2);
6843
6844        // moves cursor on excerpt boundary back a line
6845        // and doesn't allow selection to bleed through
6846        assert_eq!(
6847            local_selections[0].range,
6848            DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
6849        );
6850        assert_eq!(
6851            local_selections[0].head,
6852            DisplayPoint::new(DisplayRow(6), 0)
6853        );
6854        // moves cursor on buffer boundary back two lines
6855        // and doesn't allow selection to bleed through
6856        assert_eq!(
6857            local_selections[1].range,
6858            DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
6859        );
6860        assert_eq!(
6861            local_selections[1].head,
6862            DisplayPoint::new(DisplayRow(12), 0)
6863        );
6864    }
6865
6866    #[gpui::test]
6867    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
6868        init_test(cx, |_| {});
6869
6870        let window = cx.add_window(|cx| {
6871            let buffer = MultiBuffer::build_simple("", cx);
6872            Editor::new(EditorMode::Full, buffer, None, true, cx)
6873        });
6874        let cx = &mut VisualTestContext::from_window(*window, cx);
6875        let editor = window.root(cx).unwrap();
6876        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6877        window
6878            .update(cx, |editor, cx| {
6879                editor.set_placeholder_text("hello", cx);
6880                editor.insert_blocks(
6881                    [BlockProperties {
6882                        style: BlockStyle::Fixed,
6883                        placement: BlockPlacement::Above(Anchor::min()),
6884                        height: 3,
6885                        render: Arc::new(|cx| div().h(3. * cx.line_height()).into_any()),
6886                        priority: 0,
6887                    }],
6888                    None,
6889                    cx,
6890                );
6891
6892                // Blur the editor so that it displays placeholder text.
6893                cx.blur();
6894            })
6895            .unwrap();
6896
6897        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6898            EditorElement::new(&editor, style)
6899        });
6900        assert_eq!(state.position_map.line_layouts.len(), 4);
6901        assert_eq!(
6902            state
6903                .line_numbers
6904                .iter()
6905                .map(Option::is_some)
6906                .collect::<Vec<_>>(),
6907            &[false, false, false, true]
6908        );
6909    }
6910
6911    #[gpui::test]
6912    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
6913        const TAB_SIZE: u32 = 4;
6914
6915        let input_text = "\t \t|\t| a b";
6916        let expected_invisibles = vec![
6917            Invisible::Tab {
6918                line_start_offset: 0,
6919                line_end_offset: TAB_SIZE as usize,
6920            },
6921            Invisible::Whitespace {
6922                line_offset: TAB_SIZE as usize,
6923            },
6924            Invisible::Tab {
6925                line_start_offset: TAB_SIZE as usize + 1,
6926                line_end_offset: TAB_SIZE as usize * 2,
6927            },
6928            Invisible::Tab {
6929                line_start_offset: TAB_SIZE as usize * 2 + 1,
6930                line_end_offset: TAB_SIZE as usize * 3,
6931            },
6932            Invisible::Whitespace {
6933                line_offset: TAB_SIZE as usize * 3 + 1,
6934            },
6935            Invisible::Whitespace {
6936                line_offset: TAB_SIZE as usize * 3 + 3,
6937            },
6938        ];
6939        assert_eq!(
6940            expected_invisibles.len(),
6941            input_text
6942                .chars()
6943                .filter(|initial_char| initial_char.is_whitespace())
6944                .count(),
6945            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6946        );
6947
6948        for show_line_numbers in [true, false] {
6949            init_test(cx, |s| {
6950                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6951                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
6952            });
6953
6954            let actual_invisibles = collect_invisibles_from_new_editor(
6955                cx,
6956                EditorMode::Full,
6957                input_text,
6958                px(500.0),
6959                show_line_numbers,
6960            );
6961
6962            assert_eq!(expected_invisibles, actual_invisibles);
6963        }
6964    }
6965
6966    #[gpui::test]
6967    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
6968        init_test(cx, |s| {
6969            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6970            s.defaults.tab_size = NonZeroU32::new(4);
6971        });
6972
6973        for editor_mode_without_invisibles in [
6974            EditorMode::SingleLine { auto_width: false },
6975            EditorMode::AutoHeight { max_lines: 100 },
6976        ] {
6977            for show_line_numbers in [true, false] {
6978                let invisibles = collect_invisibles_from_new_editor(
6979                    cx,
6980                    editor_mode_without_invisibles,
6981                    "\t\t\t| | a b",
6982                    px(500.0),
6983                    show_line_numbers,
6984                );
6985                assert!(invisibles.is_empty(),
6986                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
6987            }
6988        }
6989    }
6990
6991    #[gpui::test]
6992    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
6993        let tab_size = 4;
6994        let input_text = "a\tbcd     ".repeat(9);
6995        let repeated_invisibles = [
6996            Invisible::Tab {
6997                line_start_offset: 1,
6998                line_end_offset: tab_size as usize,
6999            },
7000            Invisible::Whitespace {
7001                line_offset: tab_size as usize + 3,
7002            },
7003            Invisible::Whitespace {
7004                line_offset: tab_size as usize + 4,
7005            },
7006            Invisible::Whitespace {
7007                line_offset: tab_size as usize + 5,
7008            },
7009            Invisible::Whitespace {
7010                line_offset: tab_size as usize + 6,
7011            },
7012            Invisible::Whitespace {
7013                line_offset: tab_size as usize + 7,
7014            },
7015        ];
7016        let expected_invisibles = std::iter::once(repeated_invisibles)
7017            .cycle()
7018            .take(9)
7019            .flatten()
7020            .collect::<Vec<_>>();
7021        assert_eq!(
7022            expected_invisibles.len(),
7023            input_text
7024                .chars()
7025                .filter(|initial_char| initial_char.is_whitespace())
7026                .count(),
7027            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
7028        );
7029        info!("Expected invisibles: {expected_invisibles:?}");
7030
7031        init_test(cx, |_| {});
7032
7033        // Put the same string with repeating whitespace pattern into editors of various size,
7034        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
7035        let resize_step = 10.0;
7036        let mut editor_width = 200.0;
7037        while editor_width <= 1000.0 {
7038            for show_line_numbers in [true, false] {
7039                update_test_language_settings(cx, |s| {
7040                    s.defaults.tab_size = NonZeroU32::new(tab_size);
7041                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
7042                    s.defaults.preferred_line_length = Some(editor_width as u32);
7043                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
7044                });
7045
7046                let actual_invisibles = collect_invisibles_from_new_editor(
7047                    cx,
7048                    EditorMode::Full,
7049                    &input_text,
7050                    px(editor_width),
7051                    show_line_numbers,
7052                );
7053
7054                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
7055                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
7056                let mut i = 0;
7057                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
7058                    i = actual_index;
7059                    match expected_invisibles.get(i) {
7060                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
7061                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
7062                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
7063                            _ => {
7064                                panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
7065                            }
7066                        },
7067                        None => {
7068                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
7069                        }
7070                    }
7071                }
7072                let missing_expected_invisibles = &expected_invisibles[i + 1..];
7073                assert!(
7074                    missing_expected_invisibles.is_empty(),
7075                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
7076                );
7077
7078                editor_width += resize_step;
7079            }
7080        }
7081    }
7082
7083    #[gpui::test]
7084    fn test_inline_completion_popover_text(cx: &mut TestAppContext) {
7085        init_test(cx, |_| {});
7086
7087        // Test case 1: Simple insertion
7088        {
7089            let window = cx.add_window(|cx| {
7090                let buffer = MultiBuffer::build_simple("Hello, world!", cx);
7091                Editor::new(EditorMode::Full, buffer, None, true, cx)
7092            });
7093            let cx = &mut VisualTestContext::from_window(*window, cx);
7094
7095            window
7096                .update(cx, |editor, cx| {
7097                    let snapshot = editor.snapshot(cx);
7098                    let edit_range = snapshot.buffer_snapshot.anchor_after(Point::new(0, 6))
7099                        ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 6));
7100                    let edit_start = DisplayPoint::new(DisplayRow(0), 6);
7101                    let edits = vec![(edit_range, " beautiful".to_string())];
7102
7103                    let (text, highlights) =
7104                        inline_completion_popover_text(edit_start, &snapshot, &edits, cx);
7105
7106                    assert_eq!(text, "Hello, beautiful");
7107                    assert_eq!(highlights.len(), 1);
7108                    assert_eq!(highlights[0].0, 6..16);
7109                    assert_eq!(
7110                        highlights[0].1.background_color,
7111                        Some(cx.theme().status().created_background)
7112                    );
7113                })
7114                .unwrap();
7115        }
7116
7117        // Test case 2: Replacement
7118        {
7119            let window = cx.add_window(|cx| {
7120                let buffer = MultiBuffer::build_simple("This is a test.", cx);
7121                Editor::new(EditorMode::Full, buffer, None, true, cx)
7122            });
7123            let cx = &mut VisualTestContext::from_window(*window, cx);
7124
7125            window
7126                .update(cx, |editor, cx| {
7127                    let snapshot = editor.snapshot(cx);
7128                    let edit_start = DisplayPoint::new(DisplayRow(0), 0);
7129                    let edits = vec![(
7130                        snapshot.buffer_snapshot.anchor_after(Point::new(0, 0))
7131                            ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 4)),
7132                        "That".to_string(),
7133                    )];
7134
7135                    let (text, highlights) =
7136                        inline_completion_popover_text(edit_start, &snapshot, &edits, cx);
7137
7138                    assert_eq!(text, "That");
7139                    assert_eq!(highlights.len(), 1);
7140                    assert_eq!(highlights[0].0, 0..4);
7141                    assert_eq!(
7142                        highlights[0].1.background_color,
7143                        Some(cx.theme().status().created_background)
7144                    );
7145                })
7146                .unwrap();
7147        }
7148
7149        // Test case 3: Multiple edits
7150        {
7151            let window = cx.add_window(|cx| {
7152                let buffer = MultiBuffer::build_simple("Hello, world!", cx);
7153                Editor::new(EditorMode::Full, buffer, None, true, cx)
7154            });
7155            let cx = &mut VisualTestContext::from_window(*window, cx);
7156
7157            window
7158                .update(cx, |editor, cx| {
7159                    let snapshot = editor.snapshot(cx);
7160                    let edit_start = DisplayPoint::new(DisplayRow(0), 0);
7161                    let edits = vec![
7162                        (
7163                            snapshot.buffer_snapshot.anchor_after(Point::new(0, 0))
7164                                ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 5)),
7165                            "Greetings".into(),
7166                        ),
7167                        (
7168                            snapshot.buffer_snapshot.anchor_after(Point::new(0, 12))
7169                                ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 13)),
7170                            " and universe".into(),
7171                        ),
7172                    ];
7173
7174                    let (text, highlights) =
7175                        inline_completion_popover_text(edit_start, &snapshot, &edits, cx);
7176
7177                    assert_eq!(text, "Greetings, world and universe");
7178                    assert_eq!(highlights.len(), 2);
7179                    assert_eq!(highlights[0].0, 0..9);
7180                    assert_eq!(highlights[1].0, 16..29);
7181                    assert_eq!(
7182                        highlights[0].1.background_color,
7183                        Some(cx.theme().status().created_background)
7184                    );
7185                    assert_eq!(
7186                        highlights[1].1.background_color,
7187                        Some(cx.theme().status().created_background)
7188                    );
7189                })
7190                .unwrap();
7191        }
7192
7193        // Test case 4: Multiple lines with edits
7194        {
7195            let window = cx.add_window(|cx| {
7196                let buffer = MultiBuffer::build_simple(
7197                    "First line\nSecond line\nThird line\nFourth line",
7198                    cx,
7199                );
7200                Editor::new(EditorMode::Full, buffer, None, true, cx)
7201            });
7202            let cx = &mut VisualTestContext::from_window(*window, cx);
7203
7204            window
7205                .update(cx, |editor, cx| {
7206                    let snapshot = editor.snapshot(cx);
7207                    let edit_start = DisplayPoint::new(DisplayRow(1), 0);
7208                    let edits = vec![
7209                        (
7210                            snapshot.buffer_snapshot.anchor_before(Point::new(1, 7))
7211                                ..snapshot.buffer_snapshot.anchor_before(Point::new(1, 11)),
7212                            "modified".to_string(),
7213                        ),
7214                        (
7215                            snapshot.buffer_snapshot.anchor_before(Point::new(2, 0))
7216                                ..snapshot.buffer_snapshot.anchor_before(Point::new(2, 10)),
7217                            "New third line".to_string(),
7218                        ),
7219                        (
7220                            snapshot.buffer_snapshot.anchor_before(Point::new(3, 6))
7221                                ..snapshot.buffer_snapshot.anchor_before(Point::new(3, 6)),
7222                            " updated".to_string(),
7223                        ),
7224                    ];
7225
7226                    let (text, highlights) =
7227                        inline_completion_popover_text(edit_start, &snapshot, &edits, cx);
7228
7229                    assert_eq!(text, "Second modified\nNew third line\nFourth updated");
7230                    assert_eq!(highlights.len(), 3);
7231                    assert_eq!(highlights[0].0, 7..15); // "modified"
7232                    assert_eq!(highlights[1].0, 16..30); // "New third line"
7233                    assert_eq!(highlights[2].0, 37..45); // " updated"
7234
7235                    for highlight in &highlights {
7236                        assert_eq!(
7237                            highlight.1.background_color,
7238                            Some(cx.theme().status().created_background)
7239                        );
7240                    }
7241                })
7242                .unwrap();
7243        }
7244    }
7245
7246    fn collect_invisibles_from_new_editor(
7247        cx: &mut TestAppContext,
7248        editor_mode: EditorMode,
7249        input_text: &str,
7250        editor_width: Pixels,
7251        show_line_numbers: bool,
7252    ) -> Vec<Invisible> {
7253        info!(
7254            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
7255            editor_width.0
7256        );
7257        let window = cx.add_window(|cx| {
7258            let buffer = MultiBuffer::build_simple(input_text, cx);
7259            Editor::new(editor_mode, buffer, None, true, cx)
7260        });
7261        let cx = &mut VisualTestContext::from_window(*window, cx);
7262        let editor = window.root(cx).unwrap();
7263
7264        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
7265        window
7266            .update(cx, |editor, cx| {
7267                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
7268                editor.set_wrap_width(Some(editor_width), cx);
7269                editor.set_show_line_numbers(show_line_numbers, cx);
7270            })
7271            .unwrap();
7272        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
7273            EditorElement::new(&editor, style)
7274        });
7275        state
7276            .position_map
7277            .line_layouts
7278            .iter()
7279            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
7280            .cloned()
7281            .collect()
7282    }
7283}