element.rs

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