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