element.rs

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