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