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