element.rs

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