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