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, 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        div()
2402            .px(header_padding)
2403            .pt(header_padding)
2404            .w_full()
2405            .h(FILE_HEADER_HEIGHT as f32 * cx.line_height())
2406            .child(
2407                h_flex()
2408                    .id("path header block")
2409                    .size_full()
2410                    .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
2411                    .px(gpui::px(12.))
2412                    .rounded_md()
2413                    .shadow_md()
2414                    .border_1()
2415                    .border_color(cx.theme().colors().border)
2416                    .bg(cx.theme().colors().editor_subheader_background)
2417                    .justify_between()
2418                    .hover(|style| style.bg(cx.theme().colors().element_hover))
2419                    .child(
2420                        h_flex()
2421                            .gap_3()
2422                            .map(|header| {
2423                                let editor = self.editor.clone();
2424                                let buffer_id = for_excerpt.buffer_id;
2425                                let toggle_chevron_icon =
2426                                    FileIcons::get_chevron_icon(!is_folded, cx)
2427                                        .map(Icon::from_path);
2428                                header.child(
2429                                    ButtonLike::new("toggle-buffer-fold")
2430                                        .children(toggle_chevron_icon)
2431                                        .on_click(move |_, cx| {
2432                                            if is_folded {
2433                                                editor.update(cx, |editor, cx| {
2434                                                    editor.unfold_buffer(buffer_id, cx);
2435                                                });
2436                                            } else {
2437                                                editor.update(cx, |editor, cx| {
2438                                                    editor.fold_buffer(buffer_id, cx);
2439                                                });
2440                                            }
2441                                        }),
2442                                )
2443                            })
2444                            .child(
2445                                h_flex()
2446                                    .gap_2()
2447                                    .child(
2448                                        filename
2449                                            .map(SharedString::from)
2450                                            .unwrap_or_else(|| "untitled".into()),
2451                                    )
2452                                    .when_some(parent_path, |then, path| {
2453                                        then.child(
2454                                            div()
2455                                                .child(path)
2456                                                .text_color(cx.theme().colors().text_muted),
2457                                        )
2458                                    }),
2459                            ),
2460                    )
2461                    .child(Icon::new(IconName::ArrowUpRight))
2462                    .cursor_pointer()
2463                    .tooltip(|cx| Tooltip::for_action("Jump to File", &OpenExcerpts, cx))
2464                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
2465                    .on_click(cx.listener_for(&self.editor, {
2466                        move |editor, e: &ClickEvent, cx| {
2467                            editor.open_excerpts_common(
2468                                Some(jump_data.clone()),
2469                                e.down.modifiers.secondary(),
2470                                cx,
2471                            );
2472                        }
2473                    })),
2474            )
2475    }
2476
2477    fn render_expand_excerpt_button(
2478        &self,
2479        excerpt_id: ExcerptId,
2480        direction: ExpandExcerptDirection,
2481        icon: IconName,
2482        cx: &mut WindowContext,
2483    ) -> ButtonLike {
2484        ButtonLike::new("expand-icon")
2485            .style(ButtonStyle::Transparent)
2486            .child(
2487                svg()
2488                    .path(icon.path())
2489                    .size(IconSize::XSmall.rems())
2490                    .text_color(cx.theme().colors().editor_line_number)
2491                    .group("")
2492                    .hover(|style| style.text_color(cx.theme().colors().editor_active_line_number)),
2493            )
2494            .on_click(cx.listener_for(&self.editor, {
2495                move |editor, _, cx| {
2496                    editor.expand_excerpt(excerpt_id, direction, cx);
2497                }
2498            }))
2499            .tooltip({
2500                move |cx| Tooltip::for_action("Expand Excerpt", &ExpandExcerpts { lines: 0 }, cx)
2501            })
2502    }
2503
2504    #[allow(clippy::too_many_arguments)]
2505    fn render_blocks(
2506        &self,
2507        rows: Range<DisplayRow>,
2508        snapshot: &EditorSnapshot,
2509        hitbox: &Hitbox,
2510        text_hitbox: &Hitbox,
2511        editor_width: Pixels,
2512        scroll_width: &mut Pixels,
2513        gutter_dimensions: &GutterDimensions,
2514        em_width: Pixels,
2515        text_x: Pixels,
2516        line_height: Pixels,
2517        line_layouts: &[LineWithInvisibles],
2518        selections: &[Selection<Point>],
2519        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2520        cx: &mut WindowContext,
2521    ) -> Result<Vec<BlockLayout>, HashMap<CustomBlockId, u32>> {
2522        let (fixed_blocks, non_fixed_blocks) = snapshot
2523            .blocks_in_range(rows.clone())
2524            .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
2525
2526        let mut focused_block = self
2527            .editor
2528            .update(cx, |editor, _| editor.take_focused_block());
2529        let mut fixed_block_max_width = Pixels::ZERO;
2530        let mut blocks = Vec::new();
2531        let mut resized_blocks = HashMap::default();
2532
2533        for (row, block) in fixed_blocks {
2534            let block_id = block.id();
2535
2536            if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2537                focused_block = None;
2538            }
2539
2540            let (element, element_size) = self.render_block(
2541                block,
2542                AvailableSpace::MinContent,
2543                block_id,
2544                row,
2545                snapshot,
2546                text_x,
2547                &rows,
2548                line_layouts,
2549                gutter_dimensions,
2550                line_height,
2551                em_width,
2552                text_hitbox,
2553                editor_width,
2554                scroll_width,
2555                &mut resized_blocks,
2556                selections,
2557                is_row_soft_wrapped,
2558                cx,
2559            );
2560            fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2561            blocks.push(BlockLayout {
2562                id: block_id,
2563                row: Some(row),
2564                element,
2565                available_space: size(AvailableSpace::MinContent, element_size.height.into()),
2566                style: BlockStyle::Fixed,
2567            });
2568        }
2569        for (row, block) in non_fixed_blocks {
2570            let style = block.style();
2571            let width = match style {
2572                BlockStyle::Sticky => hitbox.size.width,
2573                BlockStyle::Flex => hitbox
2574                    .size
2575                    .width
2576                    .max(fixed_block_max_width)
2577                    .max(gutter_dimensions.width + *scroll_width),
2578                BlockStyle::Fixed => unreachable!(),
2579            };
2580            let block_id = block.id();
2581
2582            if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2583                focused_block = None;
2584            }
2585
2586            let (element, element_size) = self.render_block(
2587                block,
2588                width.into(),
2589                block_id,
2590                row,
2591                snapshot,
2592                text_x,
2593                &rows,
2594                line_layouts,
2595                gutter_dimensions,
2596                line_height,
2597                em_width,
2598                text_hitbox,
2599                editor_width,
2600                scroll_width,
2601                &mut resized_blocks,
2602                selections,
2603                is_row_soft_wrapped,
2604                cx,
2605            );
2606
2607            blocks.push(BlockLayout {
2608                id: block_id,
2609                row: Some(row),
2610                element,
2611                available_space: size(width.into(), element_size.height.into()),
2612                style,
2613            });
2614        }
2615
2616        if let Some(focused_block) = focused_block {
2617            if let Some(focus_handle) = focused_block.focus_handle.upgrade() {
2618                if focus_handle.is_focused(cx) {
2619                    if let Some(block) = snapshot.block_for_id(focused_block.id) {
2620                        let style = block.style();
2621                        let width = match style {
2622                            BlockStyle::Fixed => AvailableSpace::MinContent,
2623                            BlockStyle::Flex => AvailableSpace::Definite(
2624                                hitbox
2625                                    .size
2626                                    .width
2627                                    .max(fixed_block_max_width)
2628                                    .max(gutter_dimensions.width + *scroll_width),
2629                            ),
2630                            BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
2631                        };
2632
2633                        let (element, element_size) = self.render_block(
2634                            &block,
2635                            width,
2636                            focused_block.id,
2637                            rows.end,
2638                            snapshot,
2639                            text_x,
2640                            &rows,
2641                            line_layouts,
2642                            gutter_dimensions,
2643                            line_height,
2644                            em_width,
2645                            text_hitbox,
2646                            editor_width,
2647                            scroll_width,
2648                            &mut resized_blocks,
2649                            selections,
2650                            is_row_soft_wrapped,
2651                            cx,
2652                        );
2653
2654                        blocks.push(BlockLayout {
2655                            id: block.id(),
2656                            row: None,
2657                            element,
2658                            available_space: size(width, element_size.height.into()),
2659                            style,
2660                        });
2661                    }
2662                }
2663            }
2664        }
2665
2666        if resized_blocks.is_empty() {
2667            *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
2668            Ok(blocks)
2669        } else {
2670            Err(resized_blocks)
2671        }
2672    }
2673
2674    /// Returns true if any of the blocks changed size since the previous frame. This will trigger
2675    /// a restart of rendering for the editor based on the new sizes.
2676    fn layout_blocks(
2677        &self,
2678        blocks: &mut Vec<BlockLayout>,
2679        block_starts: &mut HashSet<DisplayRow>,
2680        hitbox: &Hitbox,
2681        line_height: Pixels,
2682        scroll_pixel_position: gpui::Point<Pixels>,
2683        cx: &mut WindowContext,
2684    ) {
2685        for block in blocks {
2686            let mut origin = if let Some(row) = block.row {
2687                block_starts.insert(row);
2688                hitbox.origin
2689                    + point(
2690                        Pixels::ZERO,
2691                        row.as_f32() * line_height - scroll_pixel_position.y,
2692                    )
2693            } else {
2694                // Position the block outside the visible area
2695                hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
2696            };
2697
2698            if !matches!(block.style, BlockStyle::Sticky) {
2699                origin += point(-scroll_pixel_position.x, Pixels::ZERO);
2700            }
2701
2702            let focus_handle = block
2703                .element
2704                .prepaint_as_root(origin, block.available_space, cx);
2705
2706            if let Some(focus_handle) = focus_handle {
2707                self.editor.update(cx, |editor, _cx| {
2708                    editor.set_focused_block(FocusedBlock {
2709                        id: block.id,
2710                        focus_handle: focus_handle.downgrade(),
2711                    });
2712                });
2713            }
2714        }
2715    }
2716
2717    #[allow(clippy::too_many_arguments)]
2718    fn layout_context_menu(
2719        &self,
2720        line_height: Pixels,
2721        hitbox: &Hitbox,
2722        text_hitbox: &Hitbox,
2723        content_origin: gpui::Point<Pixels>,
2724        start_row: DisplayRow,
2725        scroll_pixel_position: gpui::Point<Pixels>,
2726        line_layouts: &[LineWithInvisibles],
2727        newest_selection_head: DisplayPoint,
2728        gutter_overshoot: Pixels,
2729        cx: &mut WindowContext,
2730    ) -> bool {
2731        let max_height = cmp::min(
2732            12. * line_height,
2733            cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
2734        );
2735        let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
2736            if editor.context_menu_visible() {
2737                editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
2738            } else {
2739                None
2740            }
2741        }) else {
2742            return false;
2743        };
2744
2745        let context_menu_size = context_menu.layout_as_root(AvailableSpace::min_size(), cx);
2746
2747        let (x, y) = match position {
2748            crate::ContextMenuOrigin::EditorPoint(point) => {
2749                let cursor_row_layout = &line_layouts[point.row().minus(start_row) as usize];
2750                let x = cursor_row_layout.x_for_index(point.column() as usize)
2751                    - scroll_pixel_position.x;
2752                let y = point.row().next_row().as_f32() * line_height - scroll_pixel_position.y;
2753                (x, y)
2754            }
2755            crate::ContextMenuOrigin::GutterIndicator(row) => {
2756                // 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
2757                // text field.
2758                let x = -gutter_overshoot;
2759                let y = row.next_row().as_f32() * line_height - scroll_pixel_position.y;
2760                (x, y)
2761            }
2762        };
2763
2764        let mut list_origin = content_origin + point(x, y);
2765        let list_width = context_menu_size.width;
2766        let list_height = context_menu_size.height;
2767
2768        // Snap the right edge of the list to the right edge of the window if
2769        // its horizontal bounds overflow.
2770        if list_origin.x + list_width > cx.viewport_size().width {
2771            list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
2772        }
2773
2774        if list_origin.y + list_height > text_hitbox.lower_right().y {
2775            list_origin.y -= line_height + list_height;
2776        }
2777
2778        cx.defer_draw(context_menu, list_origin, 1);
2779        true
2780    }
2781
2782    #[allow(clippy::too_many_arguments)]
2783    fn layout_inline_completion_popover(
2784        &self,
2785        text_bounds: &Bounds<Pixels>,
2786        editor_snapshot: &EditorSnapshot,
2787        visible_row_range: Range<DisplayRow>,
2788        scroll_top: f32,
2789        scroll_bottom: f32,
2790        line_layouts: &[LineWithInvisibles],
2791        line_height: Pixels,
2792        scroll_pixel_position: gpui::Point<Pixels>,
2793        editor_width: Pixels,
2794        style: &EditorStyle,
2795        cx: &mut WindowContext,
2796    ) -> Option<AnyElement> {
2797        const PADDING_X: Pixels = Pixels(25.);
2798        const PADDING_Y: Pixels = Pixels(2.);
2799
2800        let active_inline_completion = self.editor.read(cx).active_inline_completion.as_ref()?;
2801
2802        match &active_inline_completion.completion {
2803            InlineCompletion::Move(target_position) => {
2804                let tab_kbd = h_flex()
2805                    .px_0p5()
2806                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
2807                    .text_size(TextSize::XSmall.rems(cx))
2808                    .text_color(cx.theme().colors().text.opacity(0.8))
2809                    .child("tab");
2810
2811                let icon_container = div().mt(px(2.5)); // For optical alignment
2812
2813                let container_element = h_flex()
2814                    .items_center()
2815                    .py_0p5()
2816                    .px_1()
2817                    .gap_1()
2818                    .bg(cx.theme().colors().editor_subheader_background)
2819                    .border_1()
2820                    .border_color(cx.theme().colors().text_accent.opacity(0.2))
2821                    .rounded_md()
2822                    .shadow_sm();
2823
2824                let target_display_point = target_position.to_display_point(editor_snapshot);
2825                if target_display_point.row().as_f32() < scroll_top {
2826                    let mut element = container_element
2827                        .child(tab_kbd)
2828                        .child(Label::new("Jump to Edit").size(LabelSize::Small))
2829                        .child(
2830                            icon_container
2831                                .child(Icon::new(IconName::ArrowUp).size(IconSize::Small)),
2832                        )
2833                        .into_any();
2834                    let size = element.layout_as_root(AvailableSpace::min_size(), cx);
2835                    let offset = point((text_bounds.size.width - size.width) / 2., PADDING_Y);
2836                    element.prepaint_at(text_bounds.origin + offset, cx);
2837                    Some(element)
2838                } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
2839                    let mut element = container_element
2840                        .child(tab_kbd)
2841                        .child(Label::new("Jump to Edit").size(LabelSize::Small))
2842                        .child(
2843                            icon_container
2844                                .child(Icon::new(IconName::ArrowDown).size(IconSize::Small)),
2845                        )
2846                        .into_any();
2847                    let size = element.layout_as_root(AvailableSpace::min_size(), cx);
2848                    let offset = point(
2849                        (text_bounds.size.width - size.width) / 2.,
2850                        text_bounds.size.height - size.height - PADDING_Y,
2851                    );
2852                    element.prepaint_at(text_bounds.origin + offset, cx);
2853                    Some(element)
2854                } else {
2855                    let mut element = container_element
2856                        .child(tab_kbd)
2857                        .child(Label::new("Jump to Edit").size(LabelSize::Small))
2858                        .into_any();
2859
2860                    let target_line_end = DisplayPoint::new(
2861                        target_display_point.row(),
2862                        editor_snapshot.line_len(target_display_point.row()),
2863                    );
2864                    let origin = self.editor.update(cx, |editor, cx| {
2865                        editor.display_to_pixel_point(target_line_end, editor_snapshot, cx)
2866                    })?;
2867                    element.prepaint_as_root(
2868                        text_bounds.origin + origin + point(PADDING_X, px(0.)),
2869                        AvailableSpace::min_size(),
2870                        cx,
2871                    );
2872                    Some(element)
2873                }
2874            }
2875            InlineCompletion::Edit(edits) => {
2876                let edit_start = edits
2877                    .first()
2878                    .unwrap()
2879                    .0
2880                    .start
2881                    .to_display_point(editor_snapshot);
2882                let edit_end = edits
2883                    .last()
2884                    .unwrap()
2885                    .0
2886                    .end
2887                    .to_display_point(editor_snapshot);
2888
2889                let is_visible = visible_row_range.contains(&edit_start.row())
2890                    || visible_row_range.contains(&edit_end.row());
2891                if !is_visible {
2892                    return None;
2893                }
2894
2895                if all_edits_insertions_or_deletions(edits, &editor_snapshot.buffer_snapshot) {
2896                    return None;
2897                }
2898
2899                let (text, highlights) = inline_completion_popover_text(editor_snapshot, edits, cx);
2900
2901                let longest_row =
2902                    editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
2903                let longest_line_width = if visible_row_range.contains(&longest_row) {
2904                    line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
2905                } else {
2906                    layout_line(
2907                        longest_row,
2908                        editor_snapshot,
2909                        style,
2910                        editor_width,
2911                        |_| false,
2912                        cx,
2913                    )
2914                    .width
2915                };
2916
2917                let text = gpui::StyledText::new(text).with_highlights(&style.text, highlights);
2918
2919                let mut element = div()
2920                    .bg(cx.theme().colors().editor_background)
2921                    .border_1()
2922                    .border_color(cx.theme().colors().border)
2923                    .rounded_md()
2924                    .px_1()
2925                    .child(text)
2926                    .into_any();
2927
2928                let origin = text_bounds.origin
2929                    + point(
2930                        longest_line_width + PADDING_X - scroll_pixel_position.x,
2931                        edit_start.row().as_f32() * line_height - scroll_pixel_position.y,
2932                    );
2933                element.prepaint_as_root(origin, AvailableSpace::min_size(), cx);
2934                Some(element)
2935            }
2936        }
2937    }
2938
2939    fn layout_mouse_context_menu(
2940        &self,
2941        editor_snapshot: &EditorSnapshot,
2942        visible_range: Range<DisplayRow>,
2943        content_origin: gpui::Point<Pixels>,
2944        cx: &mut WindowContext,
2945    ) -> Option<AnyElement> {
2946        let position = self.editor.update(cx, |editor, cx| {
2947            let visible_start_point = editor.display_to_pixel_point(
2948                DisplayPoint::new(visible_range.start, 0),
2949                editor_snapshot,
2950                cx,
2951            )?;
2952            let visible_end_point = editor.display_to_pixel_point(
2953                DisplayPoint::new(visible_range.end, 0),
2954                editor_snapshot,
2955                cx,
2956            )?;
2957
2958            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
2959            let (source_display_point, position) = match mouse_context_menu.position {
2960                MenuPosition::PinnedToScreen(point) => (None, point),
2961                MenuPosition::PinnedToEditor { source, offset } => {
2962                    let source_display_point = source.to_display_point(editor_snapshot);
2963                    let source_point = editor.to_pixel_point(source, editor_snapshot, cx)?;
2964                    let position = content_origin + source_point + offset;
2965                    (Some(source_display_point), position)
2966                }
2967            };
2968
2969            let source_included = source_display_point.map_or(true, |source_display_point| {
2970                visible_range
2971                    .to_inclusive()
2972                    .contains(&source_display_point.row())
2973            });
2974            let position_included =
2975                visible_start_point.y <= position.y && position.y <= visible_end_point.y;
2976            if !source_included && !position_included {
2977                None
2978            } else {
2979                Some(position)
2980            }
2981        })?;
2982
2983        let mut element = self.editor.update(cx, |editor, _| {
2984            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
2985            let context_menu = mouse_context_menu.context_menu.clone();
2986
2987            Some(
2988                deferred(
2989                    anchored()
2990                        .position(position)
2991                        .child(context_menu)
2992                        .anchor(AnchorCorner::TopLeft)
2993                        .snap_to_window_with_margin(px(8.)),
2994                )
2995                .with_priority(1)
2996                .into_any(),
2997            )
2998        })?;
2999
3000        element.prepaint_as_root(position, AvailableSpace::min_size(), cx);
3001        Some(element)
3002    }
3003
3004    #[allow(clippy::too_many_arguments)]
3005    fn layout_hover_popovers(
3006        &self,
3007        snapshot: &EditorSnapshot,
3008        hitbox: &Hitbox,
3009        text_hitbox: &Hitbox,
3010        visible_display_row_range: Range<DisplayRow>,
3011        content_origin: gpui::Point<Pixels>,
3012        scroll_pixel_position: gpui::Point<Pixels>,
3013        line_layouts: &[LineWithInvisibles],
3014        line_height: Pixels,
3015        em_width: Pixels,
3016        cx: &mut WindowContext,
3017    ) {
3018        struct MeasuredHoverPopover {
3019            element: AnyElement,
3020            size: Size<Pixels>,
3021            horizontal_offset: Pixels,
3022        }
3023
3024        let max_size = size(
3025            (120. * em_width) // Default size
3026                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
3027                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3028            (16. * line_height) // Default size
3029                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
3030                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3031        );
3032
3033        let hover_popovers = self.editor.update(cx, |editor, cx| {
3034            editor
3035                .hover_state
3036                .render(snapshot, visible_display_row_range.clone(), max_size, cx)
3037        });
3038        let Some((position, hover_popovers)) = hover_popovers else {
3039            return;
3040        };
3041
3042        // This is safe because we check on layout whether the required row is available
3043        let hovered_row_layout =
3044            &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
3045
3046        // Compute Hovered Point
3047        let x =
3048            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
3049        let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
3050        let hovered_point = content_origin + point(x, y);
3051
3052        let mut overall_height = Pixels::ZERO;
3053        let mut measured_hover_popovers = Vec::new();
3054        for mut hover_popover in hover_popovers {
3055            let size = hover_popover.layout_as_root(AvailableSpace::min_size(), cx);
3056            let horizontal_offset =
3057                (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
3058
3059            overall_height += HOVER_POPOVER_GAP + size.height;
3060
3061            measured_hover_popovers.push(MeasuredHoverPopover {
3062                element: hover_popover,
3063                size,
3064                horizontal_offset,
3065            });
3066        }
3067        overall_height += HOVER_POPOVER_GAP;
3068
3069        fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
3070            let mut occlusion = div()
3071                .size_full()
3072                .occlude()
3073                .on_mouse_move(|_, cx| cx.stop_propagation())
3074                .into_any_element();
3075            occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), cx);
3076            cx.defer_draw(occlusion, origin, 2);
3077        }
3078
3079        if hovered_point.y > overall_height {
3080            // There is enough space above. Render popovers above the hovered point
3081            let mut current_y = hovered_point.y;
3082            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3083                let size = popover.size;
3084                let popover_origin = point(
3085                    hovered_point.x + popover.horizontal_offset,
3086                    current_y - size.height,
3087                );
3088
3089                cx.defer_draw(popover.element, popover_origin, 2);
3090                if position != itertools::Position::Last {
3091                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
3092                    draw_occluder(size.width, origin, cx);
3093                }
3094
3095                current_y = popover_origin.y - HOVER_POPOVER_GAP;
3096            }
3097        } else {
3098            // There is not enough space above. Render popovers below the hovered point
3099            let mut current_y = hovered_point.y + line_height;
3100            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3101                let size = popover.size;
3102                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
3103
3104                cx.defer_draw(popover.element, popover_origin, 2);
3105                if position != itertools::Position::Last {
3106                    let origin = point(popover_origin.x, popover_origin.y + size.height);
3107                    draw_occluder(size.width, origin, cx);
3108                }
3109
3110                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
3111            }
3112        }
3113    }
3114
3115    #[allow(clippy::too_many_arguments)]
3116    fn layout_signature_help(
3117        &self,
3118        hitbox: &Hitbox,
3119        content_origin: gpui::Point<Pixels>,
3120        scroll_pixel_position: gpui::Point<Pixels>,
3121        newest_selection_head: Option<DisplayPoint>,
3122        start_row: DisplayRow,
3123        line_layouts: &[LineWithInvisibles],
3124        line_height: Pixels,
3125        em_width: Pixels,
3126        cx: &mut WindowContext,
3127    ) {
3128        if !self.editor.focus_handle(cx).is_focused(cx) {
3129            return;
3130        }
3131        let Some(newest_selection_head) = newest_selection_head else {
3132            return;
3133        };
3134        let selection_row = newest_selection_head.row();
3135        if selection_row < start_row {
3136            return;
3137        }
3138        let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
3139        else {
3140            return;
3141        };
3142
3143        let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
3144            - scroll_pixel_position.x
3145            + content_origin.x;
3146        let start_y =
3147            selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
3148
3149        let max_size = size(
3150            (120. * em_width) // Default size
3151                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
3152                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3153            (16. * line_height) // Default size
3154                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
3155                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3156        );
3157
3158        let maybe_element = self.editor.update(cx, |editor, cx| {
3159            if let Some(popover) = editor.signature_help_state.popover_mut() {
3160                let element = popover.render(
3161                    &self.style,
3162                    max_size,
3163                    editor.workspace.as_ref().map(|(w, _)| w.clone()),
3164                    cx,
3165                );
3166                Some(element)
3167            } else {
3168                None
3169            }
3170        });
3171        if let Some(mut element) = maybe_element {
3172            let window_size = cx.viewport_size();
3173            let size = element.layout_as_root(Size::<AvailableSpace>::default(), cx);
3174            let mut point = point(start_x, start_y - size.height);
3175
3176            // Adjusting to ensure the popover does not overflow in the X-axis direction.
3177            if point.x + size.width >= window_size.width {
3178                point.x = window_size.width - size.width;
3179            }
3180
3181            cx.defer_draw(element, point, 1)
3182        }
3183    }
3184
3185    fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
3186        cx.paint_layer(layout.hitbox.bounds, |cx| {
3187            let scroll_top = layout.position_map.snapshot.scroll_position().y;
3188            let gutter_bg = cx.theme().colors().editor_gutter_background;
3189            cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
3190            cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
3191
3192            if let EditorMode::Full = layout.mode {
3193                let mut active_rows = layout.active_rows.iter().peekable();
3194                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
3195                    let mut end_row = start_row.0;
3196                    while active_rows
3197                        .peek()
3198                        .map_or(false, |(active_row, has_selection)| {
3199                            active_row.0 == end_row + 1
3200                                && *has_selection == contains_non_empty_selection
3201                        })
3202                    {
3203                        active_rows.next().unwrap();
3204                        end_row += 1;
3205                    }
3206
3207                    if !contains_non_empty_selection {
3208                        let highlight_h_range =
3209                            match layout.position_map.snapshot.current_line_highlight {
3210                                CurrentLineHighlight::Gutter => Some(Range {
3211                                    start: layout.hitbox.left(),
3212                                    end: layout.gutter_hitbox.right(),
3213                                }),
3214                                CurrentLineHighlight::Line => Some(Range {
3215                                    start: layout.text_hitbox.bounds.left(),
3216                                    end: layout.text_hitbox.bounds.right(),
3217                                }),
3218                                CurrentLineHighlight::All => Some(Range {
3219                                    start: layout.hitbox.left(),
3220                                    end: layout.hitbox.right(),
3221                                }),
3222                                CurrentLineHighlight::None => None,
3223                            };
3224                        if let Some(range) = highlight_h_range {
3225                            let active_line_bg = cx.theme().colors().editor_active_line_background;
3226                            let bounds = Bounds {
3227                                origin: point(
3228                                    range.start,
3229                                    layout.hitbox.origin.y
3230                                        + (start_row.as_f32() - scroll_top)
3231                                            * layout.position_map.line_height,
3232                                ),
3233                                size: size(
3234                                    range.end - range.start,
3235                                    layout.position_map.line_height
3236                                        * (end_row - start_row.0 + 1) as f32,
3237                                ),
3238                            };
3239                            cx.paint_quad(fill(bounds, active_line_bg));
3240                        }
3241                    }
3242                }
3243
3244                let mut paint_highlight =
3245                    |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
3246                        let origin = point(
3247                            layout.hitbox.origin.x,
3248                            layout.hitbox.origin.y
3249                                + (highlight_row_start.as_f32() - scroll_top)
3250                                    * layout.position_map.line_height,
3251                        );
3252                        let size = size(
3253                            layout.hitbox.size.width,
3254                            layout.position_map.line_height
3255                                * highlight_row_end.next_row().minus(highlight_row_start) as f32,
3256                        );
3257                        cx.paint_quad(fill(Bounds { origin, size }, color));
3258                    };
3259
3260                let mut current_paint: Option<(Hsla, Range<DisplayRow>)> = None;
3261                for (&new_row, &new_color) in &layout.highlighted_rows {
3262                    match &mut current_paint {
3263                        Some((current_color, current_range)) => {
3264                            let current_color = *current_color;
3265                            let new_range_started = current_color != new_color
3266                                || current_range.end.next_row() != new_row;
3267                            if new_range_started {
3268                                paint_highlight(
3269                                    current_range.start,
3270                                    current_range.end,
3271                                    current_color,
3272                                );
3273                                current_paint = Some((new_color, new_row..new_row));
3274                                continue;
3275                            } else {
3276                                current_range.end = current_range.end.next_row();
3277                            }
3278                        }
3279                        None => current_paint = Some((new_color, new_row..new_row)),
3280                    };
3281                }
3282                if let Some((color, range)) = current_paint {
3283                    paint_highlight(range.start, range.end, color);
3284                }
3285
3286                let scroll_left =
3287                    layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
3288
3289                for (wrap_position, active) in layout.wrap_guides.iter() {
3290                    let x = (layout.text_hitbox.origin.x
3291                        + *wrap_position
3292                        + layout.position_map.em_width / 2.)
3293                        - scroll_left;
3294
3295                    let show_scrollbars = layout
3296                        .scrollbar_layout
3297                        .as_ref()
3298                        .map_or(false, |scrollbar| scrollbar.visible);
3299                    if x < layout.text_hitbox.origin.x
3300                        || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
3301                    {
3302                        continue;
3303                    }
3304
3305                    let color = if *active {
3306                        cx.theme().colors().editor_active_wrap_guide
3307                    } else {
3308                        cx.theme().colors().editor_wrap_guide
3309                    };
3310                    cx.paint_quad(fill(
3311                        Bounds {
3312                            origin: point(x, layout.text_hitbox.origin.y),
3313                            size: size(px(1.), layout.text_hitbox.size.height),
3314                        },
3315                        color,
3316                    ));
3317                }
3318            }
3319        })
3320    }
3321
3322    fn paint_indent_guides(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3323        let Some(indent_guides) = &layout.indent_guides else {
3324            return;
3325        };
3326
3327        let faded_color = |color: Hsla, alpha: f32| {
3328            let mut faded = color;
3329            faded.a = alpha;
3330            faded
3331        };
3332
3333        for indent_guide in indent_guides {
3334            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
3335            let settings = indent_guide.settings;
3336
3337            // TODO fixed for now, expose them through themes later
3338            const INDENT_AWARE_ALPHA: f32 = 0.2;
3339            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
3340            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
3341            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
3342
3343            let line_color = match (settings.coloring, indent_guide.active) {
3344                (IndentGuideColoring::Disabled, _) => None,
3345                (IndentGuideColoring::Fixed, false) => {
3346                    Some(cx.theme().colors().editor_indent_guide)
3347                }
3348                (IndentGuideColoring::Fixed, true) => {
3349                    Some(cx.theme().colors().editor_indent_guide_active)
3350                }
3351                (IndentGuideColoring::IndentAware, false) => {
3352                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
3353                }
3354                (IndentGuideColoring::IndentAware, true) => {
3355                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
3356                }
3357            };
3358
3359            let background_color = match (settings.background_coloring, indent_guide.active) {
3360                (IndentGuideBackgroundColoring::Disabled, _) => None,
3361                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
3362                    indent_accent_colors,
3363                    INDENT_AWARE_BACKGROUND_ALPHA,
3364                )),
3365                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
3366                    indent_accent_colors,
3367                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
3368                )),
3369            };
3370
3371            let requested_line_width = if indent_guide.active {
3372                settings.active_line_width
3373            } else {
3374                settings.line_width
3375            }
3376            .clamp(1, 10);
3377            let mut line_indicator_width = 0.;
3378            if let Some(color) = line_color {
3379                cx.paint_quad(fill(
3380                    Bounds {
3381                        origin: indent_guide.origin,
3382                        size: size(px(requested_line_width as f32), indent_guide.length),
3383                    },
3384                    color,
3385                ));
3386                line_indicator_width = requested_line_width as f32;
3387            }
3388
3389            if let Some(color) = background_color {
3390                let width = indent_guide.single_indent_width - px(line_indicator_width);
3391                cx.paint_quad(fill(
3392                    Bounds {
3393                        origin: point(
3394                            indent_guide.origin.x + px(line_indicator_width),
3395                            indent_guide.origin.y,
3396                        ),
3397                        size: size(width, indent_guide.length),
3398                    },
3399                    color,
3400                ));
3401            }
3402        }
3403    }
3404
3405    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3406        let line_height = layout.position_map.line_height;
3407        let scroll_position = layout.position_map.snapshot.scroll_position();
3408        let scroll_top = scroll_position.y * line_height;
3409
3410        cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
3411
3412        for (ix, line) in layout.line_numbers.iter().enumerate() {
3413            if let Some(line) = line {
3414                let line_origin = layout.gutter_hitbox.origin
3415                    + point(
3416                        layout.gutter_hitbox.size.width
3417                            - line.width
3418                            - layout.gutter_dimensions.right_padding,
3419                        ix as f32 * line_height - (scroll_top % line_height),
3420                    );
3421
3422                line.paint(line_origin, line_height, cx).log_err();
3423            }
3424        }
3425    }
3426
3427    fn paint_diff_hunks(layout: &mut EditorLayout, cx: &mut WindowContext) {
3428        if layout.display_hunks.is_empty() {
3429            return;
3430        }
3431
3432        let line_height = layout.position_map.line_height;
3433        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3434            for (hunk, hitbox) in &layout.display_hunks {
3435                let hunk_to_paint = match hunk {
3436                    DisplayDiffHunk::Folded { .. } => {
3437                        let hunk_bounds = Self::diff_hunk_bounds(
3438                            &layout.position_map.snapshot,
3439                            line_height,
3440                            layout.gutter_hitbox.bounds,
3441                            hunk,
3442                        );
3443                        Some((
3444                            hunk_bounds,
3445                            cx.theme().status().modified,
3446                            Corners::all(px(0.)),
3447                        ))
3448                    }
3449                    DisplayDiffHunk::Unfolded { status, .. } => {
3450                        hitbox.as_ref().map(|hunk_hitbox| match status {
3451                            DiffHunkStatus::Added => (
3452                                hunk_hitbox.bounds,
3453                                cx.theme().status().created,
3454                                Corners::all(px(0.)),
3455                            ),
3456                            DiffHunkStatus::Modified => (
3457                                hunk_hitbox.bounds,
3458                                cx.theme().status().modified,
3459                                Corners::all(px(0.)),
3460                            ),
3461                            DiffHunkStatus::Removed => (
3462                                Bounds::new(
3463                                    point(
3464                                        hunk_hitbox.origin.x - hunk_hitbox.size.width,
3465                                        hunk_hitbox.origin.y,
3466                                    ),
3467                                    size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
3468                                ),
3469                                cx.theme().status().deleted,
3470                                Corners::all(1. * line_height),
3471                            ),
3472                        })
3473                    }
3474                };
3475
3476                if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
3477                    cx.paint_quad(quad(
3478                        hunk_bounds,
3479                        corner_radii,
3480                        background_color,
3481                        Edges::default(),
3482                        transparent_black(),
3483                    ));
3484                }
3485            }
3486        });
3487    }
3488
3489    pub(super) fn diff_hunk_bounds(
3490        snapshot: &EditorSnapshot,
3491        line_height: Pixels,
3492        gutter_bounds: Bounds<Pixels>,
3493        hunk: &DisplayDiffHunk,
3494    ) -> Bounds<Pixels> {
3495        let scroll_position = snapshot.scroll_position();
3496        let scroll_top = scroll_position.y * line_height;
3497
3498        match hunk {
3499            DisplayDiffHunk::Folded { display_row, .. } => {
3500                let start_y = display_row.as_f32() * line_height - scroll_top;
3501                let end_y = start_y + line_height;
3502
3503                let width = Self::diff_hunk_strip_width(line_height);
3504                let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3505                let highlight_size = size(width, end_y - start_y);
3506                Bounds::new(highlight_origin, highlight_size)
3507            }
3508            DisplayDiffHunk::Unfolded {
3509                display_row_range,
3510                status,
3511                ..
3512            } => match status {
3513                DiffHunkStatus::Added | DiffHunkStatus::Modified => {
3514                    let start_row = display_row_range.start;
3515                    let end_row = display_row_range.end;
3516                    // If we're in a multibuffer, row range span might include an
3517                    // excerpt header, so if we were to draw the marker straight away,
3518                    // the hunk might include the rows of that header.
3519                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
3520                    // Instead, we simply check whether the range we're dealing with includes
3521                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
3522                    let end_row_in_current_excerpt = snapshot
3523                        .blocks_in_range(start_row..end_row)
3524                        .find_map(|(start_row, block)| {
3525                            if matches!(block, Block::ExcerptBoundary { .. }) {
3526                                Some(start_row)
3527                            } else {
3528                                None
3529                            }
3530                        })
3531                        .unwrap_or(end_row);
3532
3533                    let start_y = start_row.as_f32() * line_height - scroll_top;
3534                    let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
3535
3536                    let width = Self::diff_hunk_strip_width(line_height);
3537                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3538                    let highlight_size = size(width, end_y - start_y);
3539                    Bounds::new(highlight_origin, highlight_size)
3540                }
3541                DiffHunkStatus::Removed => {
3542                    let row = display_row_range.start;
3543
3544                    let offset = line_height / 2.;
3545                    let start_y = row.as_f32() * line_height - offset - scroll_top;
3546                    let end_y = start_y + line_height;
3547
3548                    let width = (0.35 * line_height).floor();
3549                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3550                    let highlight_size = size(width, end_y - start_y);
3551                    Bounds::new(highlight_origin, highlight_size)
3552                }
3553            },
3554        }
3555    }
3556
3557    /// Returns the width of the diff strip that will be displayed in the gutter.
3558    pub(super) fn diff_hunk_strip_width(line_height: Pixels) -> Pixels {
3559        // We floor the value to prevent pixel rounding.
3560        (0.275 * line_height).floor()
3561    }
3562
3563    fn paint_gutter_indicators(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3564        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3565            cx.with_element_namespace("crease_toggles", |cx| {
3566                for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
3567                    crease_toggle.paint(cx);
3568                }
3569            });
3570
3571            for test_indicator in layout.test_indicators.iter_mut() {
3572                test_indicator.paint(cx);
3573            }
3574
3575            if let Some(indicator) = layout.code_actions_indicator.as_mut() {
3576                indicator.paint(cx);
3577            }
3578        });
3579    }
3580
3581    fn paint_gutter_highlights(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3582        for (_, hunk_hitbox) in &layout.display_hunks {
3583            if let Some(hunk_hitbox) = hunk_hitbox {
3584                cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
3585            }
3586        }
3587
3588        let show_git_gutter = layout
3589            .position_map
3590            .snapshot
3591            .show_git_diff_gutter
3592            .unwrap_or_else(|| {
3593                matches!(
3594                    ProjectSettings::get_global(cx).git.git_gutter,
3595                    Some(GitGutterSetting::TrackedFiles)
3596                )
3597            });
3598        if show_git_gutter {
3599            Self::paint_diff_hunks(layout, cx)
3600        }
3601
3602        let highlight_width = 0.275 * layout.position_map.line_height;
3603        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
3604        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3605            for (range, color) in &layout.highlighted_gutter_ranges {
3606                let start_row = if range.start.row() < layout.visible_display_row_range.start {
3607                    layout.visible_display_row_range.start - DisplayRow(1)
3608                } else {
3609                    range.start.row()
3610                };
3611                let end_row = if range.end.row() > layout.visible_display_row_range.end {
3612                    layout.visible_display_row_range.end + DisplayRow(1)
3613                } else {
3614                    range.end.row()
3615                };
3616
3617                let start_y = layout.gutter_hitbox.top()
3618                    + start_row.0 as f32 * layout.position_map.line_height
3619                    - layout.position_map.scroll_pixel_position.y;
3620                let end_y = layout.gutter_hitbox.top()
3621                    + (end_row.0 + 1) as f32 * layout.position_map.line_height
3622                    - layout.position_map.scroll_pixel_position.y;
3623                let bounds = Bounds::from_corners(
3624                    point(layout.gutter_hitbox.left(), start_y),
3625                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
3626                );
3627                cx.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
3628            }
3629        });
3630    }
3631
3632    fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3633        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
3634            return;
3635        };
3636
3637        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3638            for mut blame_element in blamed_display_rows.into_iter() {
3639                blame_element.paint(cx);
3640            }
3641        })
3642    }
3643
3644    fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3645        cx.with_content_mask(
3646            Some(ContentMask {
3647                bounds: layout.text_hitbox.bounds,
3648            }),
3649            |cx| {
3650                let cursor_style = if self
3651                    .editor
3652                    .read(cx)
3653                    .hovered_link_state
3654                    .as_ref()
3655                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
3656                {
3657                    CursorStyle::PointingHand
3658                } else {
3659                    CursorStyle::IBeam
3660                };
3661                cx.set_cursor_style(cursor_style, &layout.text_hitbox);
3662
3663                let invisible_display_ranges = self.paint_highlights(layout, cx);
3664                self.paint_lines(&invisible_display_ranges, layout, cx);
3665                self.paint_redactions(layout, cx);
3666                self.paint_cursors(layout, cx);
3667                self.paint_inline_blame(layout, cx);
3668                cx.with_element_namespace("crease_trailers", |cx| {
3669                    for trailer in layout.crease_trailers.iter_mut().flatten() {
3670                        trailer.element.paint(cx);
3671                    }
3672                });
3673            },
3674        )
3675    }
3676
3677    fn paint_highlights(
3678        &mut self,
3679        layout: &mut EditorLayout,
3680        cx: &mut WindowContext,
3681    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
3682        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3683            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
3684            let line_end_overshoot = 0.15 * layout.position_map.line_height;
3685            for (range, color) in &layout.highlighted_ranges {
3686                self.paint_highlighted_range(
3687                    range.clone(),
3688                    *color,
3689                    Pixels::ZERO,
3690                    line_end_overshoot,
3691                    layout,
3692                    cx,
3693                );
3694            }
3695
3696            let corner_radius = 0.15 * layout.position_map.line_height;
3697
3698            for (player_color, selections) in &layout.selections {
3699                for selection in selections.iter() {
3700                    self.paint_highlighted_range(
3701                        selection.range.clone(),
3702                        player_color.selection,
3703                        corner_radius,
3704                        corner_radius * 2.,
3705                        layout,
3706                        cx,
3707                    );
3708
3709                    if selection.is_local && !selection.range.is_empty() {
3710                        invisible_display_ranges.push(selection.range.clone());
3711                    }
3712                }
3713            }
3714            invisible_display_ranges
3715        })
3716    }
3717
3718    fn paint_lines(
3719        &mut self,
3720        invisible_display_ranges: &[Range<DisplayPoint>],
3721        layout: &mut EditorLayout,
3722        cx: &mut WindowContext,
3723    ) {
3724        let whitespace_setting = self
3725            .editor
3726            .read(cx)
3727            .buffer
3728            .read(cx)
3729            .settings_at(0, cx)
3730            .show_whitespaces;
3731
3732        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
3733            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
3734            line_with_invisibles.draw(
3735                layout,
3736                row,
3737                layout.content_origin,
3738                whitespace_setting,
3739                invisible_display_ranges,
3740                cx,
3741            )
3742        }
3743
3744        for line_element in &mut layout.line_elements {
3745            line_element.paint(cx);
3746        }
3747    }
3748
3749    fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3750        if layout.redacted_ranges.is_empty() {
3751            return;
3752        }
3753
3754        let line_end_overshoot = layout.line_end_overshoot();
3755
3756        // A softer than perfect black
3757        let redaction_color = gpui::rgb(0x0e1111);
3758
3759        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3760            for range in layout.redacted_ranges.iter() {
3761                self.paint_highlighted_range(
3762                    range.clone(),
3763                    redaction_color.into(),
3764                    Pixels::ZERO,
3765                    line_end_overshoot,
3766                    layout,
3767                    cx,
3768                );
3769            }
3770        });
3771    }
3772
3773    fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3774        for cursor in &mut layout.visible_cursors {
3775            cursor.paint(layout.content_origin, cx);
3776        }
3777    }
3778
3779    fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3780        let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
3781            return;
3782        };
3783
3784        let thumb_bounds = scrollbar_layout.thumb_bounds();
3785        if scrollbar_layout.visible {
3786            cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
3787                cx.paint_quad(quad(
3788                    scrollbar_layout.hitbox.bounds,
3789                    Corners::default(),
3790                    cx.theme().colors().scrollbar_track_background,
3791                    Edges {
3792                        top: Pixels::ZERO,
3793                        right: Pixels::ZERO,
3794                        bottom: Pixels::ZERO,
3795                        left: ScrollbarLayout::BORDER_WIDTH,
3796                    },
3797                    cx.theme().colors().scrollbar_track_border,
3798                ));
3799
3800                let fast_markers =
3801                    self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
3802                // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
3803                self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
3804
3805                let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
3806                for marker in markers.iter().chain(&fast_markers) {
3807                    let mut marker = marker.clone();
3808                    marker.bounds.origin += scrollbar_layout.hitbox.origin;
3809                    cx.paint_quad(marker);
3810                }
3811
3812                cx.paint_quad(quad(
3813                    thumb_bounds,
3814                    Corners::default(),
3815                    cx.theme().colors().scrollbar_thumb_background,
3816                    Edges {
3817                        top: Pixels::ZERO,
3818                        right: Pixels::ZERO,
3819                        bottom: Pixels::ZERO,
3820                        left: ScrollbarLayout::BORDER_WIDTH,
3821                    },
3822                    cx.theme().colors().scrollbar_thumb_border,
3823                ));
3824            });
3825        }
3826
3827        cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
3828
3829        let row_height = scrollbar_layout.row_height;
3830        let row_range = scrollbar_layout.visible_row_range.clone();
3831
3832        cx.on_mouse_event({
3833            let editor = self.editor.clone();
3834            let hitbox = scrollbar_layout.hitbox.clone();
3835            let mut mouse_position = cx.mouse_position();
3836            move |event: &MouseMoveEvent, phase, cx| {
3837                if phase == DispatchPhase::Capture {
3838                    return;
3839                }
3840
3841                editor.update(cx, |editor, cx| {
3842                    if event.pressed_button == Some(MouseButton::Left)
3843                        && editor.scroll_manager.is_dragging_scrollbar()
3844                    {
3845                        let y = mouse_position.y;
3846                        let new_y = event.position.y;
3847                        if (hitbox.top()..hitbox.bottom()).contains(&y) {
3848                            let mut position = editor.scroll_position(cx);
3849                            position.y += (new_y - y) / row_height;
3850                            if position.y < 0.0 {
3851                                position.y = 0.0;
3852                            }
3853                            editor.set_scroll_position(position, cx);
3854                        }
3855
3856                        cx.stop_propagation();
3857                    } else {
3858                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3859                        if hitbox.is_hovered(cx) {
3860                            editor.scroll_manager.show_scrollbar(cx);
3861                        }
3862                    }
3863                    mouse_position = event.position;
3864                })
3865            }
3866        });
3867
3868        if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
3869            cx.on_mouse_event({
3870                let editor = self.editor.clone();
3871                move |_: &MouseUpEvent, phase, cx| {
3872                    if phase == DispatchPhase::Capture {
3873                        return;
3874                    }
3875
3876                    editor.update(cx, |editor, cx| {
3877                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3878                        cx.stop_propagation();
3879                    });
3880                }
3881            });
3882        } else {
3883            cx.on_mouse_event({
3884                let editor = self.editor.clone();
3885                let hitbox = scrollbar_layout.hitbox.clone();
3886                move |event: &MouseDownEvent, phase, cx| {
3887                    if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
3888                        return;
3889                    }
3890
3891                    editor.update(cx, |editor, cx| {
3892                        editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
3893
3894                        let y = event.position.y;
3895                        if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
3896                            let center_row = ((y - hitbox.top()) / row_height).round() as u32;
3897                            let top_row = center_row
3898                                .saturating_sub((row_range.end - row_range.start) as u32 / 2);
3899                            let mut position = editor.scroll_position(cx);
3900                            position.y = top_row as f32;
3901                            editor.set_scroll_position(position, cx);
3902                        } else {
3903                            editor.scroll_manager.show_scrollbar(cx);
3904                        }
3905
3906                        cx.stop_propagation();
3907                    });
3908                }
3909            });
3910        }
3911    }
3912
3913    fn collect_fast_scrollbar_markers(
3914        &self,
3915        layout: &EditorLayout,
3916        scrollbar_layout: &ScrollbarLayout,
3917        cx: &mut WindowContext,
3918    ) -> Vec<PaintQuad> {
3919        const LIMIT: usize = 100;
3920        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
3921            return vec![];
3922        }
3923        let cursor_ranges = layout
3924            .cursors
3925            .iter()
3926            .map(|(point, color)| ColoredRange {
3927                start: point.row(),
3928                end: point.row(),
3929                color: *color,
3930            })
3931            .collect_vec();
3932        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
3933    }
3934
3935    fn refresh_slow_scrollbar_markers(
3936        &self,
3937        layout: &EditorLayout,
3938        scrollbar_layout: &ScrollbarLayout,
3939        cx: &mut WindowContext,
3940    ) {
3941        self.editor.update(cx, |editor, cx| {
3942            if !editor.is_singleton(cx)
3943                || !editor
3944                    .scrollbar_marker_state
3945                    .should_refresh(scrollbar_layout.hitbox.size)
3946            {
3947                return;
3948            }
3949
3950            let scrollbar_layout = scrollbar_layout.clone();
3951            let background_highlights = editor.background_highlights.clone();
3952            let snapshot = layout.position_map.snapshot.clone();
3953            let theme = cx.theme().clone();
3954            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
3955
3956            editor.scrollbar_marker_state.dirty = false;
3957            editor.scrollbar_marker_state.pending_refresh =
3958                Some(cx.spawn(|editor, mut cx| async move {
3959                    let scrollbar_size = scrollbar_layout.hitbox.size;
3960                    let scrollbar_markers = cx
3961                        .background_executor()
3962                        .spawn(async move {
3963                            let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
3964                            let mut marker_quads = Vec::new();
3965                            if scrollbar_settings.git_diff {
3966                                let marker_row_ranges = snapshot
3967                                    .diff_map
3968                                    .diff_hunks(&snapshot.buffer_snapshot)
3969                                    .map(|hunk| {
3970                                        let start_display_row =
3971                                            MultiBufferPoint::new(hunk.row_range.start.0, 0)
3972                                                .to_display_point(&snapshot.display_snapshot)
3973                                                .row();
3974                                        let mut end_display_row =
3975                                            MultiBufferPoint::new(hunk.row_range.end.0, 0)
3976                                                .to_display_point(&snapshot.display_snapshot)
3977                                                .row();
3978                                        if end_display_row != start_display_row {
3979                                            end_display_row.0 -= 1;
3980                                        }
3981                                        let color = match hunk_status(&hunk) {
3982                                            DiffHunkStatus::Added => theme.status().created,
3983                                            DiffHunkStatus::Modified => theme.status().modified,
3984                                            DiffHunkStatus::Removed => theme.status().deleted,
3985                                        };
3986                                        ColoredRange {
3987                                            start: start_display_row,
3988                                            end: end_display_row,
3989                                            color,
3990                                        }
3991                                    });
3992
3993                                marker_quads.extend(
3994                                    scrollbar_layout
3995                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
3996                                );
3997                            }
3998
3999                            for (background_highlight_id, (_, background_ranges)) in
4000                                background_highlights.iter()
4001                            {
4002                                let is_search_highlights = *background_highlight_id
4003                                    == TypeId::of::<BufferSearchHighlights>();
4004                                let is_symbol_occurrences = *background_highlight_id
4005                                    == TypeId::of::<DocumentHighlightRead>()
4006                                    || *background_highlight_id
4007                                        == TypeId::of::<DocumentHighlightWrite>();
4008                                if (is_search_highlights && scrollbar_settings.search_results)
4009                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
4010                                {
4011                                    let mut color = theme.status().info;
4012                                    if is_symbol_occurrences {
4013                                        color.fade_out(0.5);
4014                                    }
4015                                    let marker_row_ranges = background_ranges.iter().map(|range| {
4016                                        let display_start = range
4017                                            .start
4018                                            .to_display_point(&snapshot.display_snapshot);
4019                                        let display_end =
4020                                            range.end.to_display_point(&snapshot.display_snapshot);
4021                                        ColoredRange {
4022                                            start: display_start.row(),
4023                                            end: display_end.row(),
4024                                            color,
4025                                        }
4026                                    });
4027                                    marker_quads.extend(
4028                                        scrollbar_layout
4029                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
4030                                    );
4031                                }
4032                            }
4033
4034                            if scrollbar_settings.diagnostics {
4035                                let diagnostics = snapshot
4036                                    .buffer_snapshot
4037                                    .diagnostics_in_range::<_, Point>(
4038                                        Point::zero()..max_point,
4039                                        false,
4040                                    )
4041                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
4042                                    .sorted_by_key(|diagnostic| {
4043                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
4044                                    });
4045
4046                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
4047                                    let start_display = diagnostic
4048                                        .range
4049                                        .start
4050                                        .to_display_point(&snapshot.display_snapshot);
4051                                    let end_display = diagnostic
4052                                        .range
4053                                        .end
4054                                        .to_display_point(&snapshot.display_snapshot);
4055                                    let color = match diagnostic.diagnostic.severity {
4056                                        DiagnosticSeverity::ERROR => theme.status().error,
4057                                        DiagnosticSeverity::WARNING => theme.status().warning,
4058                                        DiagnosticSeverity::INFORMATION => theme.status().info,
4059                                        _ => theme.status().hint,
4060                                    };
4061                                    ColoredRange {
4062                                        start: start_display.row(),
4063                                        end: end_display.row(),
4064                                        color,
4065                                    }
4066                                });
4067                                marker_quads.extend(
4068                                    scrollbar_layout
4069                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
4070                                );
4071                            }
4072
4073                            Arc::from(marker_quads)
4074                        })
4075                        .await;
4076
4077                    editor.update(&mut cx, |editor, cx| {
4078                        editor.scrollbar_marker_state.markers = scrollbar_markers;
4079                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
4080                        editor.scrollbar_marker_state.pending_refresh = None;
4081                        cx.notify();
4082                    })?;
4083
4084                    Ok(())
4085                }));
4086        });
4087    }
4088
4089    #[allow(clippy::too_many_arguments)]
4090    fn paint_highlighted_range(
4091        &self,
4092        range: Range<DisplayPoint>,
4093        color: Hsla,
4094        corner_radius: Pixels,
4095        line_end_overshoot: Pixels,
4096        layout: &EditorLayout,
4097        cx: &mut WindowContext,
4098    ) {
4099        let start_row = layout.visible_display_row_range.start;
4100        let end_row = layout.visible_display_row_range.end;
4101        if range.start != range.end {
4102            let row_range = if range.end.column() == 0 {
4103                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
4104            } else {
4105                cmp::max(range.start.row(), start_row)
4106                    ..cmp::min(range.end.row().next_row(), end_row)
4107            };
4108
4109            let highlighted_range = HighlightedRange {
4110                color,
4111                line_height: layout.position_map.line_height,
4112                corner_radius,
4113                start_y: layout.content_origin.y
4114                    + row_range.start.as_f32() * layout.position_map.line_height
4115                    - layout.position_map.scroll_pixel_position.y,
4116                lines: row_range
4117                    .iter_rows()
4118                    .map(|row| {
4119                        let line_layout =
4120                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
4121                        HighlightedRangeLine {
4122                            start_x: if row == range.start.row() {
4123                                layout.content_origin.x
4124                                    + line_layout.x_for_index(range.start.column() as usize)
4125                                    - layout.position_map.scroll_pixel_position.x
4126                            } else {
4127                                layout.content_origin.x
4128                                    - layout.position_map.scroll_pixel_position.x
4129                            },
4130                            end_x: if row == range.end.row() {
4131                                layout.content_origin.x
4132                                    + line_layout.x_for_index(range.end.column() as usize)
4133                                    - layout.position_map.scroll_pixel_position.x
4134                            } else {
4135                                layout.content_origin.x + line_layout.width + line_end_overshoot
4136                                    - layout.position_map.scroll_pixel_position.x
4137                            },
4138                        }
4139                    })
4140                    .collect(),
4141            };
4142
4143            highlighted_range.paint(layout.text_hitbox.bounds, cx);
4144        }
4145    }
4146
4147    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4148        if let Some(mut inline_blame) = layout.inline_blame.take() {
4149            cx.paint_layer(layout.text_hitbox.bounds, |cx| {
4150                inline_blame.paint(cx);
4151            })
4152        }
4153    }
4154
4155    fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4156        for mut block in layout.blocks.drain(..) {
4157            block.element.paint(cx);
4158        }
4159    }
4160
4161    fn paint_inline_completion_popover(
4162        &mut self,
4163        layout: &mut EditorLayout,
4164        cx: &mut WindowContext,
4165    ) {
4166        if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
4167            inline_completion_popover.paint(cx);
4168        }
4169    }
4170
4171    fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4172        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
4173            mouse_context_menu.paint(cx);
4174        }
4175    }
4176
4177    fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
4178        cx.on_mouse_event({
4179            let position_map = layout.position_map.clone();
4180            let editor = self.editor.clone();
4181            let hitbox = layout.hitbox.clone();
4182            let mut delta = ScrollDelta::default();
4183
4184            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
4185            // accidentally turn off their scrolling.
4186            let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
4187
4188            move |event: &ScrollWheelEvent, phase, cx| {
4189                if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
4190                    delta = delta.coalesce(event.delta);
4191                    editor.update(cx, |editor, cx| {
4192                        let position_map: &PositionMap = &position_map;
4193
4194                        let line_height = position_map.line_height;
4195                        let max_glyph_width = position_map.em_width;
4196                        let (delta, axis) = match delta {
4197                            gpui::ScrollDelta::Pixels(mut pixels) => {
4198                                //Trackpad
4199                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
4200                                (pixels, axis)
4201                            }
4202
4203                            gpui::ScrollDelta::Lines(lines) => {
4204                                //Not trackpad
4205                                let pixels =
4206                                    point(lines.x * max_glyph_width, lines.y * line_height);
4207                                (pixels, None)
4208                            }
4209                        };
4210
4211                        let current_scroll_position = position_map.snapshot.scroll_position();
4212                        let x = (current_scroll_position.x * max_glyph_width
4213                            - (delta.x * scroll_sensitivity))
4214                            / max_glyph_width;
4215                        let y = (current_scroll_position.y * line_height
4216                            - (delta.y * scroll_sensitivity))
4217                            / line_height;
4218                        let mut scroll_position =
4219                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
4220                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
4221                        if forbid_vertical_scroll {
4222                            scroll_position.y = current_scroll_position.y;
4223                        }
4224
4225                        if scroll_position != current_scroll_position {
4226                            editor.scroll(scroll_position, axis, cx);
4227                            cx.stop_propagation();
4228                        } else if y < 0. {
4229                            // Due to clamping, we may fail to detect cases of overscroll to the top;
4230                            // We want the scroll manager to get an update in such cases and detect the change of direction
4231                            // on the next frame.
4232                            cx.notify();
4233                        }
4234                    });
4235                }
4236            }
4237        });
4238    }
4239
4240    fn paint_mouse_listeners(
4241        &mut self,
4242        layout: &EditorLayout,
4243        hovered_hunk: Option<HoveredHunk>,
4244        cx: &mut WindowContext,
4245    ) {
4246        self.paint_scroll_wheel_listener(layout, cx);
4247
4248        cx.on_mouse_event({
4249            let position_map = layout.position_map.clone();
4250            let editor = self.editor.clone();
4251            let text_hitbox = layout.text_hitbox.clone();
4252            let gutter_hitbox = layout.gutter_hitbox.clone();
4253
4254            move |event: &MouseDownEvent, phase, cx| {
4255                if phase == DispatchPhase::Bubble {
4256                    match event.button {
4257                        MouseButton::Left => editor.update(cx, |editor, cx| {
4258                            Self::mouse_left_down(
4259                                editor,
4260                                event,
4261                                hovered_hunk.clone(),
4262                                &position_map,
4263                                &text_hitbox,
4264                                &gutter_hitbox,
4265                                cx,
4266                            );
4267                        }),
4268                        MouseButton::Right => editor.update(cx, |editor, cx| {
4269                            Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
4270                        }),
4271                        MouseButton::Middle => editor.update(cx, |editor, cx| {
4272                            Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
4273                        }),
4274                        _ => {}
4275                    };
4276                }
4277            }
4278        });
4279
4280        cx.on_mouse_event({
4281            let editor = self.editor.clone();
4282            let position_map = layout.position_map.clone();
4283            let text_hitbox = layout.text_hitbox.clone();
4284
4285            move |event: &MouseUpEvent, phase, cx| {
4286                if phase == DispatchPhase::Bubble {
4287                    editor.update(cx, |editor, cx| {
4288                        Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
4289                    });
4290                }
4291            }
4292        });
4293        cx.on_mouse_event({
4294            let position_map = layout.position_map.clone();
4295            let editor = self.editor.clone();
4296            let text_hitbox = layout.text_hitbox.clone();
4297            let gutter_hitbox = layout.gutter_hitbox.clone();
4298
4299            move |event: &MouseMoveEvent, phase, cx| {
4300                if phase == DispatchPhase::Bubble {
4301                    editor.update(cx, |editor, cx| {
4302                        if editor.hover_state.focused(cx) {
4303                            return;
4304                        }
4305                        if event.pressed_button == Some(MouseButton::Left)
4306                            || event.pressed_button == Some(MouseButton::Middle)
4307                        {
4308                            Self::mouse_dragged(
4309                                editor,
4310                                event,
4311                                &position_map,
4312                                text_hitbox.bounds,
4313                                cx,
4314                            )
4315                        }
4316
4317                        Self::mouse_moved(
4318                            editor,
4319                            event,
4320                            &position_map,
4321                            &text_hitbox,
4322                            &gutter_hitbox,
4323                            cx,
4324                        )
4325                    });
4326                }
4327            }
4328        });
4329    }
4330
4331    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
4332        bounds.upper_right().x - self.style.scrollbar_width
4333    }
4334
4335    fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
4336        let style = &self.style;
4337        let font_size = style.text.font_size.to_pixels(cx.rem_size());
4338        let layout = cx
4339            .text_system()
4340            .shape_line(
4341                SharedString::from(" ".repeat(column)),
4342                font_size,
4343                &[TextRun {
4344                    len: column,
4345                    font: style.text.font(),
4346                    color: Hsla::default(),
4347                    background_color: None,
4348                    underline: None,
4349                    strikethrough: None,
4350                }],
4351            )
4352            .unwrap();
4353
4354        layout.width
4355    }
4356
4357    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
4358        let digit_count = (snapshot.widest_line_number() as f32).log10().floor() as usize + 1;
4359        self.column_pixels(digit_count, cx)
4360    }
4361}
4362
4363fn jump_data(
4364    snapshot: &EditorSnapshot,
4365    block_row_start: DisplayRow,
4366    height: u32,
4367    for_excerpt: &ExcerptInfo,
4368    cx: &mut WindowContext<'_>,
4369) -> JumpData {
4370    let range = &for_excerpt.range;
4371    let buffer = &for_excerpt.buffer;
4372    let jump_path = project::File::from_dyn(buffer.file()).map(|file| ProjectPath {
4373        worktree_id: file.worktree_id(cx),
4374        path: file.path.clone(),
4375    });
4376    let jump_anchor = range
4377        .primary
4378        .as_ref()
4379        .map_or(range.context.start, |primary| primary.start);
4380
4381    let excerpt_start = range.context.start;
4382    let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
4383    let offset_from_excerpt_start = if jump_anchor == excerpt_start {
4384        0
4385    } else {
4386        let excerpt_start_row = language::ToPoint::to_point(&jump_anchor, buffer).row;
4387        jump_position.row - excerpt_start_row
4388    };
4389    let line_offset_from_top = block_row_start.0 + height + offset_from_excerpt_start
4390        - snapshot
4391            .scroll_anchor
4392            .scroll_position(&snapshot.display_snapshot)
4393            .y as u32;
4394    JumpData {
4395        excerpt_id: for_excerpt.id,
4396        anchor: jump_anchor,
4397        position: language::ToPoint::to_point(&jump_anchor, buffer),
4398        path: jump_path,
4399        line_offset_from_top,
4400    }
4401}
4402
4403fn inline_completion_popover_text(
4404    editor_snapshot: &EditorSnapshot,
4405    edits: &Vec<(Range<Anchor>, String)>,
4406    cx: &WindowContext,
4407) -> (String, Vec<(Range<usize>, HighlightStyle)>) {
4408    let edit_start = edits
4409        .first()
4410        .unwrap()
4411        .0
4412        .start
4413        .to_display_point(editor_snapshot);
4414
4415    let mut text = String::new();
4416    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
4417    let mut highlights = Vec::new();
4418    for (old_range, new_text) in edits {
4419        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
4420        text.extend(
4421            editor_snapshot
4422                .buffer_snapshot
4423                .chunks(offset..old_offset_range.start, false)
4424                .map(|chunk| chunk.text),
4425        );
4426        offset = old_offset_range.end;
4427
4428        let start = text.len();
4429        text.push_str(new_text);
4430        let end = text.len();
4431        highlights.push((
4432            start..end,
4433            HighlightStyle {
4434                background_color: Some(cx.theme().status().created_background),
4435                ..Default::default()
4436            },
4437        ));
4438    }
4439
4440    let edit_end = edits
4441        .last()
4442        .unwrap()
4443        .0
4444        .end
4445        .to_display_point(editor_snapshot);
4446    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
4447        .to_offset(editor_snapshot, Bias::Right);
4448    text.extend(
4449        editor_snapshot
4450            .buffer_snapshot
4451            .chunks(offset..end_of_line, false)
4452            .map(|chunk| chunk.text),
4453    );
4454
4455    (text, highlights)
4456}
4457
4458fn all_edits_insertions_or_deletions(
4459    edits: &Vec<(Range<Anchor>, String)>,
4460    snapshot: &MultiBufferSnapshot,
4461) -> bool {
4462    let mut all_insertions = true;
4463    let mut all_deletions = true;
4464
4465    for (range, new_text) in edits.iter() {
4466        let range_is_empty = range.to_offset(&snapshot).is_empty();
4467        let text_is_empty = new_text.is_empty();
4468
4469        if range_is_empty != text_is_empty {
4470            if range_is_empty {
4471                all_deletions = false;
4472            } else {
4473                all_insertions = false;
4474            }
4475        } else {
4476            return false;
4477        }
4478
4479        if !all_insertions && !all_deletions {
4480            return false;
4481        }
4482    }
4483    all_insertions || all_deletions
4484}
4485
4486#[allow(clippy::too_many_arguments)]
4487fn prepaint_gutter_button(
4488    button: IconButton,
4489    row: DisplayRow,
4490    line_height: Pixels,
4491    gutter_dimensions: &GutterDimensions,
4492    scroll_pixel_position: gpui::Point<Pixels>,
4493    gutter_hitbox: &Hitbox,
4494    rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
4495    cx: &mut WindowContext<'_>,
4496) -> AnyElement {
4497    let mut button = button.into_any_element();
4498    let available_space = size(
4499        AvailableSpace::MinContent,
4500        AvailableSpace::Definite(line_height),
4501    );
4502    let indicator_size = button.layout_as_root(available_space, cx);
4503
4504    let blame_width = gutter_dimensions.git_blame_entries_width;
4505    let gutter_width = rows_with_hunk_bounds
4506        .get(&row)
4507        .map(|bounds| bounds.size.width);
4508    let left_offset = blame_width.max(gutter_width).unwrap_or_default();
4509
4510    let mut x = left_offset;
4511    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
4512        - indicator_size.width
4513        - left_offset;
4514    x += available_width / 2.;
4515
4516    let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
4517    y += (line_height - indicator_size.height) / 2.;
4518
4519    button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
4520    button
4521}
4522
4523fn render_inline_blame_entry(
4524    blame: &gpui::Model<GitBlame>,
4525    blame_entry: BlameEntry,
4526    style: &EditorStyle,
4527    workspace: Option<WeakView<Workspace>>,
4528    cx: &mut WindowContext<'_>,
4529) -> AnyElement {
4530    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
4531
4532    let author = blame_entry.author.as_deref().unwrap_or_default();
4533    let summary_enabled = ProjectSettings::get_global(cx)
4534        .git
4535        .show_inline_commit_summary();
4536
4537    let text = match blame_entry.summary.as_ref() {
4538        Some(summary) if summary_enabled => {
4539            format!("{}, {} - {}", author, relative_timestamp, summary)
4540        }
4541        _ => format!("{}, {}", author, relative_timestamp),
4542    };
4543
4544    let details = blame.read(cx).details_for_entry(&blame_entry);
4545
4546    let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
4547
4548    h_flex()
4549        .id("inline-blame")
4550        .w_full()
4551        .font_family(style.text.font().family)
4552        .text_color(cx.theme().status().hint)
4553        .line_height(style.text.line_height)
4554        .child(Icon::new(IconName::FileGit).color(Color::Hint))
4555        .child(text)
4556        .gap_2()
4557        .hoverable_tooltip(move |_| tooltip.clone().into())
4558        .into_any()
4559}
4560
4561fn render_blame_entry(
4562    ix: usize,
4563    blame: &gpui::Model<GitBlame>,
4564    blame_entry: BlameEntry,
4565    style: &EditorStyle,
4566    last_used_color: &mut Option<(PlayerColor, Oid)>,
4567    editor: View<Editor>,
4568    cx: &mut WindowContext<'_>,
4569) -> AnyElement {
4570    let mut sha_color = cx
4571        .theme()
4572        .players()
4573        .color_for_participant(blame_entry.sha.into());
4574    // If the last color we used is the same as the one we get for this line, but
4575    // the commit SHAs are different, then we try again to get a different color.
4576    match *last_used_color {
4577        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
4578            let index: u32 = blame_entry.sha.into();
4579            sha_color = cx.theme().players().color_for_participant(index + 1);
4580        }
4581        _ => {}
4582    };
4583    last_used_color.replace((sha_color, blame_entry.sha));
4584
4585    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
4586
4587    let short_commit_id = blame_entry.sha.display_short();
4588
4589    let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
4590    let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
4591
4592    let details = blame.read(cx).details_for_entry(&blame_entry);
4593
4594    let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
4595
4596    let tooltip = cx.new_view(|_| {
4597        BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
4598    });
4599
4600    h_flex()
4601        .w_full()
4602        .justify_between()
4603        .font_family(style.text.font().family)
4604        .line_height(style.text.line_height)
4605        .id(("blame", ix))
4606        .text_color(cx.theme().status().hint)
4607        .pr_2()
4608        .gap_2()
4609        .child(
4610            h_flex()
4611                .items_center()
4612                .gap_2()
4613                .child(div().text_color(sha_color.cursor).child(short_commit_id))
4614                .child(name),
4615        )
4616        .child(relative_timestamp)
4617        .on_mouse_down(MouseButton::Right, {
4618            let blame_entry = blame_entry.clone();
4619            let details = details.clone();
4620            move |event, cx| {
4621                deploy_blame_entry_context_menu(
4622                    &blame_entry,
4623                    details.as_ref(),
4624                    editor.clone(),
4625                    event.position,
4626                    cx,
4627                );
4628            }
4629        })
4630        .hover(|style| style.bg(cx.theme().colors().element_hover))
4631        .when_some(
4632            details.and_then(|details| details.permalink),
4633            |this, url| {
4634                let url = url.clone();
4635                this.cursor_pointer().on_click(move |_, cx| {
4636                    cx.stop_propagation();
4637                    cx.open_url(url.as_str())
4638                })
4639            },
4640        )
4641        .hoverable_tooltip(move |_| tooltip.clone().into())
4642        .into_any()
4643}
4644
4645fn deploy_blame_entry_context_menu(
4646    blame_entry: &BlameEntry,
4647    details: Option<&CommitDetails>,
4648    editor: View<Editor>,
4649    position: gpui::Point<Pixels>,
4650    cx: &mut WindowContext<'_>,
4651) {
4652    let context_menu = ContextMenu::build(cx, move |menu, _| {
4653        let sha = format!("{}", blame_entry.sha);
4654        menu.on_blur_subscription(Subscription::new(|| {}))
4655            .entry("Copy commit SHA", None, move |cx| {
4656                cx.write_to_clipboard(ClipboardItem::new_string(sha.clone()));
4657            })
4658            .when_some(
4659                details.and_then(|details| details.permalink.clone()),
4660                |this, url| this.entry("Open permalink", None, move |cx| cx.open_url(url.as_str())),
4661            )
4662    });
4663
4664    editor.update(cx, move |editor, cx| {
4665        editor.mouse_context_menu = Some(MouseContextMenu::new(
4666            MenuPosition::PinnedToScreen(position),
4667            context_menu,
4668            cx,
4669        ));
4670        cx.notify();
4671    });
4672}
4673
4674#[derive(Debug)]
4675pub(crate) struct LineWithInvisibles {
4676    fragments: SmallVec<[LineFragment; 1]>,
4677    invisibles: Vec<Invisible>,
4678    len: usize,
4679    width: Pixels,
4680    font_size: Pixels,
4681}
4682
4683#[allow(clippy::large_enum_variant)]
4684enum LineFragment {
4685    Text(ShapedLine),
4686    Element {
4687        element: Option<AnyElement>,
4688        size: Size<Pixels>,
4689        len: usize,
4690    },
4691}
4692
4693impl fmt::Debug for LineFragment {
4694    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4695        match self {
4696            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
4697            LineFragment::Element { size, len, .. } => f
4698                .debug_struct("Element")
4699                .field("size", size)
4700                .field("len", len)
4701                .finish(),
4702        }
4703    }
4704}
4705
4706impl LineWithInvisibles {
4707    #[allow(clippy::too_many_arguments)]
4708    fn from_chunks<'a>(
4709        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
4710        editor_style: &EditorStyle,
4711        max_line_len: usize,
4712        max_line_count: usize,
4713        editor_mode: EditorMode,
4714        text_width: Pixels,
4715        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
4716        cx: &mut WindowContext,
4717    ) -> Vec<Self> {
4718        let text_style = &editor_style.text;
4719        let mut layouts = Vec::with_capacity(max_line_count);
4720        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
4721        let mut line = String::new();
4722        let mut invisibles = Vec::new();
4723        let mut width = Pixels::ZERO;
4724        let mut len = 0;
4725        let mut styles = Vec::new();
4726        let mut non_whitespace_added = false;
4727        let mut row = 0;
4728        let mut line_exceeded_max_len = false;
4729        let font_size = text_style.font_size.to_pixels(cx.rem_size());
4730
4731        let ellipsis = SharedString::from("");
4732
4733        for highlighted_chunk in chunks.chain([HighlightedChunk {
4734            text: "\n",
4735            style: None,
4736            is_tab: false,
4737            replacement: None,
4738        }]) {
4739            if let Some(replacement) = highlighted_chunk.replacement {
4740                if !line.is_empty() {
4741                    let shaped_line = cx
4742                        .text_system()
4743                        .shape_line(line.clone().into(), font_size, &styles)
4744                        .unwrap();
4745                    width += shaped_line.width;
4746                    len += shaped_line.len;
4747                    fragments.push(LineFragment::Text(shaped_line));
4748                    line.clear();
4749                    styles.clear();
4750                }
4751
4752                match replacement {
4753                    ChunkReplacement::Renderer(renderer) => {
4754                        let available_width = if renderer.constrain_width {
4755                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
4756                                ellipsis.clone()
4757                            } else {
4758                                SharedString::from(Arc::from(highlighted_chunk.text))
4759                            };
4760                            let shaped_line = cx
4761                                .text_system()
4762                                .shape_line(
4763                                    chunk,
4764                                    font_size,
4765                                    &[text_style.to_run(highlighted_chunk.text.len())],
4766                                )
4767                                .unwrap();
4768                            AvailableSpace::Definite(shaped_line.width)
4769                        } else {
4770                            AvailableSpace::MinContent
4771                        };
4772
4773                        let mut element = (renderer.render)(&mut ChunkRendererContext {
4774                            context: cx,
4775                            max_width: text_width,
4776                        });
4777                        let line_height = text_style.line_height_in_pixels(cx.rem_size());
4778                        let size = element.layout_as_root(
4779                            size(available_width, AvailableSpace::Definite(line_height)),
4780                            cx,
4781                        );
4782
4783                        width += size.width;
4784                        len += highlighted_chunk.text.len();
4785                        fragments.push(LineFragment::Element {
4786                            element: Some(element),
4787                            size,
4788                            len: highlighted_chunk.text.len(),
4789                        });
4790                    }
4791                    ChunkReplacement::Str(x) => {
4792                        let text_style = if let Some(style) = highlighted_chunk.style {
4793                            Cow::Owned(text_style.clone().highlight(style))
4794                        } else {
4795                            Cow::Borrowed(text_style)
4796                        };
4797
4798                        let run = TextRun {
4799                            len: x.len(),
4800                            font: text_style.font(),
4801                            color: text_style.color,
4802                            background_color: text_style.background_color,
4803                            underline: text_style.underline,
4804                            strikethrough: text_style.strikethrough,
4805                        };
4806                        let line_layout = cx
4807                            .text_system()
4808                            .shape_line(x, font_size, &[run])
4809                            .unwrap()
4810                            .with_len(highlighted_chunk.text.len());
4811
4812                        width += line_layout.width;
4813                        len += highlighted_chunk.text.len();
4814                        fragments.push(LineFragment::Text(line_layout))
4815                    }
4816                }
4817            } else {
4818                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
4819                    if ix > 0 {
4820                        let shaped_line = cx
4821                            .text_system()
4822                            .shape_line(line.clone().into(), font_size, &styles)
4823                            .unwrap();
4824                        width += shaped_line.width;
4825                        len += shaped_line.len;
4826                        fragments.push(LineFragment::Text(shaped_line));
4827                        layouts.push(Self {
4828                            width: mem::take(&mut width),
4829                            len: mem::take(&mut len),
4830                            fragments: mem::take(&mut fragments),
4831                            invisibles: std::mem::take(&mut invisibles),
4832                            font_size,
4833                        });
4834
4835                        line.clear();
4836                        styles.clear();
4837                        row += 1;
4838                        line_exceeded_max_len = false;
4839                        non_whitespace_added = false;
4840                        if row == max_line_count {
4841                            return layouts;
4842                        }
4843                    }
4844
4845                    if !line_chunk.is_empty() && !line_exceeded_max_len {
4846                        let text_style = if let Some(style) = highlighted_chunk.style {
4847                            Cow::Owned(text_style.clone().highlight(style))
4848                        } else {
4849                            Cow::Borrowed(text_style)
4850                        };
4851
4852                        if line.len() + line_chunk.len() > max_line_len {
4853                            let mut chunk_len = max_line_len - line.len();
4854                            while !line_chunk.is_char_boundary(chunk_len) {
4855                                chunk_len -= 1;
4856                            }
4857                            line_chunk = &line_chunk[..chunk_len];
4858                            line_exceeded_max_len = true;
4859                        }
4860
4861                        styles.push(TextRun {
4862                            len: line_chunk.len(),
4863                            font: text_style.font(),
4864                            color: text_style.color,
4865                            background_color: text_style.background_color,
4866                            underline: text_style.underline,
4867                            strikethrough: text_style.strikethrough,
4868                        });
4869
4870                        if editor_mode == EditorMode::Full {
4871                            // Line wrap pads its contents with fake whitespaces,
4872                            // avoid printing them
4873                            let is_soft_wrapped = is_row_soft_wrapped(row);
4874                            if highlighted_chunk.is_tab {
4875                                if non_whitespace_added || !is_soft_wrapped {
4876                                    invisibles.push(Invisible::Tab {
4877                                        line_start_offset: line.len(),
4878                                        line_end_offset: line.len() + line_chunk.len(),
4879                                    });
4880                                }
4881                            } else {
4882                                invisibles.extend(
4883                                    line_chunk
4884                                        .bytes()
4885                                        .enumerate()
4886                                        .filter(|(_, line_byte)| {
4887                                            let is_whitespace =
4888                                                (*line_byte as char).is_whitespace();
4889                                            non_whitespace_added |= !is_whitespace;
4890                                            is_whitespace
4891                                                && (non_whitespace_added || !is_soft_wrapped)
4892                                        })
4893                                        .map(|(whitespace_index, _)| Invisible::Whitespace {
4894                                            line_offset: line.len() + whitespace_index,
4895                                        }),
4896                                )
4897                            }
4898                        }
4899
4900                        line.push_str(line_chunk);
4901                    }
4902                }
4903            }
4904        }
4905
4906        layouts
4907    }
4908
4909    fn prepaint(
4910        &mut self,
4911        line_height: Pixels,
4912        scroll_pixel_position: gpui::Point<Pixels>,
4913        row: DisplayRow,
4914        content_origin: gpui::Point<Pixels>,
4915        line_elements: &mut SmallVec<[AnyElement; 1]>,
4916        cx: &mut WindowContext,
4917    ) {
4918        let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
4919        let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
4920        for fragment in &mut self.fragments {
4921            match fragment {
4922                LineFragment::Text(line) => {
4923                    fragment_origin.x += line.width;
4924                }
4925                LineFragment::Element { element, size, .. } => {
4926                    let mut element = element
4927                        .take()
4928                        .expect("you can't prepaint LineWithInvisibles twice");
4929
4930                    // Center the element vertically within the line.
4931                    let mut element_origin = fragment_origin;
4932                    element_origin.y += (line_height - size.height) / 2.;
4933                    element.prepaint_at(element_origin, cx);
4934                    line_elements.push(element);
4935
4936                    fragment_origin.x += size.width;
4937                }
4938            }
4939        }
4940    }
4941
4942    fn draw(
4943        &self,
4944        layout: &EditorLayout,
4945        row: DisplayRow,
4946        content_origin: gpui::Point<Pixels>,
4947        whitespace_setting: ShowWhitespaceSetting,
4948        selection_ranges: &[Range<DisplayPoint>],
4949        cx: &mut WindowContext,
4950    ) {
4951        let line_height = layout.position_map.line_height;
4952        let line_y = line_height
4953            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
4954
4955        let mut fragment_origin =
4956            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
4957
4958        for fragment in &self.fragments {
4959            match fragment {
4960                LineFragment::Text(line) => {
4961                    line.paint(fragment_origin, line_height, cx).log_err();
4962                    fragment_origin.x += line.width;
4963                }
4964                LineFragment::Element { size, .. } => {
4965                    fragment_origin.x += size.width;
4966                }
4967            }
4968        }
4969
4970        self.draw_invisibles(
4971            selection_ranges,
4972            layout,
4973            content_origin,
4974            line_y,
4975            row,
4976            line_height,
4977            whitespace_setting,
4978            cx,
4979        );
4980    }
4981
4982    #[allow(clippy::too_many_arguments)]
4983    fn draw_invisibles(
4984        &self,
4985        selection_ranges: &[Range<DisplayPoint>],
4986        layout: &EditorLayout,
4987        content_origin: gpui::Point<Pixels>,
4988        line_y: Pixels,
4989        row: DisplayRow,
4990        line_height: Pixels,
4991        whitespace_setting: ShowWhitespaceSetting,
4992        cx: &mut WindowContext,
4993    ) {
4994        let extract_whitespace_info = |invisible: &Invisible| {
4995            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
4996                Invisible::Tab {
4997                    line_start_offset,
4998                    line_end_offset,
4999                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
5000                Invisible::Whitespace { line_offset } => {
5001                    (*line_offset, line_offset + 1, &layout.space_invisible)
5002                }
5003            };
5004
5005            let x_offset = self.x_for_index(token_offset);
5006            let invisible_offset =
5007                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
5008            let origin = content_origin
5009                + gpui::point(
5010                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
5011                    line_y,
5012                );
5013
5014            (
5015                [token_offset, token_end_offset],
5016                Box::new(move |cx: &mut WindowContext| {
5017                    invisible_symbol.paint(origin, line_height, cx).log_err();
5018                }),
5019            )
5020        };
5021
5022        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
5023        match whitespace_setting {
5024            ShowWhitespaceSetting::None => (),
5025            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(cx)),
5026            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
5027                let invisible_point = DisplayPoint::new(row, start as u32);
5028                if !selection_ranges
5029                    .iter()
5030                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
5031                {
5032                    return;
5033                }
5034
5035                paint(cx);
5036            }),
5037
5038            // For a whitespace to be on a boundary, any of the following conditions need to be met:
5039            // - It is a tab
5040            // - It is adjacent to an edge (start or end)
5041            // - It is adjacent to a whitespace (left or right)
5042            ShowWhitespaceSetting::Boundary => {
5043                // 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
5044                // the above cases.
5045                // Note: We zip in the original `invisibles` to check for tab equality
5046                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut WindowContext)>)> = None;
5047                for (([start, end], paint), invisible) in
5048                    invisible_iter.zip_eq(self.invisibles.iter())
5049                {
5050                    let should_render = match (&last_seen, invisible) {
5051                        (_, Invisible::Tab { .. }) => true,
5052                        (Some((_, last_end, _)), _) => *last_end == start,
5053                        _ => false,
5054                    };
5055
5056                    if should_render || start == 0 || end == self.len {
5057                        paint(cx);
5058
5059                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
5060                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
5061                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
5062                            // Note that we need to make sure that the last one is actually adjacent
5063                            if !should_render_last && last_end == start {
5064                                paint_last(cx);
5065                            }
5066                        }
5067                    }
5068
5069                    // Manually render anything within a selection
5070                    let invisible_point = DisplayPoint::new(row, start as u32);
5071                    if selection_ranges.iter().any(|region| {
5072                        region.start <= invisible_point && invisible_point < region.end
5073                    }) {
5074                        paint(cx);
5075                    }
5076
5077                    last_seen = Some((should_render, end, paint));
5078                }
5079            }
5080        }
5081    }
5082
5083    pub fn x_for_index(&self, index: usize) -> Pixels {
5084        let mut fragment_start_x = Pixels::ZERO;
5085        let mut fragment_start_index = 0;
5086
5087        for fragment in &self.fragments {
5088            match fragment {
5089                LineFragment::Text(shaped_line) => {
5090                    let fragment_end_index = fragment_start_index + shaped_line.len;
5091                    if index < fragment_end_index {
5092                        return fragment_start_x
5093                            + shaped_line.x_for_index(index - fragment_start_index);
5094                    }
5095                    fragment_start_x += shaped_line.width;
5096                    fragment_start_index = fragment_end_index;
5097                }
5098                LineFragment::Element { len, size, .. } => {
5099                    let fragment_end_index = fragment_start_index + len;
5100                    if index < fragment_end_index {
5101                        return fragment_start_x;
5102                    }
5103                    fragment_start_x += size.width;
5104                    fragment_start_index = fragment_end_index;
5105                }
5106            }
5107        }
5108
5109        fragment_start_x
5110    }
5111
5112    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
5113        let mut fragment_start_x = Pixels::ZERO;
5114        let mut fragment_start_index = 0;
5115
5116        for fragment in &self.fragments {
5117            match fragment {
5118                LineFragment::Text(shaped_line) => {
5119                    let fragment_end_x = fragment_start_x + shaped_line.width;
5120                    if x < fragment_end_x {
5121                        return Some(
5122                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
5123                        );
5124                    }
5125                    fragment_start_x = fragment_end_x;
5126                    fragment_start_index += shaped_line.len;
5127                }
5128                LineFragment::Element { len, size, .. } => {
5129                    let fragment_end_x = fragment_start_x + size.width;
5130                    if x < fragment_end_x {
5131                        return Some(fragment_start_index);
5132                    }
5133                    fragment_start_index += len;
5134                    fragment_start_x = fragment_end_x;
5135                }
5136            }
5137        }
5138
5139        None
5140    }
5141
5142    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
5143        let mut fragment_start_index = 0;
5144
5145        for fragment in &self.fragments {
5146            match fragment {
5147                LineFragment::Text(shaped_line) => {
5148                    let fragment_end_index = fragment_start_index + shaped_line.len;
5149                    if index < fragment_end_index {
5150                        return shaped_line.font_id_for_index(index - fragment_start_index);
5151                    }
5152                    fragment_start_index = fragment_end_index;
5153                }
5154                LineFragment::Element { len, .. } => {
5155                    let fragment_end_index = fragment_start_index + len;
5156                    if index < fragment_end_index {
5157                        return None;
5158                    }
5159                    fragment_start_index = fragment_end_index;
5160                }
5161            }
5162        }
5163
5164        None
5165    }
5166}
5167
5168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5169enum Invisible {
5170    /// A tab character
5171    ///
5172    /// A tab character is internally represented by spaces (configured by the user's tab width)
5173    /// aligned to the nearest column, so it's necessary to store the start and end offset for
5174    /// adjacency checks.
5175    Tab {
5176        line_start_offset: usize,
5177        line_end_offset: usize,
5178    },
5179    Whitespace {
5180        line_offset: usize,
5181    },
5182}
5183
5184impl EditorElement {
5185    /// Returns the rem size to use when rendering the [`EditorElement`].
5186    ///
5187    /// This allows UI elements to scale based on the `buffer_font_size`.
5188    fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
5189        match self.editor.read(cx).mode {
5190            EditorMode::Full => {
5191                let buffer_font_size = self.style.text.font_size;
5192                match buffer_font_size {
5193                    AbsoluteLength::Pixels(pixels) => {
5194                        let rem_size_scale = {
5195                            // Our default UI font size is 14px on a 16px base scale.
5196                            // This means the default UI font size is 0.875rems.
5197                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
5198
5199                            // We then determine the delta between a single rem and the default font
5200                            // size scale.
5201                            let default_font_size_delta = 1. - default_font_size_scale;
5202
5203                            // Finally, we add this delta to 1rem to get the scale factor that
5204                            // should be used to scale up the UI.
5205                            1. + default_font_size_delta
5206                        };
5207
5208                        Some(pixels * rem_size_scale)
5209                    }
5210                    AbsoluteLength::Rems(rems) => {
5211                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
5212                    }
5213                }
5214            }
5215            // We currently use single-line and auto-height editors in UI contexts,
5216            // so we don't want to scale everything with the buffer font size, as it
5217            // ends up looking off.
5218            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
5219        }
5220    }
5221}
5222
5223impl Element for EditorElement {
5224    type RequestLayoutState = ();
5225    type PrepaintState = EditorLayout;
5226
5227    fn id(&self) -> Option<ElementId> {
5228        None
5229    }
5230
5231    fn request_layout(
5232        &mut self,
5233        _: Option<&GlobalElementId>,
5234        cx: &mut WindowContext,
5235    ) -> (gpui::LayoutId, ()) {
5236        let rem_size = self.rem_size(cx);
5237        cx.with_rem_size(rem_size, |cx| {
5238            self.editor.update(cx, |editor, cx| {
5239                editor.set_style(self.style.clone(), cx);
5240
5241                let layout_id = match editor.mode {
5242                    EditorMode::SingleLine { auto_width } => {
5243                        let rem_size = cx.rem_size();
5244
5245                        let height = self.style.text.line_height_in_pixels(rem_size);
5246                        if auto_width {
5247                            let editor_handle = cx.view().clone();
5248                            let style = self.style.clone();
5249                            cx.request_measured_layout(Style::default(), move |_, _, cx| {
5250                                let editor_snapshot =
5251                                    editor_handle.update(cx, |editor, cx| editor.snapshot(cx));
5252                                let line = Self::layout_lines(
5253                                    DisplayRow(0)..DisplayRow(1),
5254                                    &editor_snapshot,
5255                                    &style,
5256                                    px(f32::MAX),
5257                                    |_| false, // Single lines never soft wrap
5258                                    cx,
5259                                )
5260                                .pop()
5261                                .unwrap();
5262
5263                                let font_id = cx.text_system().resolve_font(&style.text.font());
5264                                let font_size = style.text.font_size.to_pixels(cx.rem_size());
5265                                let em_width = cx
5266                                    .text_system()
5267                                    .typographic_bounds(font_id, font_size, 'm')
5268                                    .unwrap()
5269                                    .size
5270                                    .width;
5271
5272                                size(line.width + em_width, height)
5273                            })
5274                        } else {
5275                            let mut style = Style::default();
5276                            style.size.height = height.into();
5277                            style.size.width = relative(1.).into();
5278                            cx.request_layout(style, None)
5279                        }
5280                    }
5281                    EditorMode::AutoHeight { max_lines } => {
5282                        let editor_handle = cx.view().clone();
5283                        let max_line_number_width =
5284                            self.max_line_number_width(&editor.snapshot(cx), cx);
5285                        cx.request_measured_layout(
5286                            Style::default(),
5287                            move |known_dimensions, available_space, cx| {
5288                                editor_handle
5289                                    .update(cx, |editor, cx| {
5290                                        compute_auto_height_layout(
5291                                            editor,
5292                                            max_lines,
5293                                            max_line_number_width,
5294                                            known_dimensions,
5295                                            available_space.width,
5296                                            cx,
5297                                        )
5298                                    })
5299                                    .unwrap_or_default()
5300                            },
5301                        )
5302                    }
5303                    EditorMode::Full => {
5304                        let mut style = Style::default();
5305                        style.size.width = relative(1.).into();
5306                        style.size.height = relative(1.).into();
5307                        cx.request_layout(style, None)
5308                    }
5309                };
5310
5311                (layout_id, ())
5312            })
5313        })
5314    }
5315
5316    fn prepaint(
5317        &mut self,
5318        _: Option<&GlobalElementId>,
5319        bounds: Bounds<Pixels>,
5320        _: &mut Self::RequestLayoutState,
5321        cx: &mut WindowContext,
5322    ) -> Self::PrepaintState {
5323        let text_style = TextStyleRefinement {
5324            font_size: Some(self.style.text.font_size),
5325            line_height: Some(self.style.text.line_height),
5326            ..Default::default()
5327        };
5328        let focus_handle = self.editor.focus_handle(cx);
5329        cx.set_view_id(self.editor.entity_id());
5330        cx.set_focus_handle(&focus_handle);
5331
5332        let rem_size = self.rem_size(cx);
5333        cx.with_rem_size(rem_size, |cx| {
5334            cx.with_text_style(Some(text_style), |cx| {
5335                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5336                    let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
5337                    let style = self.style.clone();
5338
5339                    let font_id = cx.text_system().resolve_font(&style.text.font());
5340                    let font_size = style.text.font_size.to_pixels(cx.rem_size());
5341                    let line_height = style.text.line_height_in_pixels(cx.rem_size());
5342                    let em_width = cx
5343                        .text_system()
5344                        .typographic_bounds(font_id, font_size, 'm')
5345                        .unwrap()
5346                        .size
5347                        .width;
5348                    let em_advance = cx
5349                        .text_system()
5350                        .advance(font_id, font_size, 'm')
5351                        .unwrap()
5352                        .width;
5353
5354                    let gutter_dimensions = snapshot.gutter_dimensions(
5355                        font_id,
5356                        font_size,
5357                        em_width,
5358                        em_advance,
5359                        self.max_line_number_width(&snapshot, cx),
5360                        cx,
5361                    );
5362                    let text_width = bounds.size.width - gutter_dimensions.width;
5363
5364                    let right_margin = if snapshot.mode == EditorMode::Full {
5365                        EditorElement::SCROLLBAR_WIDTH
5366                    } else {
5367                        px(0.)
5368                    };
5369                    let overscroll = size(em_width + right_margin, px(0.));
5370
5371                    let editor_width =
5372                        text_width - gutter_dimensions.margin - overscroll.width - em_width;
5373
5374                    snapshot = self.editor.update(cx, |editor, cx| {
5375                        editor.last_bounds = Some(bounds);
5376                        editor.gutter_dimensions = gutter_dimensions;
5377                        editor.set_visible_line_count(bounds.size.height / line_height, cx);
5378
5379                        if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
5380                            snapshot
5381                        } else {
5382                            let wrap_width = match editor.soft_wrap_mode(cx) {
5383                                SoftWrap::GitDiff => None,
5384                                SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
5385                                SoftWrap::EditorWidth => Some(editor_width),
5386                                SoftWrap::Column(column) => Some(column as f32 * em_advance),
5387                                SoftWrap::Bounded(column) => {
5388                                    Some(editor_width.min(column as f32 * em_advance))
5389                                }
5390                            };
5391
5392                            if editor.set_wrap_width(wrap_width, cx) {
5393                                editor.snapshot(cx)
5394                            } else {
5395                                snapshot
5396                            }
5397                        }
5398                    });
5399
5400                    let wrap_guides = self
5401                        .editor
5402                        .read(cx)
5403                        .wrap_guides(cx)
5404                        .iter()
5405                        .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
5406                        .collect::<SmallVec<[_; 2]>>();
5407
5408                    let hitbox = cx.insert_hitbox(bounds, false);
5409                    let gutter_hitbox =
5410                        cx.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
5411                    let text_hitbox = cx.insert_hitbox(
5412                        Bounds {
5413                            origin: gutter_hitbox.upper_right(),
5414                            size: size(text_width, bounds.size.height),
5415                        },
5416                        false,
5417                    );
5418                    // Offset the content_bounds from the text_bounds by the gutter margin (which
5419                    // is roughly half a character wide) to make hit testing work more like how we want.
5420                    let content_origin =
5421                        text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
5422
5423                    let height_in_lines = bounds.size.height / line_height;
5424                    let max_row = snapshot.max_point().row().as_f32();
5425                    let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
5426                        (max_row - height_in_lines + 1.).max(0.)
5427                    } else {
5428                        let settings = EditorSettings::get_global(cx);
5429                        match settings.scroll_beyond_last_line {
5430                            ScrollBeyondLastLine::OnePage => max_row,
5431                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
5432                            ScrollBeyondLastLine::VerticalScrollMargin => {
5433                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
5434                                    .max(0.)
5435                            }
5436                        }
5437                    };
5438
5439                    let mut autoscroll_request = None;
5440                    let mut autoscroll_containing_element = false;
5441                    let mut autoscroll_horizontally = false;
5442                    self.editor.update(cx, |editor, cx| {
5443                        autoscroll_request = editor.autoscroll_request();
5444                        autoscroll_containing_element =
5445                            autoscroll_request.is_some() || editor.has_pending_selection();
5446                        autoscroll_horizontally =
5447                            editor.autoscroll_vertically(bounds, line_height, max_scroll_top, cx);
5448                        snapshot = editor.snapshot(cx);
5449                    });
5450
5451                    let mut scroll_position = snapshot.scroll_position();
5452                    // The scroll position is a fractional point, the whole number of which represents
5453                    // the top of the window in terms of display rows.
5454                    let start_row = DisplayRow(scroll_position.y as u32);
5455                    let max_row = snapshot.max_point().row();
5456                    let end_row = cmp::min(
5457                        (scroll_position.y + height_in_lines).ceil() as u32,
5458                        max_row.next_row().0,
5459                    );
5460                    let end_row = DisplayRow(end_row);
5461
5462                    let buffer_rows = snapshot
5463                        .buffer_rows(start_row)
5464                        .take((start_row..end_row).len())
5465                        .collect::<Vec<_>>();
5466                    let is_row_soft_wrapped =
5467                        |row| buffer_rows.get(row).copied().flatten().is_none();
5468
5469                    let start_anchor = if start_row == Default::default() {
5470                        Anchor::min()
5471                    } else {
5472                        snapshot.buffer_snapshot.anchor_before(
5473                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
5474                        )
5475                    };
5476                    let end_anchor = if end_row > max_row {
5477                        Anchor::max()
5478                    } else {
5479                        snapshot.buffer_snapshot.anchor_before(
5480                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
5481                        )
5482                    };
5483
5484                    let highlighted_rows = self
5485                        .editor
5486                        .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
5487                    let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
5488                        start_anchor..end_anchor,
5489                        &snapshot.display_snapshot,
5490                        cx.theme().colors(),
5491                    );
5492                    let highlighted_gutter_ranges =
5493                        self.editor.read(cx).gutter_highlights_in_range(
5494                            start_anchor..end_anchor,
5495                            &snapshot.display_snapshot,
5496                            cx,
5497                        );
5498
5499                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
5500                        start_anchor..end_anchor,
5501                        &snapshot.display_snapshot,
5502                        cx,
5503                    );
5504
5505                    let local_selections: Vec<Selection<Point>> =
5506                        self.editor.update(cx, |editor, cx| {
5507                            let mut selections = editor
5508                                .selections
5509                                .disjoint_in_range(start_anchor..end_anchor, cx);
5510                            selections.extend(editor.selections.pending(cx));
5511                            selections
5512                        });
5513
5514                    let (selections, active_rows, newest_selection_head) = self.layout_selections(
5515                        start_anchor,
5516                        end_anchor,
5517                        &local_selections,
5518                        &snapshot,
5519                        start_row,
5520                        end_row,
5521                        cx,
5522                    );
5523
5524                    let line_numbers = self.layout_line_numbers(
5525                        start_row..end_row,
5526                        buffer_rows.iter().copied(),
5527                        &active_rows,
5528                        newest_selection_head,
5529                        &snapshot,
5530                        cx,
5531                    );
5532
5533                    let mut crease_toggles = cx.with_element_namespace("crease_toggles", |cx| {
5534                        self.layout_crease_toggles(
5535                            start_row..end_row,
5536                            buffer_rows.iter().copied(),
5537                            &active_rows,
5538                            &snapshot,
5539                            cx,
5540                        )
5541                    });
5542                    let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
5543                        self.layout_crease_trailers(buffer_rows.iter().copied(), &snapshot, cx)
5544                    });
5545
5546                    let display_hunks = self.layout_gutter_git_hunks(
5547                        line_height,
5548                        &gutter_hitbox,
5549                        start_row..end_row,
5550                        start_anchor..end_anchor,
5551                        &snapshot,
5552                        cx,
5553                    );
5554
5555                    let mut max_visible_line_width = Pixels::ZERO;
5556                    let mut line_layouts = Self::layout_lines(
5557                        start_row..end_row,
5558                        &snapshot,
5559                        &self.style,
5560                        editor_width,
5561                        is_row_soft_wrapped,
5562                        cx,
5563                    );
5564                    for line_with_invisibles in &line_layouts {
5565                        if line_with_invisibles.width > max_visible_line_width {
5566                            max_visible_line_width = line_with_invisibles.width;
5567                        }
5568                    }
5569
5570                    let longest_line_width = layout_line(
5571                        snapshot.longest_row(),
5572                        &snapshot,
5573                        &style,
5574                        editor_width,
5575                        is_row_soft_wrapped,
5576                        cx,
5577                    )
5578                    .width;
5579                    let mut scroll_width =
5580                        longest_line_width.max(max_visible_line_width) + overscroll.width;
5581
5582                    let blocks = cx.with_element_namespace("blocks", |cx| {
5583                        self.render_blocks(
5584                            start_row..end_row,
5585                            &snapshot,
5586                            &hitbox,
5587                            &text_hitbox,
5588                            editor_width,
5589                            &mut scroll_width,
5590                            &gutter_dimensions,
5591                            em_width,
5592                            gutter_dimensions.full_width(),
5593                            line_height,
5594                            &line_layouts,
5595                            &local_selections,
5596                            is_row_soft_wrapped,
5597                            cx,
5598                        )
5599                    });
5600                    let mut blocks = match blocks {
5601                        Ok(blocks) => blocks,
5602                        Err(resized_blocks) => {
5603                            self.editor.update(cx, |editor, cx| {
5604                                editor.resize_blocks(resized_blocks, autoscroll_request, cx)
5605                            });
5606                            return self.prepaint(None, bounds, &mut (), cx);
5607                        }
5608                    };
5609
5610                    let start_buffer_row =
5611                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
5612                    let end_buffer_row =
5613                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
5614
5615                    let scroll_max = point(
5616                        ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
5617                        max_row.as_f32(),
5618                    );
5619
5620                    self.editor.update(cx, |editor, cx| {
5621                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
5622
5623                        let autoscrolled = if autoscroll_horizontally {
5624                            editor.autoscroll_horizontally(
5625                                start_row,
5626                                text_hitbox.size.width,
5627                                scroll_width,
5628                                em_width,
5629                                &line_layouts,
5630                                cx,
5631                            )
5632                        } else {
5633                            false
5634                        };
5635
5636                        if clamped || autoscrolled {
5637                            snapshot = editor.snapshot(cx);
5638                            scroll_position = snapshot.scroll_position();
5639                        }
5640                    });
5641
5642                    let scroll_pixel_position = point(
5643                        scroll_position.x * em_width,
5644                        scroll_position.y * line_height,
5645                    );
5646
5647                    let indent_guides = self.layout_indent_guides(
5648                        content_origin,
5649                        text_hitbox.origin,
5650                        start_buffer_row..end_buffer_row,
5651                        scroll_pixel_position,
5652                        line_height,
5653                        &snapshot,
5654                        cx,
5655                    );
5656
5657                    let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
5658                        self.prepaint_crease_trailers(
5659                            crease_trailers,
5660                            &line_layouts,
5661                            line_height,
5662                            content_origin,
5663                            scroll_pixel_position,
5664                            em_width,
5665                            cx,
5666                        )
5667                    });
5668
5669                    let mut inline_blame = None;
5670                    if let Some(newest_selection_head) = newest_selection_head {
5671                        let display_row = newest_selection_head.row();
5672                        if (start_row..end_row).contains(&display_row) {
5673                            let line_ix = display_row.minus(start_row) as usize;
5674                            let line_layout = &line_layouts[line_ix];
5675                            let crease_trailer_layout = crease_trailers[line_ix].as_ref();
5676                            inline_blame = self.layout_inline_blame(
5677                                display_row,
5678                                &snapshot.display_snapshot,
5679                                line_layout,
5680                                crease_trailer_layout,
5681                                em_width,
5682                                content_origin,
5683                                scroll_pixel_position,
5684                                line_height,
5685                                cx,
5686                            );
5687                        }
5688                    }
5689
5690                    let blamed_display_rows = self.layout_blame_entries(
5691                        buffer_rows.into_iter(),
5692                        em_width,
5693                        scroll_position,
5694                        line_height,
5695                        &gutter_hitbox,
5696                        gutter_dimensions.git_blame_entries_width,
5697                        cx,
5698                    );
5699
5700                    let scroll_max = point(
5701                        ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
5702                        max_scroll_top,
5703                    );
5704
5705                    self.editor.update(cx, |editor, cx| {
5706                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
5707
5708                        let autoscrolled = if autoscroll_horizontally {
5709                            editor.autoscroll_horizontally(
5710                                start_row,
5711                                text_hitbox.size.width,
5712                                scroll_width,
5713                                em_width,
5714                                &line_layouts,
5715                                cx,
5716                            )
5717                        } else {
5718                            false
5719                        };
5720
5721                        if clamped || autoscrolled {
5722                            snapshot = editor.snapshot(cx);
5723                            scroll_position = snapshot.scroll_position();
5724                        }
5725                    });
5726
5727                    let line_elements = self.prepaint_lines(
5728                        start_row,
5729                        &mut line_layouts,
5730                        line_height,
5731                        scroll_pixel_position,
5732                        content_origin,
5733                        cx,
5734                    );
5735
5736                    let mut block_start_rows = HashSet::default();
5737                    cx.with_element_namespace("blocks", |cx| {
5738                        self.layout_blocks(
5739                            &mut blocks,
5740                            &mut block_start_rows,
5741                            &hitbox,
5742                            line_height,
5743                            scroll_pixel_position,
5744                            cx,
5745                        );
5746                    });
5747
5748                    let cursors = self.collect_cursors(&snapshot, cx);
5749                    let visible_row_range = start_row..end_row;
5750                    let non_visible_cursors = cursors
5751                        .iter()
5752                        .any(move |c| !visible_row_range.contains(&c.0.row()));
5753
5754                    let visible_cursors = self.layout_visible_cursors(
5755                        &snapshot,
5756                        &selections,
5757                        &block_start_rows,
5758                        start_row..end_row,
5759                        &line_layouts,
5760                        &text_hitbox,
5761                        content_origin,
5762                        scroll_position,
5763                        scroll_pixel_position,
5764                        line_height,
5765                        em_width,
5766                        autoscroll_containing_element,
5767                        cx,
5768                    );
5769
5770                    let scrollbar_layout = self.layout_scrollbar(
5771                        &snapshot,
5772                        bounds,
5773                        scroll_position,
5774                        height_in_lines,
5775                        non_visible_cursors,
5776                        cx,
5777                    );
5778
5779                    let gutter_settings = EditorSettings::get_global(cx).gutter;
5780
5781                    let expanded_add_hunks_by_rows = self.editor.update(cx, |editor, _| {
5782                        editor
5783                            .diff_map
5784                            .hunks(false)
5785                            .filter(|hunk| hunk.status == DiffHunkStatus::Added)
5786                            .map(|expanded_hunk| {
5787                                let start_row = expanded_hunk
5788                                    .hunk_range
5789                                    .start
5790                                    .to_display_point(&snapshot)
5791                                    .row();
5792                                (start_row, expanded_hunk.clone())
5793                            })
5794                            .collect::<HashMap<_, _>>()
5795                    });
5796
5797                    let rows_with_hunk_bounds = display_hunks
5798                        .iter()
5799                        .filter_map(|(hunk, hitbox)| Some((hunk, hitbox.as_ref()?.bounds)))
5800                        .fold(
5801                            HashMap::default(),
5802                            |mut rows_with_hunk_bounds, (hunk, bounds)| {
5803                                match hunk {
5804                                    DisplayDiffHunk::Folded { display_row } => {
5805                                        rows_with_hunk_bounds.insert(*display_row, bounds);
5806                                    }
5807                                    DisplayDiffHunk::Unfolded {
5808                                        display_row_range, ..
5809                                    } => {
5810                                        for display_row in display_row_range.iter_rows() {
5811                                            rows_with_hunk_bounds.insert(display_row, bounds);
5812                                        }
5813                                    }
5814                                }
5815                                rows_with_hunk_bounds
5816                            },
5817                        );
5818                    let mut _context_menu_visible = false;
5819                    let mut code_actions_indicator = None;
5820                    if let Some(newest_selection_head) = newest_selection_head {
5821                        if (start_row..end_row).contains(&newest_selection_head.row()) {
5822                            _context_menu_visible = self.layout_context_menu(
5823                                line_height,
5824                                &hitbox,
5825                                &text_hitbox,
5826                                content_origin,
5827                                start_row,
5828                                scroll_pixel_position,
5829                                &line_layouts,
5830                                newest_selection_head,
5831                                gutter_dimensions.width - gutter_dimensions.left_padding,
5832                                cx,
5833                            );
5834
5835                            let show_code_actions = snapshot
5836                                .show_code_actions
5837                                .unwrap_or(gutter_settings.code_actions);
5838                            if show_code_actions {
5839                                let newest_selection_point =
5840                                    newest_selection_head.to_point(&snapshot.display_snapshot);
5841                                let newest_selection_display_row =
5842                                    newest_selection_point.to_display_point(&snapshot).row();
5843                                if !expanded_add_hunks_by_rows
5844                                    .contains_key(&newest_selection_display_row)
5845                                {
5846                                    if !snapshot
5847                                        .is_line_folded(MultiBufferRow(newest_selection_point.row))
5848                                    {
5849                                        let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
5850                                            MultiBufferRow(newest_selection_point.row),
5851                                        );
5852                                        if let Some((buffer, range)) = buffer {
5853                                            let buffer_id = buffer.remote_id();
5854                                            let row = range.start.row;
5855                                            let has_test_indicator = self
5856                                                .editor
5857                                                .read(cx)
5858                                                .tasks
5859                                                .contains_key(&(buffer_id, row));
5860
5861                                            if !has_test_indicator {
5862                                                code_actions_indicator = self
5863                                                    .layout_code_actions_indicator(
5864                                                        line_height,
5865                                                        newest_selection_head,
5866                                                        scroll_pixel_position,
5867                                                        &gutter_dimensions,
5868                                                        &gutter_hitbox,
5869                                                        &rows_with_hunk_bounds,
5870                                                        cx,
5871                                                    );
5872                                            }
5873                                        }
5874                                    }
5875                                }
5876                            }
5877                        }
5878                    }
5879
5880                    let test_indicators = if gutter_settings.runnables {
5881                        self.layout_run_indicators(
5882                            line_height,
5883                            start_row..end_row,
5884                            scroll_pixel_position,
5885                            &gutter_dimensions,
5886                            &gutter_hitbox,
5887                            &rows_with_hunk_bounds,
5888                            &snapshot,
5889                            cx,
5890                        )
5891                    } else {
5892                        Vec::new()
5893                    };
5894
5895                    self.layout_signature_help(
5896                        &hitbox,
5897                        content_origin,
5898                        scroll_pixel_position,
5899                        newest_selection_head,
5900                        start_row,
5901                        &line_layouts,
5902                        line_height,
5903                        em_width,
5904                        cx,
5905                    );
5906
5907                    if !cx.has_active_drag() {
5908                        self.layout_hover_popovers(
5909                            &snapshot,
5910                            &hitbox,
5911                            &text_hitbox,
5912                            start_row..end_row,
5913                            content_origin,
5914                            scroll_pixel_position,
5915                            &line_layouts,
5916                            line_height,
5917                            em_width,
5918                            cx,
5919                        );
5920                    }
5921
5922                    let inline_completion_popover = self.layout_inline_completion_popover(
5923                        &text_hitbox.bounds,
5924                        &snapshot,
5925                        start_row..end_row,
5926                        scroll_position.y,
5927                        scroll_position.y + height_in_lines,
5928                        &line_layouts,
5929                        line_height,
5930                        scroll_pixel_position,
5931                        editor_width,
5932                        &style,
5933                        cx,
5934                    );
5935
5936                    let mouse_context_menu = self.layout_mouse_context_menu(
5937                        &snapshot,
5938                        start_row..end_row,
5939                        content_origin,
5940                        cx,
5941                    );
5942
5943                    cx.with_element_namespace("crease_toggles", |cx| {
5944                        self.prepaint_crease_toggles(
5945                            &mut crease_toggles,
5946                            line_height,
5947                            &gutter_dimensions,
5948                            gutter_settings,
5949                            scroll_pixel_position,
5950                            &gutter_hitbox,
5951                            cx,
5952                        )
5953                    });
5954
5955                    let invisible_symbol_font_size = font_size / 2.;
5956                    let tab_invisible = cx
5957                        .text_system()
5958                        .shape_line(
5959                            "".into(),
5960                            invisible_symbol_font_size,
5961                            &[TextRun {
5962                                len: "".len(),
5963                                font: self.style.text.font(),
5964                                color: cx.theme().colors().editor_invisible,
5965                                background_color: None,
5966                                underline: None,
5967                                strikethrough: None,
5968                            }],
5969                        )
5970                        .unwrap();
5971                    let space_invisible = cx
5972                        .text_system()
5973                        .shape_line(
5974                            "".into(),
5975                            invisible_symbol_font_size,
5976                            &[TextRun {
5977                                len: "".len(),
5978                                font: self.style.text.font(),
5979                                color: cx.theme().colors().editor_invisible,
5980                                background_color: None,
5981                                underline: None,
5982                                strikethrough: None,
5983                            }],
5984                        )
5985                        .unwrap();
5986
5987                    EditorLayout {
5988                        mode: snapshot.mode,
5989                        position_map: Rc::new(PositionMap {
5990                            size: bounds.size,
5991                            scroll_pixel_position,
5992                            scroll_max,
5993                            line_layouts,
5994                            line_height,
5995                            em_width,
5996                            em_advance,
5997                            snapshot,
5998                        }),
5999                        visible_display_row_range: start_row..end_row,
6000                        wrap_guides,
6001                        indent_guides,
6002                        hitbox,
6003                        text_hitbox,
6004                        gutter_hitbox,
6005                        gutter_dimensions,
6006                        display_hunks,
6007                        content_origin,
6008                        scrollbar_layout,
6009                        active_rows,
6010                        highlighted_rows,
6011                        highlighted_ranges,
6012                        highlighted_gutter_ranges,
6013                        redacted_ranges,
6014                        line_elements,
6015                        line_numbers,
6016                        blamed_display_rows,
6017                        inline_blame,
6018                        blocks,
6019                        cursors,
6020                        visible_cursors,
6021                        selections,
6022                        inline_completion_popover,
6023                        mouse_context_menu,
6024                        test_indicators,
6025                        code_actions_indicator,
6026                        crease_toggles,
6027                        crease_trailers,
6028                        tab_invisible,
6029                        space_invisible,
6030                    }
6031                })
6032            })
6033        })
6034    }
6035
6036    fn paint(
6037        &mut self,
6038        _: Option<&GlobalElementId>,
6039        bounds: Bounds<gpui::Pixels>,
6040        _: &mut Self::RequestLayoutState,
6041        layout: &mut Self::PrepaintState,
6042        cx: &mut WindowContext,
6043    ) {
6044        let focus_handle = self.editor.focus_handle(cx);
6045        let key_context = self.editor.update(cx, |editor, cx| editor.key_context(cx));
6046        cx.set_key_context(key_context);
6047        cx.handle_input(
6048            &focus_handle,
6049            ElementInputHandler::new(bounds, self.editor.clone()),
6050        );
6051        self.register_actions(cx);
6052        self.register_key_listeners(cx, layout);
6053
6054        let text_style = TextStyleRefinement {
6055            font_size: Some(self.style.text.font_size),
6056            line_height: Some(self.style.text.line_height),
6057            ..Default::default()
6058        };
6059        let hovered_hunk = layout
6060            .display_hunks
6061            .iter()
6062            .find_map(|(hunk, hunk_hitbox)| match hunk {
6063                DisplayDiffHunk::Folded { .. } => None,
6064                DisplayDiffHunk::Unfolded {
6065                    diff_base_byte_range,
6066                    multi_buffer_range,
6067                    status,
6068                    ..
6069                } => {
6070                    if hunk_hitbox
6071                        .as_ref()
6072                        .map(|hitbox| hitbox.is_hovered(cx))
6073                        .unwrap_or(false)
6074                    {
6075                        Some(HoveredHunk {
6076                            status: *status,
6077                            multi_buffer_range: multi_buffer_range.clone(),
6078                            diff_base_byte_range: diff_base_byte_range.clone(),
6079                        })
6080                    } else {
6081                        None
6082                    }
6083                }
6084            });
6085        let rem_size = self.rem_size(cx);
6086        cx.with_rem_size(rem_size, |cx| {
6087            cx.with_text_style(Some(text_style), |cx| {
6088                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
6089                    self.paint_mouse_listeners(layout, hovered_hunk, cx);
6090                    self.paint_background(layout, cx);
6091                    self.paint_indent_guides(layout, cx);
6092
6093                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
6094                        self.paint_blamed_display_rows(layout, cx);
6095                        self.paint_line_numbers(layout, cx);
6096                    }
6097
6098                    self.paint_text(layout, cx);
6099
6100                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
6101                        self.paint_gutter_highlights(layout, cx);
6102                        self.paint_gutter_indicators(layout, cx);
6103                    }
6104
6105                    if !layout.blocks.is_empty() {
6106                        cx.with_element_namespace("blocks", |cx| {
6107                            self.paint_blocks(layout, cx);
6108                        });
6109                    }
6110
6111                    self.paint_scrollbar(layout, cx);
6112                    self.paint_inline_completion_popover(layout, cx);
6113                    self.paint_mouse_context_menu(layout, cx);
6114                });
6115            })
6116        })
6117    }
6118}
6119
6120pub(super) fn gutter_bounds(
6121    editor_bounds: Bounds<Pixels>,
6122    gutter_dimensions: GutterDimensions,
6123) -> Bounds<Pixels> {
6124    Bounds {
6125        origin: editor_bounds.origin,
6126        size: size(gutter_dimensions.width, editor_bounds.size.height),
6127    }
6128}
6129
6130impl IntoElement for EditorElement {
6131    type Element = Self;
6132
6133    fn into_element(self) -> Self::Element {
6134        self
6135    }
6136}
6137
6138pub struct EditorLayout {
6139    position_map: Rc<PositionMap>,
6140    hitbox: Hitbox,
6141    text_hitbox: Hitbox,
6142    gutter_hitbox: Hitbox,
6143    gutter_dimensions: GutterDimensions,
6144    content_origin: gpui::Point<Pixels>,
6145    scrollbar_layout: Option<ScrollbarLayout>,
6146    mode: EditorMode,
6147    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
6148    indent_guides: Option<Vec<IndentGuideLayout>>,
6149    visible_display_row_range: Range<DisplayRow>,
6150    active_rows: BTreeMap<DisplayRow, bool>,
6151    highlighted_rows: BTreeMap<DisplayRow, Hsla>,
6152    line_elements: SmallVec<[AnyElement; 1]>,
6153    line_numbers: Vec<Option<ShapedLine>>,
6154    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
6155    blamed_display_rows: Option<Vec<AnyElement>>,
6156    inline_blame: Option<AnyElement>,
6157    blocks: Vec<BlockLayout>,
6158    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
6159    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
6160    redacted_ranges: Vec<Range<DisplayPoint>>,
6161    cursors: Vec<(DisplayPoint, Hsla)>,
6162    visible_cursors: Vec<CursorLayout>,
6163    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
6164    code_actions_indicator: Option<AnyElement>,
6165    test_indicators: Vec<AnyElement>,
6166    crease_toggles: Vec<Option<AnyElement>>,
6167    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
6168    inline_completion_popover: Option<AnyElement>,
6169    mouse_context_menu: Option<AnyElement>,
6170    tab_invisible: ShapedLine,
6171    space_invisible: ShapedLine,
6172}
6173
6174impl EditorLayout {
6175    fn line_end_overshoot(&self) -> Pixels {
6176        0.15 * self.position_map.line_height
6177    }
6178}
6179
6180struct ColoredRange<T> {
6181    start: T,
6182    end: T,
6183    color: Hsla,
6184}
6185
6186#[derive(Clone)]
6187struct ScrollbarLayout {
6188    hitbox: Hitbox,
6189    visible_row_range: Range<f32>,
6190    visible: bool,
6191    row_height: Pixels,
6192    thumb_height: Pixels,
6193}
6194
6195impl ScrollbarLayout {
6196    const BORDER_WIDTH: Pixels = px(1.0);
6197    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
6198    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
6199    const MIN_THUMB_HEIGHT: Pixels = px(20.0);
6200
6201    fn thumb_bounds(&self) -> Bounds<Pixels> {
6202        let thumb_top = self.y_for_row(self.visible_row_range.start);
6203        let thumb_bottom = thumb_top + self.thumb_height;
6204        Bounds::from_corners(
6205            point(self.hitbox.left(), thumb_top),
6206            point(self.hitbox.right(), thumb_bottom),
6207        )
6208    }
6209
6210    fn y_for_row(&self, row: f32) -> Pixels {
6211        self.hitbox.top() + row * self.row_height
6212    }
6213
6214    fn marker_quads_for_ranges(
6215        &self,
6216        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
6217        column: Option<usize>,
6218    ) -> Vec<PaintQuad> {
6219        struct MinMax {
6220            min: Pixels,
6221            max: Pixels,
6222        }
6223        let (x_range, height_limit) = if let Some(column) = column {
6224            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
6225            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
6226            let end = start + column_width;
6227            (
6228                Range { start, end },
6229                MinMax {
6230                    min: Self::MIN_MARKER_HEIGHT,
6231                    max: px(f32::MAX),
6232                },
6233            )
6234        } else {
6235            (
6236                Range {
6237                    start: Self::BORDER_WIDTH,
6238                    end: self.hitbox.size.width,
6239                },
6240                MinMax {
6241                    min: Self::LINE_MARKER_HEIGHT,
6242                    max: Self::LINE_MARKER_HEIGHT,
6243                },
6244            )
6245        };
6246
6247        let row_to_y = |row: DisplayRow| row.as_f32() * self.row_height;
6248        let mut pixel_ranges = row_ranges
6249            .into_iter()
6250            .map(|range| {
6251                let start_y = row_to_y(range.start);
6252                let end_y = row_to_y(range.end)
6253                    + self.row_height.max(height_limit.min).min(height_limit.max);
6254                ColoredRange {
6255                    start: start_y,
6256                    end: end_y,
6257                    color: range.color,
6258                }
6259            })
6260            .peekable();
6261
6262        let mut quads = Vec::new();
6263        while let Some(mut pixel_range) = pixel_ranges.next() {
6264            while let Some(next_pixel_range) = pixel_ranges.peek() {
6265                if pixel_range.end >= next_pixel_range.start - px(1.0)
6266                    && pixel_range.color == next_pixel_range.color
6267                {
6268                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
6269                    pixel_ranges.next();
6270                } else {
6271                    break;
6272                }
6273            }
6274
6275            let bounds = Bounds::from_corners(
6276                point(x_range.start, pixel_range.start),
6277                point(x_range.end, pixel_range.end),
6278            );
6279            quads.push(quad(
6280                bounds,
6281                Corners::default(),
6282                pixel_range.color,
6283                Edges::default(),
6284                Hsla::transparent_black(),
6285            ));
6286        }
6287
6288        quads
6289    }
6290}
6291
6292struct CreaseTrailerLayout {
6293    element: AnyElement,
6294    bounds: Bounds<Pixels>,
6295}
6296
6297struct PositionMap {
6298    size: Size<Pixels>,
6299    line_height: Pixels,
6300    scroll_pixel_position: gpui::Point<Pixels>,
6301    scroll_max: gpui::Point<f32>,
6302    em_width: Pixels,
6303    em_advance: Pixels,
6304    line_layouts: Vec<LineWithInvisibles>,
6305    snapshot: EditorSnapshot,
6306}
6307
6308#[derive(Debug, Copy, Clone)]
6309pub struct PointForPosition {
6310    pub previous_valid: DisplayPoint,
6311    pub next_valid: DisplayPoint,
6312    pub exact_unclipped: DisplayPoint,
6313    pub column_overshoot_after_line_end: u32,
6314}
6315
6316impl PointForPosition {
6317    pub fn as_valid(&self) -> Option<DisplayPoint> {
6318        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
6319            Some(self.previous_valid)
6320        } else {
6321            None
6322        }
6323    }
6324}
6325
6326impl PositionMap {
6327    fn point_for_position(
6328        &self,
6329        text_bounds: Bounds<Pixels>,
6330        position: gpui::Point<Pixels>,
6331    ) -> PointForPosition {
6332        let scroll_position = self.snapshot.scroll_position();
6333        let position = position - text_bounds.origin;
6334        let y = position.y.max(px(0.)).min(self.size.height);
6335        let x = position.x + (scroll_position.x * self.em_width);
6336        let row = ((y / self.line_height) + scroll_position.y) as u32;
6337
6338        let (column, x_overshoot_after_line_end) = if let Some(line) = self
6339            .line_layouts
6340            .get(row as usize - scroll_position.y as usize)
6341        {
6342            if let Some(ix) = line.index_for_x(x) {
6343                (ix as u32, px(0.))
6344            } else {
6345                (line.len as u32, px(0.).max(x - line.width))
6346            }
6347        } else {
6348            (0, x)
6349        };
6350
6351        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
6352        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
6353        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
6354
6355        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
6356        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
6357        PointForPosition {
6358            previous_valid,
6359            next_valid,
6360            exact_unclipped,
6361            column_overshoot_after_line_end,
6362        }
6363    }
6364}
6365
6366struct BlockLayout {
6367    id: BlockId,
6368    row: Option<DisplayRow>,
6369    element: AnyElement,
6370    available_space: Size<AvailableSpace>,
6371    style: BlockStyle,
6372}
6373
6374fn layout_line(
6375    row: DisplayRow,
6376    snapshot: &EditorSnapshot,
6377    style: &EditorStyle,
6378    text_width: Pixels,
6379    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6380    cx: &mut WindowContext,
6381) -> LineWithInvisibles {
6382    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
6383    LineWithInvisibles::from_chunks(
6384        chunks,
6385        &style,
6386        MAX_LINE_LEN,
6387        1,
6388        snapshot.mode,
6389        text_width,
6390        is_row_soft_wrapped,
6391        cx,
6392    )
6393    .pop()
6394    .unwrap()
6395}
6396
6397#[derive(Debug)]
6398pub struct IndentGuideLayout {
6399    origin: gpui::Point<Pixels>,
6400    length: Pixels,
6401    single_indent_width: Pixels,
6402    depth: u32,
6403    active: bool,
6404    settings: IndentGuideSettings,
6405}
6406
6407pub struct CursorLayout {
6408    origin: gpui::Point<Pixels>,
6409    block_width: Pixels,
6410    line_height: Pixels,
6411    color: Hsla,
6412    shape: CursorShape,
6413    block_text: Option<ShapedLine>,
6414    cursor_name: Option<AnyElement>,
6415}
6416
6417#[derive(Debug)]
6418pub struct CursorName {
6419    string: SharedString,
6420    color: Hsla,
6421    is_top_row: bool,
6422}
6423
6424impl CursorLayout {
6425    pub fn new(
6426        origin: gpui::Point<Pixels>,
6427        block_width: Pixels,
6428        line_height: Pixels,
6429        color: Hsla,
6430        shape: CursorShape,
6431        block_text: Option<ShapedLine>,
6432    ) -> CursorLayout {
6433        CursorLayout {
6434            origin,
6435            block_width,
6436            line_height,
6437            color,
6438            shape,
6439            block_text,
6440            cursor_name: None,
6441        }
6442    }
6443
6444    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
6445        Bounds {
6446            origin: self.origin + origin,
6447            size: size(self.block_width, self.line_height),
6448        }
6449    }
6450
6451    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
6452        match self.shape {
6453            CursorShape::Bar => Bounds {
6454                origin: self.origin + origin,
6455                size: size(px(2.0), self.line_height),
6456            },
6457            CursorShape::Block | CursorShape::Hollow => Bounds {
6458                origin: self.origin + origin,
6459                size: size(self.block_width, self.line_height),
6460            },
6461            CursorShape::Underline => Bounds {
6462                origin: self.origin
6463                    + origin
6464                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
6465                size: size(self.block_width, px(2.0)),
6466            },
6467        }
6468    }
6469
6470    pub fn layout(
6471        &mut self,
6472        origin: gpui::Point<Pixels>,
6473        cursor_name: Option<CursorName>,
6474        cx: &mut WindowContext,
6475    ) {
6476        if let Some(cursor_name) = cursor_name {
6477            let bounds = self.bounds(origin);
6478            let text_size = self.line_height / 1.5;
6479
6480            let name_origin = if cursor_name.is_top_row {
6481                point(bounds.right() - px(1.), bounds.top())
6482            } else {
6483                point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
6484            };
6485            let mut name_element = div()
6486                .bg(self.color)
6487                .text_size(text_size)
6488                .px_0p5()
6489                .line_height(text_size + px(2.))
6490                .text_color(cursor_name.color)
6491                .child(cursor_name.string.clone())
6492                .into_any_element();
6493
6494            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), cx);
6495
6496            self.cursor_name = Some(name_element);
6497        }
6498    }
6499
6500    pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
6501        let bounds = self.bounds(origin);
6502
6503        //Draw background or border quad
6504        let cursor = if matches!(self.shape, CursorShape::Hollow) {
6505            outline(bounds, self.color)
6506        } else {
6507            fill(bounds, self.color)
6508        };
6509
6510        if let Some(name) = &mut self.cursor_name {
6511            name.paint(cx);
6512        }
6513
6514        cx.paint_quad(cursor);
6515
6516        if let Some(block_text) = &self.block_text {
6517            block_text
6518                .paint(self.origin + origin, self.line_height, cx)
6519                .log_err();
6520        }
6521    }
6522
6523    pub fn shape(&self) -> CursorShape {
6524        self.shape
6525    }
6526}
6527
6528#[derive(Debug)]
6529pub struct HighlightedRange {
6530    pub start_y: Pixels,
6531    pub line_height: Pixels,
6532    pub lines: Vec<HighlightedRangeLine>,
6533    pub color: Hsla,
6534    pub corner_radius: Pixels,
6535}
6536
6537#[derive(Debug)]
6538pub struct HighlightedRangeLine {
6539    pub start_x: Pixels,
6540    pub end_x: Pixels,
6541}
6542
6543impl HighlightedRange {
6544    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
6545        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
6546            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
6547            self.paint_lines(
6548                self.start_y + self.line_height,
6549                &self.lines[1..],
6550                bounds,
6551                cx,
6552            );
6553        } else {
6554            self.paint_lines(self.start_y, &self.lines, bounds, cx);
6555        }
6556    }
6557
6558    fn paint_lines(
6559        &self,
6560        start_y: Pixels,
6561        lines: &[HighlightedRangeLine],
6562        _bounds: Bounds<Pixels>,
6563        cx: &mut WindowContext,
6564    ) {
6565        if lines.is_empty() {
6566            return;
6567        }
6568
6569        let first_line = lines.first().unwrap();
6570        let last_line = lines.last().unwrap();
6571
6572        let first_top_left = point(first_line.start_x, start_y);
6573        let first_top_right = point(first_line.end_x, start_y);
6574
6575        let curve_height = point(Pixels::ZERO, self.corner_radius);
6576        let curve_width = |start_x: Pixels, end_x: Pixels| {
6577            let max = (end_x - start_x) / 2.;
6578            let width = if max < self.corner_radius {
6579                max
6580            } else {
6581                self.corner_radius
6582            };
6583
6584            point(width, Pixels::ZERO)
6585        };
6586
6587        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
6588        let mut path = gpui::Path::new(first_top_right - top_curve_width);
6589        path.curve_to(first_top_right + curve_height, first_top_right);
6590
6591        let mut iter = lines.iter().enumerate().peekable();
6592        while let Some((ix, line)) = iter.next() {
6593            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
6594
6595            if let Some((_, next_line)) = iter.peek() {
6596                let next_top_right = point(next_line.end_x, bottom_right.y);
6597
6598                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
6599                    Ordering::Equal => {
6600                        path.line_to(bottom_right);
6601                    }
6602                    Ordering::Less => {
6603                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
6604                        path.line_to(bottom_right - curve_height);
6605                        if self.corner_radius > Pixels::ZERO {
6606                            path.curve_to(bottom_right - curve_width, bottom_right);
6607                        }
6608                        path.line_to(next_top_right + curve_width);
6609                        if self.corner_radius > Pixels::ZERO {
6610                            path.curve_to(next_top_right + curve_height, next_top_right);
6611                        }
6612                    }
6613                    Ordering::Greater => {
6614                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
6615                        path.line_to(bottom_right - curve_height);
6616                        if self.corner_radius > Pixels::ZERO {
6617                            path.curve_to(bottom_right + curve_width, bottom_right);
6618                        }
6619                        path.line_to(next_top_right - curve_width);
6620                        if self.corner_radius > Pixels::ZERO {
6621                            path.curve_to(next_top_right + curve_height, next_top_right);
6622                        }
6623                    }
6624                }
6625            } else {
6626                let curve_width = curve_width(line.start_x, line.end_x);
6627                path.line_to(bottom_right - curve_height);
6628                if self.corner_radius > Pixels::ZERO {
6629                    path.curve_to(bottom_right - curve_width, bottom_right);
6630                }
6631
6632                let bottom_left = point(line.start_x, bottom_right.y);
6633                path.line_to(bottom_left + curve_width);
6634                if self.corner_radius > Pixels::ZERO {
6635                    path.curve_to(bottom_left - curve_height, bottom_left);
6636                }
6637            }
6638        }
6639
6640        if first_line.start_x > last_line.start_x {
6641            let curve_width = curve_width(last_line.start_x, first_line.start_x);
6642            let second_top_left = point(last_line.start_x, start_y + self.line_height);
6643            path.line_to(second_top_left + curve_height);
6644            if self.corner_radius > Pixels::ZERO {
6645                path.curve_to(second_top_left + curve_width, second_top_left);
6646            }
6647            let first_bottom_left = point(first_line.start_x, second_top_left.y);
6648            path.line_to(first_bottom_left - curve_width);
6649            if self.corner_radius > Pixels::ZERO {
6650                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
6651            }
6652        }
6653
6654        path.line_to(first_top_left + curve_height);
6655        if self.corner_radius > Pixels::ZERO {
6656            path.curve_to(first_top_left + top_curve_width, first_top_left);
6657        }
6658        path.line_to(first_top_right - top_curve_width);
6659
6660        cx.paint_path(path, self.color);
6661    }
6662}
6663
6664pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
6665    (delta.pow(1.5) / 100.0).into()
6666}
6667
6668fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
6669    (delta.pow(1.2) / 300.0).into()
6670}
6671
6672pub fn register_action<T: Action>(
6673    view: &View<Editor>,
6674    cx: &mut WindowContext,
6675    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
6676) {
6677    let view = view.clone();
6678    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
6679        let action = action.downcast_ref().unwrap();
6680        if phase == DispatchPhase::Bubble {
6681            view.update(cx, |editor, cx| {
6682                listener(editor, action, cx);
6683            })
6684        }
6685    })
6686}
6687
6688fn compute_auto_height_layout(
6689    editor: &mut Editor,
6690    max_lines: usize,
6691    max_line_number_width: Pixels,
6692    known_dimensions: Size<Option<Pixels>>,
6693    available_width: AvailableSpace,
6694    cx: &mut ViewContext<Editor>,
6695) -> Option<Size<Pixels>> {
6696    let width = known_dimensions.width.or({
6697        if let AvailableSpace::Definite(available_width) = available_width {
6698            Some(available_width)
6699        } else {
6700            None
6701        }
6702    })?;
6703    if let Some(height) = known_dimensions.height {
6704        return Some(size(width, height));
6705    }
6706
6707    let style = editor.style.as_ref().unwrap();
6708    let font_id = cx.text_system().resolve_font(&style.text.font());
6709    let font_size = style.text.font_size.to_pixels(cx.rem_size());
6710    let line_height = style.text.line_height_in_pixels(cx.rem_size());
6711    let em_width = cx
6712        .text_system()
6713        .typographic_bounds(font_id, font_size, 'm')
6714        .unwrap()
6715        .size
6716        .width;
6717    let em_advance = cx
6718        .text_system()
6719        .advance(font_id, font_size, 'm')
6720        .unwrap()
6721        .width;
6722
6723    let mut snapshot = editor.snapshot(cx);
6724    let gutter_dimensions = snapshot.gutter_dimensions(
6725        font_id,
6726        font_size,
6727        em_width,
6728        em_advance,
6729        max_line_number_width,
6730        cx,
6731    );
6732
6733    editor.gutter_dimensions = gutter_dimensions;
6734    let text_width = width - gutter_dimensions.width;
6735    let overscroll = size(em_width, px(0.));
6736
6737    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
6738    if editor.set_wrap_width(Some(editor_width), cx) {
6739        snapshot = editor.snapshot(cx);
6740    }
6741
6742    let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
6743    let height = scroll_height
6744        .max(line_height)
6745        .min(line_height * max_lines as f32);
6746
6747    Some(size(width, height))
6748}
6749
6750#[cfg(test)]
6751mod tests {
6752    use super::*;
6753    use crate::{
6754        display_map::{BlockPlacement, BlockProperties},
6755        editor_tests::{init_test, update_test_language_settings},
6756        Editor, MultiBuffer,
6757    };
6758    use gpui::{TestAppContext, VisualTestContext};
6759    use language::language_settings;
6760    use log::info;
6761    use std::num::NonZeroU32;
6762    use util::test::sample_text;
6763
6764    #[gpui::test]
6765    fn test_shape_line_numbers(cx: &mut TestAppContext) {
6766        init_test(cx, |_| {});
6767        let window = cx.add_window(|cx| {
6768            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
6769            Editor::new(EditorMode::Full, buffer, None, true, cx)
6770        });
6771
6772        let editor = window.root(cx).unwrap();
6773        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6774        let element = EditorElement::new(&editor, style);
6775        let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
6776
6777        let layouts = cx
6778            .update_window(*window, |_, cx| {
6779                element.layout_line_numbers(
6780                    DisplayRow(0)..DisplayRow(6),
6781                    (0..6).map(MultiBufferRow).map(Some),
6782                    &Default::default(),
6783                    Some(DisplayPoint::new(DisplayRow(0), 0)),
6784                    &snapshot,
6785                    cx,
6786                )
6787            })
6788            .unwrap();
6789        assert_eq!(layouts.len(), 6);
6790
6791        let relative_rows = window
6792            .update(cx, |editor, cx| {
6793                let snapshot = editor.snapshot(cx);
6794                element.calculate_relative_line_numbers(
6795                    &snapshot,
6796                    &(DisplayRow(0)..DisplayRow(6)),
6797                    Some(DisplayRow(3)),
6798                )
6799            })
6800            .unwrap();
6801        assert_eq!(relative_rows[&DisplayRow(0)], 3);
6802        assert_eq!(relative_rows[&DisplayRow(1)], 2);
6803        assert_eq!(relative_rows[&DisplayRow(2)], 1);
6804        // current line has no relative number
6805        assert_eq!(relative_rows[&DisplayRow(4)], 1);
6806        assert_eq!(relative_rows[&DisplayRow(5)], 2);
6807
6808        // works if cursor is before screen
6809        let relative_rows = window
6810            .update(cx, |editor, cx| {
6811                let snapshot = editor.snapshot(cx);
6812                element.calculate_relative_line_numbers(
6813                    &snapshot,
6814                    &(DisplayRow(3)..DisplayRow(6)),
6815                    Some(DisplayRow(1)),
6816                )
6817            })
6818            .unwrap();
6819        assert_eq!(relative_rows.len(), 3);
6820        assert_eq!(relative_rows[&DisplayRow(3)], 2);
6821        assert_eq!(relative_rows[&DisplayRow(4)], 3);
6822        assert_eq!(relative_rows[&DisplayRow(5)], 4);
6823
6824        // works if cursor is after screen
6825        let relative_rows = window
6826            .update(cx, |editor, cx| {
6827                let snapshot = editor.snapshot(cx);
6828                element.calculate_relative_line_numbers(
6829                    &snapshot,
6830                    &(DisplayRow(0)..DisplayRow(3)),
6831                    Some(DisplayRow(6)),
6832                )
6833            })
6834            .unwrap();
6835        assert_eq!(relative_rows.len(), 3);
6836        assert_eq!(relative_rows[&DisplayRow(0)], 5);
6837        assert_eq!(relative_rows[&DisplayRow(1)], 4);
6838        assert_eq!(relative_rows[&DisplayRow(2)], 3);
6839    }
6840
6841    #[gpui::test]
6842    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
6843        init_test(cx, |_| {});
6844
6845        let window = cx.add_window(|cx| {
6846            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
6847            Editor::new(EditorMode::Full, buffer, None, true, cx)
6848        });
6849        let cx = &mut VisualTestContext::from_window(*window, cx);
6850        let editor = window.root(cx).unwrap();
6851        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6852
6853        window
6854            .update(cx, |editor, cx| {
6855                editor.cursor_shape = CursorShape::Block;
6856                editor.change_selections(None, cx, |s| {
6857                    s.select_ranges([
6858                        Point::new(0, 0)..Point::new(1, 0),
6859                        Point::new(3, 2)..Point::new(3, 3),
6860                        Point::new(5, 6)..Point::new(6, 0),
6861                    ]);
6862                });
6863            })
6864            .unwrap();
6865
6866        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6867            EditorElement::new(&editor, style)
6868        });
6869
6870        assert_eq!(state.selections.len(), 1);
6871        let local_selections = &state.selections[0].1;
6872        assert_eq!(local_selections.len(), 3);
6873        // moves cursor back one line
6874        assert_eq!(
6875            local_selections[0].head,
6876            DisplayPoint::new(DisplayRow(0), 6)
6877        );
6878        assert_eq!(
6879            local_selections[0].range,
6880            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
6881        );
6882
6883        // moves cursor back one column
6884        assert_eq!(
6885            local_selections[1].range,
6886            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
6887        );
6888        assert_eq!(
6889            local_selections[1].head,
6890            DisplayPoint::new(DisplayRow(3), 2)
6891        );
6892
6893        // leaves cursor on the max point
6894        assert_eq!(
6895            local_selections[2].range,
6896            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
6897        );
6898        assert_eq!(
6899            local_selections[2].head,
6900            DisplayPoint::new(DisplayRow(6), 0)
6901        );
6902
6903        // active lines does not include 1 (even though the range of the selection does)
6904        assert_eq!(
6905            state.active_rows.keys().cloned().collect::<Vec<_>>(),
6906            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
6907        );
6908
6909        // multi-buffer support
6910        // in DisplayPoint coordinates, this is what we're dealing with:
6911        //  0: [[file
6912        //  1:   header
6913        //  2:   section]]
6914        //  3: aaaaaa
6915        //  4: bbbbbb
6916        //  5: cccccc
6917        //  6:
6918        //  7: [[footer]]
6919        //  8: [[header]]
6920        //  9: ffffff
6921        // 10: gggggg
6922        // 11: hhhhhh
6923        // 12:
6924        // 13: [[footer]]
6925        // 14: [[file
6926        // 15:   header
6927        // 16:   section]]
6928        // 17: bbbbbb
6929        // 18: cccccc
6930        // 19: dddddd
6931        // 20: [[footer]]
6932        let window = cx.add_window(|cx| {
6933            let buffer = MultiBuffer::build_multi(
6934                [
6935                    (
6936                        &(sample_text(8, 6, 'a') + "\n"),
6937                        vec![
6938                            Point::new(0, 0)..Point::new(3, 0),
6939                            Point::new(4, 0)..Point::new(7, 0),
6940                        ],
6941                    ),
6942                    (
6943                        &(sample_text(8, 6, 'a') + "\n"),
6944                        vec![Point::new(1, 0)..Point::new(3, 0)],
6945                    ),
6946                ],
6947                cx,
6948            );
6949            Editor::new(EditorMode::Full, buffer, None, true, cx)
6950        });
6951        let editor = window.root(cx).unwrap();
6952        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6953        let _state = window.update(cx, |editor, cx| {
6954            editor.cursor_shape = CursorShape::Block;
6955            editor.change_selections(None, cx, |s| {
6956                s.select_display_ranges([
6957                    DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
6958                    DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
6959                ]);
6960            });
6961        });
6962
6963        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6964            EditorElement::new(&editor, style)
6965        });
6966        assert_eq!(state.selections.len(), 1);
6967        let local_selections = &state.selections[0].1;
6968        assert_eq!(local_selections.len(), 2);
6969
6970        // moves cursor on excerpt boundary back a line
6971        // and doesn't allow selection to bleed through
6972        assert_eq!(
6973            local_selections[0].range,
6974            DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
6975        );
6976        assert_eq!(
6977            local_selections[0].head,
6978            DisplayPoint::new(DisplayRow(6), 0)
6979        );
6980        // moves cursor on buffer boundary back two lines
6981        // and doesn't allow selection to bleed through
6982        assert_eq!(
6983            local_selections[1].range,
6984            DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
6985        );
6986        assert_eq!(
6987            local_selections[1].head,
6988            DisplayPoint::new(DisplayRow(12), 0)
6989        );
6990    }
6991
6992    #[gpui::test]
6993    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
6994        init_test(cx, |_| {});
6995
6996        let window = cx.add_window(|cx| {
6997            let buffer = MultiBuffer::build_simple("", cx);
6998            Editor::new(EditorMode::Full, buffer, None, true, cx)
6999        });
7000        let cx = &mut VisualTestContext::from_window(*window, cx);
7001        let editor = window.root(cx).unwrap();
7002        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
7003        window
7004            .update(cx, |editor, cx| {
7005                editor.set_placeholder_text("hello", cx);
7006                editor.insert_blocks(
7007                    [BlockProperties {
7008                        style: BlockStyle::Fixed,
7009                        placement: BlockPlacement::Above(Anchor::min()),
7010                        height: 3,
7011                        render: Arc::new(|cx| div().h(3. * cx.line_height()).into_any()),
7012                        priority: 0,
7013                    }],
7014                    None,
7015                    cx,
7016                );
7017
7018                // Blur the editor so that it displays placeholder text.
7019                cx.blur();
7020            })
7021            .unwrap();
7022
7023        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
7024            EditorElement::new(&editor, style)
7025        });
7026        assert_eq!(state.position_map.line_layouts.len(), 4);
7027        assert_eq!(
7028            state
7029                .line_numbers
7030                .iter()
7031                .map(Option::is_some)
7032                .collect::<Vec<_>>(),
7033            &[false, false, false, true]
7034        );
7035    }
7036
7037    #[gpui::test]
7038    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
7039        const TAB_SIZE: u32 = 4;
7040
7041        let input_text = "\t \t|\t| a b";
7042        let expected_invisibles = vec![
7043            Invisible::Tab {
7044                line_start_offset: 0,
7045                line_end_offset: TAB_SIZE as usize,
7046            },
7047            Invisible::Whitespace {
7048                line_offset: TAB_SIZE as usize,
7049            },
7050            Invisible::Tab {
7051                line_start_offset: TAB_SIZE as usize + 1,
7052                line_end_offset: TAB_SIZE as usize * 2,
7053            },
7054            Invisible::Tab {
7055                line_start_offset: TAB_SIZE as usize * 2 + 1,
7056                line_end_offset: TAB_SIZE as usize * 3,
7057            },
7058            Invisible::Whitespace {
7059                line_offset: TAB_SIZE as usize * 3 + 1,
7060            },
7061            Invisible::Whitespace {
7062                line_offset: TAB_SIZE as usize * 3 + 3,
7063            },
7064        ];
7065        assert_eq!(
7066            expected_invisibles.len(),
7067            input_text
7068                .chars()
7069                .filter(|initial_char| initial_char.is_whitespace())
7070                .count(),
7071            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
7072        );
7073
7074        for show_line_numbers in [true, false] {
7075            init_test(cx, |s| {
7076                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
7077                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
7078            });
7079
7080            let actual_invisibles = collect_invisibles_from_new_editor(
7081                cx,
7082                EditorMode::Full,
7083                input_text,
7084                px(500.0),
7085                show_line_numbers,
7086            );
7087
7088            assert_eq!(expected_invisibles, actual_invisibles);
7089        }
7090    }
7091
7092    #[gpui::test]
7093    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
7094        init_test(cx, |s| {
7095            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
7096            s.defaults.tab_size = NonZeroU32::new(4);
7097        });
7098
7099        for editor_mode_without_invisibles in [
7100            EditorMode::SingleLine { auto_width: false },
7101            EditorMode::AutoHeight { max_lines: 100 },
7102        ] {
7103            for show_line_numbers in [true, false] {
7104                let invisibles = collect_invisibles_from_new_editor(
7105                    cx,
7106                    editor_mode_without_invisibles,
7107                    "\t\t\t| | a b",
7108                    px(500.0),
7109                    show_line_numbers,
7110                );
7111                assert!(invisibles.is_empty(),
7112                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
7113            }
7114        }
7115    }
7116
7117    #[gpui::test]
7118    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
7119        let tab_size = 4;
7120        let input_text = "a\tbcd     ".repeat(9);
7121        let repeated_invisibles = [
7122            Invisible::Tab {
7123                line_start_offset: 1,
7124                line_end_offset: tab_size as usize,
7125            },
7126            Invisible::Whitespace {
7127                line_offset: tab_size as usize + 3,
7128            },
7129            Invisible::Whitespace {
7130                line_offset: tab_size as usize + 4,
7131            },
7132            Invisible::Whitespace {
7133                line_offset: tab_size as usize + 5,
7134            },
7135            Invisible::Whitespace {
7136                line_offset: tab_size as usize + 6,
7137            },
7138            Invisible::Whitespace {
7139                line_offset: tab_size as usize + 7,
7140            },
7141        ];
7142        let expected_invisibles = std::iter::once(repeated_invisibles)
7143            .cycle()
7144            .take(9)
7145            .flatten()
7146            .collect::<Vec<_>>();
7147        assert_eq!(
7148            expected_invisibles.len(),
7149            input_text
7150                .chars()
7151                .filter(|initial_char| initial_char.is_whitespace())
7152                .count(),
7153            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
7154        );
7155        info!("Expected invisibles: {expected_invisibles:?}");
7156
7157        init_test(cx, |_| {});
7158
7159        // Put the same string with repeating whitespace pattern into editors of various size,
7160        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
7161        let resize_step = 10.0;
7162        let mut editor_width = 200.0;
7163        while editor_width <= 1000.0 {
7164            for show_line_numbers in [true, false] {
7165                update_test_language_settings(cx, |s| {
7166                    s.defaults.tab_size = NonZeroU32::new(tab_size);
7167                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
7168                    s.defaults.preferred_line_length = Some(editor_width as u32);
7169                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
7170                });
7171
7172                let actual_invisibles = collect_invisibles_from_new_editor(
7173                    cx,
7174                    EditorMode::Full,
7175                    &input_text,
7176                    px(editor_width),
7177                    show_line_numbers,
7178                );
7179
7180                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
7181                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
7182                let mut i = 0;
7183                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
7184                    i = actual_index;
7185                    match expected_invisibles.get(i) {
7186                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
7187                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
7188                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
7189                            _ => {
7190                                panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
7191                            }
7192                        },
7193                        None => {
7194                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
7195                        }
7196                    }
7197                }
7198                let missing_expected_invisibles = &expected_invisibles[i + 1..];
7199                assert!(
7200                    missing_expected_invisibles.is_empty(),
7201                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
7202                );
7203
7204                editor_width += resize_step;
7205            }
7206        }
7207    }
7208
7209    #[gpui::test]
7210    fn test_inline_completion_popover_text(cx: &mut TestAppContext) {
7211        init_test(cx, |_| {});
7212
7213        // Test case 1: Simple insertion
7214        {
7215            let window = cx.add_window(|cx| {
7216                let buffer = MultiBuffer::build_simple("Hello, world!", cx);
7217                Editor::new(EditorMode::Full, buffer, None, true, cx)
7218            });
7219            let cx = &mut VisualTestContext::from_window(*window, cx);
7220
7221            window
7222                .update(cx, |editor, cx| {
7223                    let snapshot = editor.snapshot(cx);
7224                    let edit_range = snapshot.buffer_snapshot.anchor_after(Point::new(0, 6))
7225                        ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 6));
7226                    let edits = vec![(edit_range, " beautiful".to_string())];
7227
7228                    let (text, highlights) = inline_completion_popover_text(&snapshot, &edits, cx);
7229
7230                    assert_eq!(text, "Hello, beautiful world!");
7231                    assert_eq!(highlights.len(), 1);
7232                    assert_eq!(highlights[0].0, 6..16);
7233                    assert_eq!(
7234                        highlights[0].1.background_color,
7235                        Some(cx.theme().status().created_background)
7236                    );
7237                })
7238                .unwrap();
7239        }
7240
7241        // Test case 2: Replacement
7242        {
7243            let window = cx.add_window(|cx| {
7244                let buffer = MultiBuffer::build_simple("This is a test.", cx);
7245                Editor::new(EditorMode::Full, buffer, None, true, cx)
7246            });
7247            let cx = &mut VisualTestContext::from_window(*window, cx);
7248
7249            window
7250                .update(cx, |editor, cx| {
7251                    let snapshot = editor.snapshot(cx);
7252                    let edits = vec![(
7253                        snapshot.buffer_snapshot.anchor_after(Point::new(0, 0))
7254                            ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 4)),
7255                        "That".to_string(),
7256                    )];
7257
7258                    let (text, highlights) = inline_completion_popover_text(&snapshot, &edits, cx);
7259
7260                    assert_eq!(text, "That is a test.");
7261                    assert_eq!(highlights.len(), 1);
7262                    assert_eq!(highlights[0].0, 0..4);
7263                    assert_eq!(
7264                        highlights[0].1.background_color,
7265                        Some(cx.theme().status().created_background)
7266                    );
7267                })
7268                .unwrap();
7269        }
7270
7271        // Test case 3: Multiple edits
7272        {
7273            let window = cx.add_window(|cx| {
7274                let buffer = MultiBuffer::build_simple("Hello, world!", cx);
7275                Editor::new(EditorMode::Full, buffer, None, true, cx)
7276            });
7277            let cx = &mut VisualTestContext::from_window(*window, cx);
7278
7279            window
7280                .update(cx, |editor, cx| {
7281                    let snapshot = editor.snapshot(cx);
7282                    let edits = vec![
7283                        (
7284                            snapshot.buffer_snapshot.anchor_after(Point::new(0, 0))
7285                                ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 5)),
7286                            "Greetings".into(),
7287                        ),
7288                        (
7289                            snapshot.buffer_snapshot.anchor_after(Point::new(0, 12))
7290                                ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 12)),
7291                            " and universe".into(),
7292                        ),
7293                    ];
7294
7295                    let (text, highlights) = inline_completion_popover_text(&snapshot, &edits, cx);
7296
7297                    assert_eq!(text, "Greetings, world and universe!");
7298                    assert_eq!(highlights.len(), 2);
7299                    assert_eq!(highlights[0].0, 0..9);
7300                    assert_eq!(highlights[1].0, 16..29);
7301                    assert_eq!(
7302                        highlights[0].1.background_color,
7303                        Some(cx.theme().status().created_background)
7304                    );
7305                    assert_eq!(
7306                        highlights[1].1.background_color,
7307                        Some(cx.theme().status().created_background)
7308                    );
7309                })
7310                .unwrap();
7311        }
7312
7313        // Test case 4: Multiple lines with edits
7314        {
7315            let window = cx.add_window(|cx| {
7316                let buffer = MultiBuffer::build_simple(
7317                    "First line\nSecond line\nThird line\nFourth line",
7318                    cx,
7319                );
7320                Editor::new(EditorMode::Full, buffer, None, true, cx)
7321            });
7322            let cx = &mut VisualTestContext::from_window(*window, cx);
7323
7324            window
7325                .update(cx, |editor, cx| {
7326                    let snapshot = editor.snapshot(cx);
7327                    let edits = vec![
7328                        (
7329                            snapshot.buffer_snapshot.anchor_before(Point::new(1, 7))
7330                                ..snapshot.buffer_snapshot.anchor_before(Point::new(1, 11)),
7331                            "modified".to_string(),
7332                        ),
7333                        (
7334                            snapshot.buffer_snapshot.anchor_before(Point::new(2, 0))
7335                                ..snapshot.buffer_snapshot.anchor_before(Point::new(2, 10)),
7336                            "New third line".to_string(),
7337                        ),
7338                        (
7339                            snapshot.buffer_snapshot.anchor_before(Point::new(3, 6))
7340                                ..snapshot.buffer_snapshot.anchor_before(Point::new(3, 6)),
7341                            " updated".to_string(),
7342                        ),
7343                    ];
7344
7345                    let (text, highlights) = inline_completion_popover_text(&snapshot, &edits, cx);
7346
7347                    assert_eq!(text, "Second modified\nNew third line\nFourth updated line");
7348                    assert_eq!(highlights.len(), 3);
7349                    assert_eq!(highlights[0].0, 7..15); // "modified"
7350                    assert_eq!(highlights[1].0, 16..30); // "New third line"
7351                    assert_eq!(highlights[2].0, 37..45); // " updated"
7352
7353                    for highlight in &highlights {
7354                        assert_eq!(
7355                            highlight.1.background_color,
7356                            Some(cx.theme().status().created_background)
7357                        );
7358                    }
7359                })
7360                .unwrap();
7361        }
7362    }
7363
7364    fn collect_invisibles_from_new_editor(
7365        cx: &mut TestAppContext,
7366        editor_mode: EditorMode,
7367        input_text: &str,
7368        editor_width: Pixels,
7369        show_line_numbers: bool,
7370    ) -> Vec<Invisible> {
7371        info!(
7372            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
7373            editor_width.0
7374        );
7375        let window = cx.add_window(|cx| {
7376            let buffer = MultiBuffer::build_simple(input_text, cx);
7377            Editor::new(editor_mode, buffer, None, true, cx)
7378        });
7379        let cx = &mut VisualTestContext::from_window(*window, cx);
7380        let editor = window.root(cx).unwrap();
7381
7382        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
7383        window
7384            .update(cx, |editor, cx| {
7385                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
7386                editor.set_wrap_width(Some(editor_width), cx);
7387                editor.set_show_line_numbers(show_line_numbers, cx);
7388            })
7389            .unwrap();
7390        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
7391            EditorElement::new(&editor, style)
7392        });
7393        state
7394            .position_map
7395            .line_layouts
7396            .iter()
7397            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
7398            .cloned()
7399            .collect()
7400    }
7401}