element.rs

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