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