element.rs

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