element.rs

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