element.rs

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