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