element.rs

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