element.rs

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