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