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