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 = settings.line_width.clamp(1, 10);
2795            let mut line_indicator_width = 0.;
2796            if let Some(color) = line_color {
2797                cx.paint_quad(fill(
2798                    Bounds {
2799                        origin: indent_guide.origin,
2800                        size: size(px(requested_line_width as f32), indent_guide.length),
2801                    },
2802                    color,
2803                ));
2804                line_indicator_width = requested_line_width as f32;
2805            }
2806
2807            if let Some(color) = background_color {
2808                let width = indent_guide.single_indent_width - px(line_indicator_width);
2809                cx.paint_quad(fill(
2810                    Bounds {
2811                        origin: point(
2812                            indent_guide.origin.x + px(line_indicator_width),
2813                            indent_guide.origin.y,
2814                        ),
2815                        size: size(width, indent_guide.length),
2816                    },
2817                    color,
2818                ));
2819            }
2820        }
2821    }
2822
2823    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2824        let line_height = layout.position_map.line_height;
2825        let scroll_position = layout.position_map.snapshot.scroll_position();
2826        let scroll_top = scroll_position.y * line_height;
2827
2828        cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
2829
2830        for (ix, line) in layout.line_numbers.iter().enumerate() {
2831            if let Some(line) = line {
2832                let line_origin = layout.gutter_hitbox.origin
2833                    + point(
2834                        layout.gutter_hitbox.size.width
2835                            - line.width
2836                            - layout.gutter_dimensions.right_padding,
2837                        ix as f32 * line_height - (scroll_top % line_height),
2838                    );
2839
2840                line.paint(line_origin, line_height, cx).log_err();
2841            }
2842        }
2843    }
2844
2845    fn paint_diff_hunks(layout: &EditorLayout, cx: &mut WindowContext) {
2846        if layout.display_hunks.is_empty() {
2847            return;
2848        }
2849
2850        let line_height = layout.position_map.line_height;
2851        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2852            for (hunk, hitbox) in &layout.display_hunks {
2853                let hunk_to_paint = match hunk {
2854                    DisplayDiffHunk::Folded { .. } => {
2855                        let hunk_bounds = Self::diff_hunk_bounds(
2856                            &layout.position_map.snapshot,
2857                            line_height,
2858                            layout.gutter_hitbox.bounds,
2859                            &hunk,
2860                        );
2861                        Some((
2862                            hunk_bounds,
2863                            cx.theme().status().modified,
2864                            Corners::all(1. * line_height),
2865                        ))
2866                    }
2867                    DisplayDiffHunk::Unfolded { status, .. } => {
2868                        hitbox.as_ref().map(|hunk_hitbox| match status {
2869                            DiffHunkStatus::Added => (
2870                                hunk_hitbox.bounds,
2871                                cx.theme().status().created,
2872                                Corners::all(0.05 * line_height),
2873                            ),
2874                            DiffHunkStatus::Modified => (
2875                                hunk_hitbox.bounds,
2876                                cx.theme().status().modified,
2877                                Corners::all(0.05 * line_height),
2878                            ),
2879                            DiffHunkStatus::Removed => (
2880                                Bounds::new(
2881                                    point(
2882                                        hunk_hitbox.origin.x - hunk_hitbox.size.width,
2883                                        hunk_hitbox.origin.y,
2884                                    ),
2885                                    size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
2886                                ),
2887                                cx.theme().status().deleted,
2888                                Corners::all(1. * line_height),
2889                            ),
2890                        })
2891                    }
2892                };
2893
2894                if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
2895                    cx.paint_quad(quad(
2896                        hunk_bounds,
2897                        corner_radii,
2898                        background_color,
2899                        Edges::default(),
2900                        transparent_black(),
2901                    ));
2902                }
2903            }
2904        });
2905    }
2906
2907    fn diff_hunk_bounds(
2908        snapshot: &EditorSnapshot,
2909        line_height: Pixels,
2910        bounds: Bounds<Pixels>,
2911        hunk: &DisplayDiffHunk,
2912    ) -> Bounds<Pixels> {
2913        let scroll_position = snapshot.scroll_position();
2914        let scroll_top = scroll_position.y * line_height;
2915
2916        match hunk {
2917            DisplayDiffHunk::Folded { display_row, .. } => {
2918                let start_y = display_row.as_f32() * line_height - scroll_top;
2919                let end_y = start_y + line_height;
2920
2921                let width = 0.275 * line_height;
2922                let highlight_origin = bounds.origin + point(px(0.), start_y);
2923                let highlight_size = size(width, end_y - start_y);
2924                Bounds::new(highlight_origin, highlight_size)
2925            }
2926            DisplayDiffHunk::Unfolded {
2927                display_row_range,
2928                status,
2929                ..
2930            } => match status {
2931                DiffHunkStatus::Added | DiffHunkStatus::Modified => {
2932                    let start_row = display_row_range.start;
2933                    let end_row = display_row_range.end;
2934                    // If we're in a multibuffer, row range span might include an
2935                    // excerpt header, so if we were to draw the marker straight away,
2936                    // the hunk might include the rows of that header.
2937                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
2938                    // Instead, we simply check whether the range we're dealing with includes
2939                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
2940                    let end_row_in_current_excerpt = snapshot
2941                        .blocks_in_range(start_row..end_row)
2942                        .find_map(|(start_row, block)| {
2943                            if matches!(block, TransformBlock::ExcerptHeader { .. }) {
2944                                Some(start_row)
2945                            } else {
2946                                None
2947                            }
2948                        })
2949                        .unwrap_or(end_row);
2950
2951                    let start_y = start_row.as_f32() * line_height - scroll_top;
2952                    let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
2953
2954                    let width = 0.275 * line_height;
2955                    let highlight_origin = bounds.origin + point(px(0.), start_y);
2956                    let highlight_size = size(width, end_y - start_y);
2957                    Bounds::new(highlight_origin, highlight_size)
2958                }
2959                DiffHunkStatus::Removed => {
2960                    let row = display_row_range.start;
2961
2962                    let offset = line_height / 2.;
2963                    let start_y = row.as_f32() * line_height - offset - scroll_top;
2964                    let end_y = start_y + line_height;
2965
2966                    let width = 0.35 * line_height;
2967                    let highlight_origin = bounds.origin + point(px(0.), start_y);
2968                    let highlight_size = size(width, end_y - start_y);
2969                    Bounds::new(highlight_origin, highlight_size)
2970                }
2971            },
2972        }
2973    }
2974
2975    fn paint_gutter_indicators(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2976        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2977            cx.with_element_namespace("gutter_fold_toggles", |cx| {
2978                for fold_indicator in layout.gutter_fold_toggles.iter_mut().flatten() {
2979                    fold_indicator.paint(cx);
2980                }
2981            });
2982
2983            for test_indicators in layout.test_indicators.iter_mut() {
2984                test_indicators.paint(cx);
2985            }
2986
2987            if let Some(indicator) = layout.code_actions_indicator.as_mut() {
2988                indicator.paint(cx);
2989            }
2990        });
2991    }
2992
2993    fn paint_gutter_highlights(&self, layout: &EditorLayout, cx: &mut WindowContext) {
2994        for (_, hunk_hitbox) in &layout.display_hunks {
2995            if let Some(hunk_hitbox) = hunk_hitbox {
2996                cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
2997            }
2998        }
2999
3000        let show_git_gutter = layout
3001            .position_map
3002            .snapshot
3003            .show_git_diff_gutter
3004            .unwrap_or_else(|| {
3005                matches!(
3006                    ProjectSettings::get_global(cx).git.git_gutter,
3007                    Some(GitGutterSetting::TrackedFiles)
3008                )
3009            });
3010        if show_git_gutter {
3011            Self::paint_diff_hunks(layout, cx)
3012        }
3013
3014        let highlight_width = 0.275 * layout.position_map.line_height;
3015        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
3016        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3017            for (range, color) in &layout.highlighted_gutter_ranges {
3018                let start_row = if range.start.row() < layout.visible_display_row_range.start {
3019                    layout.visible_display_row_range.start - DisplayRow(1)
3020                } else {
3021                    range.start.row()
3022                };
3023                let end_row = if range.end.row() > layout.visible_display_row_range.end {
3024                    layout.visible_display_row_range.end + DisplayRow(1)
3025                } else {
3026                    range.end.row()
3027                };
3028
3029                let start_y = layout.gutter_hitbox.top()
3030                    + start_row.0 as f32 * layout.position_map.line_height
3031                    - layout.position_map.scroll_pixel_position.y;
3032                let end_y = layout.gutter_hitbox.top()
3033                    + (end_row.0 + 1) as f32 * layout.position_map.line_height
3034                    - layout.position_map.scroll_pixel_position.y;
3035                let bounds = Bounds::from_corners(
3036                    point(layout.gutter_hitbox.left(), start_y),
3037                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
3038                );
3039                cx.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
3040            }
3041        });
3042    }
3043
3044    fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3045        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
3046            return;
3047        };
3048
3049        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3050            for mut blame_element in blamed_display_rows.into_iter() {
3051                blame_element.paint(cx);
3052            }
3053        })
3054    }
3055
3056    fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3057        cx.with_content_mask(
3058            Some(ContentMask {
3059                bounds: layout.text_hitbox.bounds,
3060            }),
3061            |cx| {
3062                let cursor_style = if self
3063                    .editor
3064                    .read(cx)
3065                    .hovered_link_state
3066                    .as_ref()
3067                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
3068                {
3069                    CursorStyle::PointingHand
3070                } else {
3071                    CursorStyle::IBeam
3072                };
3073                cx.set_cursor_style(cursor_style, &layout.text_hitbox);
3074
3075                let invisible_display_ranges = self.paint_highlights(layout, cx);
3076                self.paint_lines(&invisible_display_ranges, layout, cx);
3077                self.paint_redactions(layout, cx);
3078                self.paint_cursors(layout, cx);
3079                self.paint_inline_blame(layout, cx);
3080                cx.with_element_namespace("crease_trailers", |cx| {
3081                    for trailer in layout.crease_trailers.iter_mut().flatten() {
3082                        trailer.element.paint(cx);
3083                    }
3084                });
3085            },
3086        )
3087    }
3088
3089    fn paint_highlights(
3090        &mut self,
3091        layout: &mut EditorLayout,
3092        cx: &mut WindowContext,
3093    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
3094        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3095            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
3096            let line_end_overshoot = 0.15 * layout.position_map.line_height;
3097            for (range, color) in &layout.highlighted_ranges {
3098                self.paint_highlighted_range(
3099                    range.clone(),
3100                    *color,
3101                    Pixels::ZERO,
3102                    line_end_overshoot,
3103                    layout,
3104                    cx,
3105                );
3106            }
3107
3108            let corner_radius = 0.15 * layout.position_map.line_height;
3109
3110            for (player_color, selections) in &layout.selections {
3111                for selection in selections.into_iter() {
3112                    self.paint_highlighted_range(
3113                        selection.range.clone(),
3114                        player_color.selection,
3115                        corner_radius,
3116                        corner_radius * 2.,
3117                        layout,
3118                        cx,
3119                    );
3120
3121                    if selection.is_local && !selection.range.is_empty() {
3122                        invisible_display_ranges.push(selection.range.clone());
3123                    }
3124                }
3125            }
3126            invisible_display_ranges
3127        })
3128    }
3129
3130    fn paint_lines(
3131        &mut self,
3132        invisible_display_ranges: &[Range<DisplayPoint>],
3133        layout: &mut EditorLayout,
3134        cx: &mut WindowContext,
3135    ) {
3136        let whitespace_setting = self
3137            .editor
3138            .read(cx)
3139            .buffer
3140            .read(cx)
3141            .settings_at(0, cx)
3142            .show_whitespaces;
3143
3144        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
3145            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
3146            line_with_invisibles.draw(
3147                layout,
3148                row,
3149                layout.content_origin,
3150                whitespace_setting,
3151                invisible_display_ranges,
3152                cx,
3153            )
3154        }
3155
3156        for line_element in &mut layout.line_elements {
3157            line_element.paint(cx);
3158        }
3159    }
3160
3161    fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3162        if layout.redacted_ranges.is_empty() {
3163            return;
3164        }
3165
3166        let line_end_overshoot = layout.line_end_overshoot();
3167
3168        // A softer than perfect black
3169        let redaction_color = gpui::rgb(0x0e1111);
3170
3171        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3172            for range in layout.redacted_ranges.iter() {
3173                self.paint_highlighted_range(
3174                    range.clone(),
3175                    redaction_color.into(),
3176                    Pixels::ZERO,
3177                    line_end_overshoot,
3178                    layout,
3179                    cx,
3180                );
3181            }
3182        });
3183    }
3184
3185    fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3186        for cursor in &mut layout.visible_cursors {
3187            cursor.paint(layout.content_origin, cx);
3188        }
3189    }
3190
3191    fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3192        let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
3193            return;
3194        };
3195
3196        let thumb_bounds = scrollbar_layout.thumb_bounds();
3197        if scrollbar_layout.visible {
3198            cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
3199                cx.paint_quad(quad(
3200                    scrollbar_layout.hitbox.bounds,
3201                    Corners::default(),
3202                    cx.theme().colors().scrollbar_track_background,
3203                    Edges {
3204                        top: Pixels::ZERO,
3205                        right: Pixels::ZERO,
3206                        bottom: Pixels::ZERO,
3207                        left: ScrollbarLayout::BORDER_WIDTH,
3208                    },
3209                    cx.theme().colors().scrollbar_track_border,
3210                ));
3211
3212                let fast_markers =
3213                    self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
3214                // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
3215                self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
3216
3217                let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
3218                for marker in markers.iter().chain(&fast_markers) {
3219                    let mut marker = marker.clone();
3220                    marker.bounds.origin += scrollbar_layout.hitbox.origin;
3221                    cx.paint_quad(marker);
3222                }
3223
3224                cx.paint_quad(quad(
3225                    thumb_bounds,
3226                    Corners::default(),
3227                    cx.theme().colors().scrollbar_thumb_background,
3228                    Edges {
3229                        top: Pixels::ZERO,
3230                        right: Pixels::ZERO,
3231                        bottom: Pixels::ZERO,
3232                        left: ScrollbarLayout::BORDER_WIDTH,
3233                    },
3234                    cx.theme().colors().scrollbar_thumb_border,
3235                ));
3236            });
3237        }
3238
3239        cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
3240
3241        let row_height = scrollbar_layout.row_height;
3242        let row_range = scrollbar_layout.visible_row_range.clone();
3243
3244        cx.on_mouse_event({
3245            let editor = self.editor.clone();
3246            let hitbox = scrollbar_layout.hitbox.clone();
3247            let mut mouse_position = cx.mouse_position();
3248            move |event: &MouseMoveEvent, phase, cx| {
3249                if phase == DispatchPhase::Capture {
3250                    return;
3251                }
3252
3253                editor.update(cx, |editor, cx| {
3254                    if event.pressed_button == Some(MouseButton::Left)
3255                        && editor.scroll_manager.is_dragging_scrollbar()
3256                    {
3257                        let y = mouse_position.y;
3258                        let new_y = event.position.y;
3259                        if (hitbox.top()..hitbox.bottom()).contains(&y) {
3260                            let mut position = editor.scroll_position(cx);
3261                            position.y += (new_y - y) / row_height;
3262                            if position.y < 0.0 {
3263                                position.y = 0.0;
3264                            }
3265                            editor.set_scroll_position(position, cx);
3266                        }
3267
3268                        cx.stop_propagation();
3269                    } else {
3270                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3271                        if hitbox.is_hovered(cx) {
3272                            editor.scroll_manager.show_scrollbar(cx);
3273                        }
3274                    }
3275                    mouse_position = event.position;
3276                })
3277            }
3278        });
3279
3280        if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
3281            cx.on_mouse_event({
3282                let editor = self.editor.clone();
3283                move |_: &MouseUpEvent, phase, cx| {
3284                    if phase == DispatchPhase::Capture {
3285                        return;
3286                    }
3287
3288                    editor.update(cx, |editor, cx| {
3289                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3290                        cx.stop_propagation();
3291                    });
3292                }
3293            });
3294        } else {
3295            cx.on_mouse_event({
3296                let editor = self.editor.clone();
3297                let hitbox = scrollbar_layout.hitbox.clone();
3298                move |event: &MouseDownEvent, phase, cx| {
3299                    if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
3300                        return;
3301                    }
3302
3303                    editor.update(cx, |editor, cx| {
3304                        editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
3305
3306                        let y = event.position.y;
3307                        if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
3308                            let center_row = ((y - hitbox.top()) / row_height).round() as u32;
3309                            let top_row = center_row
3310                                .saturating_sub((row_range.end - row_range.start) as u32 / 2);
3311                            let mut position = editor.scroll_position(cx);
3312                            position.y = top_row as f32;
3313                            editor.set_scroll_position(position, cx);
3314                        } else {
3315                            editor.scroll_manager.show_scrollbar(cx);
3316                        }
3317
3318                        cx.stop_propagation();
3319                    });
3320                }
3321            });
3322        }
3323    }
3324
3325    fn collect_fast_scrollbar_markers(
3326        &self,
3327        layout: &EditorLayout,
3328        scrollbar_layout: &ScrollbarLayout,
3329        cx: &mut WindowContext,
3330    ) -> Vec<PaintQuad> {
3331        const LIMIT: usize = 100;
3332        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
3333            return vec![];
3334        }
3335        let cursor_ranges = layout
3336            .cursors
3337            .iter()
3338            .map(|(point, color)| ColoredRange {
3339                start: point.row(),
3340                end: point.row(),
3341                color: *color,
3342            })
3343            .collect_vec();
3344        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
3345    }
3346
3347    fn refresh_slow_scrollbar_markers(
3348        &self,
3349        layout: &EditorLayout,
3350        scrollbar_layout: &ScrollbarLayout,
3351        cx: &mut WindowContext,
3352    ) {
3353        self.editor.update(cx, |editor, cx| {
3354            if !editor.is_singleton(cx)
3355                || !editor
3356                    .scrollbar_marker_state
3357                    .should_refresh(scrollbar_layout.hitbox.size)
3358            {
3359                return;
3360            }
3361
3362            let scrollbar_layout = scrollbar_layout.clone();
3363            let background_highlights = editor.background_highlights.clone();
3364            let snapshot = layout.position_map.snapshot.clone();
3365            let theme = cx.theme().clone();
3366            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
3367
3368            editor.scrollbar_marker_state.dirty = false;
3369            editor.scrollbar_marker_state.pending_refresh =
3370                Some(cx.spawn(|editor, mut cx| async move {
3371                    let scrollbar_size = scrollbar_layout.hitbox.size;
3372                    let scrollbar_markers = cx
3373                        .background_executor()
3374                        .spawn(async move {
3375                            let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
3376                            let mut marker_quads = Vec::new();
3377                            if scrollbar_settings.git_diff {
3378                                let marker_row_ranges = snapshot
3379                                    .buffer_snapshot
3380                                    .git_diff_hunks_in_range(
3381                                        MultiBufferRow::MIN..MultiBufferRow::MAX,
3382                                    )
3383                                    .map(|hunk| {
3384                                        let start_display_row =
3385                                            MultiBufferPoint::new(hunk.associated_range.start.0, 0)
3386                                                .to_display_point(&snapshot.display_snapshot)
3387                                                .row();
3388                                        let mut end_display_row =
3389                                            MultiBufferPoint::new(hunk.associated_range.end.0, 0)
3390                                                .to_display_point(&snapshot.display_snapshot)
3391                                                .row();
3392                                        if end_display_row != start_display_row {
3393                                            end_display_row.0 -= 1;
3394                                        }
3395                                        let color = match hunk_status(&hunk) {
3396                                            DiffHunkStatus::Added => theme.status().created,
3397                                            DiffHunkStatus::Modified => theme.status().modified,
3398                                            DiffHunkStatus::Removed => theme.status().deleted,
3399                                        };
3400                                        ColoredRange {
3401                                            start: start_display_row,
3402                                            end: end_display_row,
3403                                            color,
3404                                        }
3405                                    });
3406
3407                                marker_quads.extend(
3408                                    scrollbar_layout
3409                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
3410                                );
3411                            }
3412
3413                            for (background_highlight_id, (_, background_ranges)) in
3414                                background_highlights.iter()
3415                            {
3416                                let is_search_highlights = *background_highlight_id
3417                                    == TypeId::of::<BufferSearchHighlights>();
3418                                let is_symbol_occurrences = *background_highlight_id
3419                                    == TypeId::of::<DocumentHighlightRead>()
3420                                    || *background_highlight_id
3421                                        == TypeId::of::<DocumentHighlightWrite>();
3422                                if (is_search_highlights && scrollbar_settings.search_results)
3423                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
3424                                {
3425                                    let mut color = theme.status().info;
3426                                    if is_symbol_occurrences {
3427                                        color.fade_out(0.5);
3428                                    }
3429                                    let marker_row_ranges =
3430                                        background_ranges.into_iter().map(|range| {
3431                                            let display_start = range
3432                                                .start
3433                                                .to_display_point(&snapshot.display_snapshot);
3434                                            let display_end = range
3435                                                .end
3436                                                .to_display_point(&snapshot.display_snapshot);
3437                                            ColoredRange {
3438                                                start: display_start.row(),
3439                                                end: display_end.row(),
3440                                                color,
3441                                            }
3442                                        });
3443                                    marker_quads.extend(
3444                                        scrollbar_layout
3445                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
3446                                    );
3447                                }
3448                            }
3449
3450                            if scrollbar_settings.diagnostics {
3451                                let diagnostics = snapshot
3452                                    .buffer_snapshot
3453                                    .diagnostics_in_range::<_, Point>(
3454                                        Point::zero()..max_point,
3455                                        false,
3456                                    )
3457                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
3458                                    .sorted_by_key(|diagnostic| {
3459                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
3460                                    });
3461
3462                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
3463                                    let start_display = diagnostic
3464                                        .range
3465                                        .start
3466                                        .to_display_point(&snapshot.display_snapshot);
3467                                    let end_display = diagnostic
3468                                        .range
3469                                        .end
3470                                        .to_display_point(&snapshot.display_snapshot);
3471                                    let color = match diagnostic.diagnostic.severity {
3472                                        DiagnosticSeverity::ERROR => theme.status().error,
3473                                        DiagnosticSeverity::WARNING => theme.status().warning,
3474                                        DiagnosticSeverity::INFORMATION => theme.status().info,
3475                                        _ => theme.status().hint,
3476                                    };
3477                                    ColoredRange {
3478                                        start: start_display.row(),
3479                                        end: end_display.row(),
3480                                        color,
3481                                    }
3482                                });
3483                                marker_quads.extend(
3484                                    scrollbar_layout
3485                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
3486                                );
3487                            }
3488
3489                            Arc::from(marker_quads)
3490                        })
3491                        .await;
3492
3493                    editor.update(&mut cx, |editor, cx| {
3494                        editor.scrollbar_marker_state.markers = scrollbar_markers;
3495                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
3496                        editor.scrollbar_marker_state.pending_refresh = None;
3497                        cx.notify();
3498                    })?;
3499
3500                    Ok(())
3501                }));
3502        });
3503    }
3504
3505    #[allow(clippy::too_many_arguments)]
3506    fn paint_highlighted_range(
3507        &self,
3508        range: Range<DisplayPoint>,
3509        color: Hsla,
3510        corner_radius: Pixels,
3511        line_end_overshoot: Pixels,
3512        layout: &EditorLayout,
3513        cx: &mut WindowContext,
3514    ) {
3515        let start_row = layout.visible_display_row_range.start;
3516        let end_row = layout.visible_display_row_range.end;
3517        if range.start != range.end {
3518            let row_range = if range.end.column() == 0 {
3519                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3520            } else {
3521                cmp::max(range.start.row(), start_row)
3522                    ..cmp::min(range.end.row().next_row(), end_row)
3523            };
3524
3525            let highlighted_range = HighlightedRange {
3526                color,
3527                line_height: layout.position_map.line_height,
3528                corner_radius,
3529                start_y: layout.content_origin.y
3530                    + row_range.start.as_f32() * layout.position_map.line_height
3531                    - layout.position_map.scroll_pixel_position.y,
3532                lines: row_range
3533                    .iter_rows()
3534                    .map(|row| {
3535                        let line_layout =
3536                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
3537                        HighlightedRangeLine {
3538                            start_x: if row == range.start.row() {
3539                                layout.content_origin.x
3540                                    + line_layout.x_for_index(range.start.column() as usize)
3541                                    - layout.position_map.scroll_pixel_position.x
3542                            } else {
3543                                layout.content_origin.x
3544                                    - layout.position_map.scroll_pixel_position.x
3545                            },
3546                            end_x: if row == range.end.row() {
3547                                layout.content_origin.x
3548                                    + line_layout.x_for_index(range.end.column() as usize)
3549                                    - layout.position_map.scroll_pixel_position.x
3550                            } else {
3551                                layout.content_origin.x + line_layout.width + line_end_overshoot
3552                                    - layout.position_map.scroll_pixel_position.x
3553                            },
3554                        }
3555                    })
3556                    .collect(),
3557            };
3558
3559            highlighted_range.paint(layout.text_hitbox.bounds, cx);
3560        }
3561    }
3562
3563    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3564        if let Some(mut inline_blame) = layout.inline_blame.take() {
3565            cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3566                inline_blame.paint(cx);
3567            })
3568        }
3569    }
3570
3571    fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3572        for mut block in layout.blocks.drain(..) {
3573            block.element.paint(cx);
3574        }
3575    }
3576
3577    fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3578        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
3579            mouse_context_menu.paint(cx);
3580        }
3581    }
3582
3583    fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3584        cx.on_mouse_event({
3585            let position_map = layout.position_map.clone();
3586            let editor = self.editor.clone();
3587            let hitbox = layout.hitbox.clone();
3588            let mut delta = ScrollDelta::default();
3589
3590            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
3591            // accidentally turn off their scrolling.
3592            let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
3593
3594            move |event: &ScrollWheelEvent, phase, cx| {
3595                if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
3596                    delta = delta.coalesce(event.delta);
3597                    editor.update(cx, |editor, cx| {
3598                        let position_map: &PositionMap = &position_map;
3599
3600                        let line_height = position_map.line_height;
3601                        let max_glyph_width = position_map.em_width;
3602                        let (delta, axis) = match delta {
3603                            gpui::ScrollDelta::Pixels(mut pixels) => {
3604                                //Trackpad
3605                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
3606                                (pixels, axis)
3607                            }
3608
3609                            gpui::ScrollDelta::Lines(lines) => {
3610                                //Not trackpad
3611                                let pixels =
3612                                    point(lines.x * max_glyph_width, lines.y * line_height);
3613                                (pixels, None)
3614                            }
3615                        };
3616
3617                        let current_scroll_position = position_map.snapshot.scroll_position();
3618                        let x = (current_scroll_position.x * max_glyph_width
3619                            - (delta.x * scroll_sensitivity))
3620                            / max_glyph_width;
3621                        let y = (current_scroll_position.y * line_height
3622                            - (delta.y * scroll_sensitivity))
3623                            / line_height;
3624                        let mut scroll_position =
3625                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
3626                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
3627                        if forbid_vertical_scroll {
3628                            scroll_position.y = current_scroll_position.y;
3629                            if scroll_position == current_scroll_position {
3630                                return;
3631                            }
3632                        }
3633                        editor.scroll(scroll_position, axis, cx);
3634                        cx.stop_propagation();
3635                    });
3636                }
3637            }
3638        });
3639    }
3640
3641    fn paint_mouse_listeners(
3642        &mut self,
3643        layout: &EditorLayout,
3644        hovered_hunk: Option<HunkToExpand>,
3645        cx: &mut WindowContext,
3646    ) {
3647        self.paint_scroll_wheel_listener(layout, cx);
3648
3649        cx.on_mouse_event({
3650            let position_map = layout.position_map.clone();
3651            let editor = self.editor.clone();
3652            let text_hitbox = layout.text_hitbox.clone();
3653            let gutter_hitbox = layout.gutter_hitbox.clone();
3654
3655            move |event: &MouseDownEvent, phase, cx| {
3656                if phase == DispatchPhase::Bubble {
3657                    match event.button {
3658                        MouseButton::Left => editor.update(cx, |editor, cx| {
3659                            Self::mouse_left_down(
3660                                editor,
3661                                event,
3662                                hovered_hunk.as_ref(),
3663                                &position_map,
3664                                &text_hitbox,
3665                                &gutter_hitbox,
3666                                cx,
3667                            );
3668                        }),
3669                        MouseButton::Right => editor.update(cx, |editor, cx| {
3670                            Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
3671                        }),
3672                        MouseButton::Middle => editor.update(cx, |editor, cx| {
3673                            Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
3674                        }),
3675                        _ => {}
3676                    };
3677                }
3678            }
3679        });
3680
3681        cx.on_mouse_event({
3682            let editor = self.editor.clone();
3683            let position_map = layout.position_map.clone();
3684            let text_hitbox = layout.text_hitbox.clone();
3685
3686            move |event: &MouseUpEvent, phase, cx| {
3687                if phase == DispatchPhase::Bubble {
3688                    editor.update(cx, |editor, cx| {
3689                        Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
3690                    });
3691                }
3692            }
3693        });
3694        cx.on_mouse_event({
3695            let position_map = layout.position_map.clone();
3696            let editor = self.editor.clone();
3697            let text_hitbox = layout.text_hitbox.clone();
3698            let gutter_hitbox = layout.gutter_hitbox.clone();
3699
3700            move |event: &MouseMoveEvent, phase, cx| {
3701                if phase == DispatchPhase::Bubble {
3702                    editor.update(cx, |editor, cx| {
3703                        if event.pressed_button == Some(MouseButton::Left)
3704                            || event.pressed_button == Some(MouseButton::Middle)
3705                        {
3706                            Self::mouse_dragged(
3707                                editor,
3708                                event,
3709                                &position_map,
3710                                text_hitbox.bounds,
3711                                cx,
3712                            )
3713                        }
3714
3715                        Self::mouse_moved(
3716                            editor,
3717                            event,
3718                            &position_map,
3719                            &text_hitbox,
3720                            &gutter_hitbox,
3721                            cx,
3722                        )
3723                    });
3724                }
3725            }
3726        });
3727    }
3728
3729    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
3730        bounds.upper_right().x - self.style.scrollbar_width
3731    }
3732
3733    fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
3734        let style = &self.style;
3735        let font_size = style.text.font_size.to_pixels(cx.rem_size());
3736        let layout = cx
3737            .text_system()
3738            .shape_line(
3739                SharedString::from(" ".repeat(column)),
3740                font_size,
3741                &[TextRun {
3742                    len: column,
3743                    font: style.text.font(),
3744                    color: Hsla::default(),
3745                    background_color: None,
3746                    underline: None,
3747                    strikethrough: None,
3748                }],
3749            )
3750            .unwrap();
3751
3752        layout.width
3753    }
3754
3755    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
3756        let digit_count = snapshot
3757            .max_buffer_row()
3758            .next_row()
3759            .as_f32()
3760            .log10()
3761            .floor() as usize
3762            + 1;
3763        self.column_pixels(digit_count, cx)
3764    }
3765}
3766
3767fn prepaint_gutter_button(
3768    button: IconButton,
3769    row: DisplayRow,
3770    line_height: Pixels,
3771    gutter_dimensions: &GutterDimensions,
3772    scroll_pixel_position: gpui::Point<Pixels>,
3773    gutter_hitbox: &Hitbox,
3774    cx: &mut WindowContext<'_>,
3775) -> AnyElement {
3776    let mut button = button.into_any_element();
3777    let available_space = size(
3778        AvailableSpace::MinContent,
3779        AvailableSpace::Definite(line_height),
3780    );
3781    let indicator_size = button.layout_as_root(available_space, cx);
3782
3783    let blame_width = gutter_dimensions
3784        .git_blame_entries_width
3785        .unwrap_or(Pixels::ZERO);
3786
3787    let mut x = blame_width;
3788    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
3789        - indicator_size.width
3790        - blame_width;
3791    x += available_width / 2.;
3792
3793    let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
3794    y += (line_height - indicator_size.height) / 2.;
3795
3796    button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
3797    button
3798}
3799
3800fn render_inline_blame_entry(
3801    blame: &gpui::Model<GitBlame>,
3802    blame_entry: BlameEntry,
3803    style: &EditorStyle,
3804    workspace: Option<WeakView<Workspace>>,
3805    cx: &mut WindowContext<'_>,
3806) -> AnyElement {
3807    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3808
3809    let author = blame_entry.author.as_deref().unwrap_or_default();
3810    let text = format!("{}, {}", author, relative_timestamp);
3811
3812    let details = blame.read(cx).details_for_entry(&blame_entry);
3813
3814    let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
3815
3816    h_flex()
3817        .id("inline-blame")
3818        .w_full()
3819        .font_family(style.text.font().family)
3820        .text_color(cx.theme().status().hint)
3821        .line_height(style.text.line_height)
3822        .child(Icon::new(IconName::FileGit).color(Color::Hint))
3823        .child(text)
3824        .gap_2()
3825        .hoverable_tooltip(move |_| tooltip.clone().into())
3826        .into_any()
3827}
3828
3829fn render_blame_entry(
3830    ix: usize,
3831    blame: &gpui::Model<GitBlame>,
3832    blame_entry: BlameEntry,
3833    style: &EditorStyle,
3834    last_used_color: &mut Option<(PlayerColor, Oid)>,
3835    editor: View<Editor>,
3836    cx: &mut WindowContext<'_>,
3837) -> AnyElement {
3838    let mut sha_color = cx
3839        .theme()
3840        .players()
3841        .color_for_participant(blame_entry.sha.into());
3842    // If the last color we used is the same as the one we get for this line, but
3843    // the commit SHAs are different, then we try again to get a different color.
3844    match *last_used_color {
3845        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3846            let index: u32 = blame_entry.sha.into();
3847            sha_color = cx.theme().players().color_for_participant(index + 1);
3848        }
3849        _ => {}
3850    };
3851    last_used_color.replace((sha_color, blame_entry.sha));
3852
3853    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3854
3855    let short_commit_id = blame_entry.sha.display_short();
3856
3857    let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3858    let name = util::truncate_and_trailoff(author_name, 20);
3859
3860    let details = blame.read(cx).details_for_entry(&blame_entry);
3861
3862    let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3863
3864    let tooltip = cx.new_view(|_| {
3865        BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3866    });
3867
3868    h_flex()
3869        .w_full()
3870        .font_family(style.text.font().family)
3871        .line_height(style.text.line_height)
3872        .id(("blame", ix))
3873        .children([
3874            div()
3875                .text_color(sha_color.cursor)
3876                .child(short_commit_id)
3877                .mr_2(),
3878            div()
3879                .w_full()
3880                .h_flex()
3881                .justify_between()
3882                .text_color(cx.theme().status().hint)
3883                .child(name)
3884                .child(relative_timestamp),
3885        ])
3886        .on_mouse_down(MouseButton::Right, {
3887            let blame_entry = blame_entry.clone();
3888            let details = details.clone();
3889            move |event, cx| {
3890                deploy_blame_entry_context_menu(
3891                    &blame_entry,
3892                    details.as_ref(),
3893                    editor.clone(),
3894                    event.position,
3895                    cx,
3896                );
3897            }
3898        })
3899        .hover(|style| style.bg(cx.theme().colors().element_hover))
3900        .when_some(
3901            details.and_then(|details| details.permalink),
3902            |this, url| {
3903                let url = url.clone();
3904                this.cursor_pointer().on_click(move |_, cx| {
3905                    cx.stop_propagation();
3906                    cx.open_url(url.as_str())
3907                })
3908            },
3909        )
3910        .hoverable_tooltip(move |_| tooltip.clone().into())
3911        .into_any()
3912}
3913
3914fn deploy_blame_entry_context_menu(
3915    blame_entry: &BlameEntry,
3916    details: Option<&CommitDetails>,
3917    editor: View<Editor>,
3918    position: gpui::Point<Pixels>,
3919    cx: &mut WindowContext<'_>,
3920) {
3921    let context_menu = ContextMenu::build(cx, move |this, _| {
3922        let sha = format!("{}", blame_entry.sha);
3923        this.entry("Copy commit SHA", None, move |cx| {
3924            cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
3925        })
3926        .when_some(
3927            details.and_then(|details| details.permalink.clone()),
3928            |this, url| this.entry("Open permalink", None, move |cx| cx.open_url(url.as_str())),
3929        )
3930    });
3931
3932    editor.update(cx, move |editor, cx| {
3933        editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
3934        cx.notify();
3935    });
3936}
3937
3938#[derive(Debug)]
3939pub(crate) struct LineWithInvisibles {
3940    fragments: SmallVec<[LineFragment; 1]>,
3941    invisibles: Vec<Invisible>,
3942    len: usize,
3943    width: Pixels,
3944    font_size: Pixels,
3945}
3946
3947#[allow(clippy::large_enum_variant)]
3948enum LineFragment {
3949    Text(ShapedLine),
3950    Element {
3951        element: Option<AnyElement>,
3952        size: Size<Pixels>,
3953        len: usize,
3954    },
3955}
3956
3957impl fmt::Debug for LineFragment {
3958    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3959        match self {
3960            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
3961            LineFragment::Element { size, len, .. } => f
3962                .debug_struct("Element")
3963                .field("size", size)
3964                .field("len", len)
3965                .finish(),
3966        }
3967    }
3968}
3969
3970impl LineWithInvisibles {
3971    fn from_chunks<'a>(
3972        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
3973        text_style: &TextStyle,
3974        max_line_len: usize,
3975        max_line_count: usize,
3976        line_number_layouts: &[Option<ShapedLine>],
3977        editor_mode: EditorMode,
3978        cx: &mut WindowContext,
3979    ) -> Vec<Self> {
3980        let mut layouts = Vec::with_capacity(max_line_count);
3981        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
3982        let mut line = String::new();
3983        let mut invisibles = Vec::new();
3984        let mut width = Pixels::ZERO;
3985        let mut len = 0;
3986        let mut styles = Vec::new();
3987        let mut non_whitespace_added = false;
3988        let mut row = 0;
3989        let mut line_exceeded_max_len = false;
3990        let font_size = text_style.font_size.to_pixels(cx.rem_size());
3991
3992        let ellipsis = SharedString::from("");
3993
3994        for highlighted_chunk in chunks.chain([HighlightedChunk {
3995            text: "\n",
3996            style: None,
3997            is_tab: false,
3998            renderer: None,
3999        }]) {
4000            if let Some(renderer) = highlighted_chunk.renderer {
4001                if !line.is_empty() {
4002                    let shaped_line = cx
4003                        .text_system()
4004                        .shape_line(line.clone().into(), font_size, &styles)
4005                        .unwrap();
4006                    width += shaped_line.width;
4007                    len += shaped_line.len;
4008                    fragments.push(LineFragment::Text(shaped_line));
4009                    line.clear();
4010                    styles.clear();
4011                }
4012
4013                let available_width = if renderer.constrain_width {
4014                    let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
4015                        ellipsis.clone()
4016                    } else {
4017                        SharedString::from(Arc::from(highlighted_chunk.text))
4018                    };
4019                    let shaped_line = cx
4020                        .text_system()
4021                        .shape_line(
4022                            chunk,
4023                            font_size,
4024                            &[text_style.to_run(highlighted_chunk.text.len())],
4025                        )
4026                        .unwrap();
4027                    AvailableSpace::Definite(shaped_line.width)
4028                } else {
4029                    AvailableSpace::MinContent
4030                };
4031
4032                let mut element = (renderer.render)(cx);
4033                let line_height = text_style.line_height_in_pixels(cx.rem_size());
4034                let size = element.layout_as_root(
4035                    size(available_width, AvailableSpace::Definite(line_height)),
4036                    cx,
4037                );
4038
4039                width += size.width;
4040                len += highlighted_chunk.text.len();
4041                fragments.push(LineFragment::Element {
4042                    element: Some(element),
4043                    size,
4044                    len: highlighted_chunk.text.len(),
4045                });
4046            } else {
4047                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
4048                    if ix > 0 {
4049                        let shaped_line = cx
4050                            .text_system()
4051                            .shape_line(line.clone().into(), font_size, &styles)
4052                            .unwrap();
4053                        width += shaped_line.width;
4054                        len += shaped_line.len;
4055                        fragments.push(LineFragment::Text(shaped_line));
4056                        layouts.push(Self {
4057                            width: mem::take(&mut width),
4058                            len: mem::take(&mut len),
4059                            fragments: mem::take(&mut fragments),
4060                            invisibles: std::mem::take(&mut invisibles),
4061                            font_size,
4062                        });
4063
4064                        line.clear();
4065                        styles.clear();
4066                        row += 1;
4067                        line_exceeded_max_len = false;
4068                        non_whitespace_added = false;
4069                        if row == max_line_count {
4070                            return layouts;
4071                        }
4072                    }
4073
4074                    if !line_chunk.is_empty() && !line_exceeded_max_len {
4075                        let text_style = if let Some(style) = highlighted_chunk.style {
4076                            Cow::Owned(text_style.clone().highlight(style))
4077                        } else {
4078                            Cow::Borrowed(text_style)
4079                        };
4080
4081                        if line.len() + line_chunk.len() > max_line_len {
4082                            let mut chunk_len = max_line_len - line.len();
4083                            while !line_chunk.is_char_boundary(chunk_len) {
4084                                chunk_len -= 1;
4085                            }
4086                            line_chunk = &line_chunk[..chunk_len];
4087                            line_exceeded_max_len = true;
4088                        }
4089
4090                        styles.push(TextRun {
4091                            len: line_chunk.len(),
4092                            font: text_style.font(),
4093                            color: text_style.color,
4094                            background_color: text_style.background_color,
4095                            underline: text_style.underline,
4096                            strikethrough: text_style.strikethrough,
4097                        });
4098
4099                        if editor_mode == EditorMode::Full {
4100                            // Line wrap pads its contents with fake whitespaces,
4101                            // avoid printing them
4102                            let inside_wrapped_string = line_number_layouts
4103                                .get(row)
4104                                .and_then(|layout| layout.as_ref())
4105                                .is_none();
4106                            if highlighted_chunk.is_tab {
4107                                if non_whitespace_added || !inside_wrapped_string {
4108                                    invisibles.push(Invisible::Tab {
4109                                        line_start_offset: line.len(),
4110                                        line_end_offset: line.len() + line_chunk.len(),
4111                                    });
4112                                }
4113                            } else {
4114                                invisibles.extend(
4115                                    line_chunk
4116                                        .bytes()
4117                                        .enumerate()
4118                                        .filter(|(_, line_byte)| {
4119                                            let is_whitespace =
4120                                                (*line_byte as char).is_whitespace();
4121                                            non_whitespace_added |= !is_whitespace;
4122                                            is_whitespace
4123                                                && (non_whitespace_added || !inside_wrapped_string)
4124                                        })
4125                                        .map(|(whitespace_index, _)| Invisible::Whitespace {
4126                                            line_offset: line.len() + whitespace_index,
4127                                        }),
4128                                )
4129                            }
4130                        }
4131
4132                        line.push_str(line_chunk);
4133                    }
4134                }
4135            }
4136        }
4137
4138        layouts
4139    }
4140
4141    fn prepaint(
4142        &mut self,
4143        line_height: Pixels,
4144        scroll_pixel_position: gpui::Point<Pixels>,
4145        row: DisplayRow,
4146        content_origin: gpui::Point<Pixels>,
4147        line_elements: &mut SmallVec<[AnyElement; 1]>,
4148        cx: &mut WindowContext,
4149    ) {
4150        let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
4151        let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
4152        for fragment in &mut self.fragments {
4153            match fragment {
4154                LineFragment::Text(line) => {
4155                    fragment_origin.x += line.width;
4156                }
4157                LineFragment::Element { element, size, .. } => {
4158                    let mut element = element
4159                        .take()
4160                        .expect("you can't prepaint LineWithInvisibles twice");
4161
4162                    // Center the element vertically within the line.
4163                    let mut element_origin = fragment_origin;
4164                    element_origin.y += (line_height - size.height) / 2.;
4165                    element.prepaint_at(element_origin, cx);
4166                    line_elements.push(element);
4167
4168                    fragment_origin.x += size.width;
4169                }
4170            }
4171        }
4172    }
4173
4174    fn draw(
4175        &self,
4176        layout: &EditorLayout,
4177        row: DisplayRow,
4178        content_origin: gpui::Point<Pixels>,
4179        whitespace_setting: ShowWhitespaceSetting,
4180        selection_ranges: &[Range<DisplayPoint>],
4181        cx: &mut WindowContext,
4182    ) {
4183        let line_height = layout.position_map.line_height;
4184        let line_y = line_height
4185            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
4186
4187        let mut fragment_origin =
4188            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
4189
4190        for fragment in &self.fragments {
4191            match fragment {
4192                LineFragment::Text(line) => {
4193                    line.paint(fragment_origin, line_height, cx).log_err();
4194                    fragment_origin.x += line.width;
4195                }
4196                LineFragment::Element { size, .. } => {
4197                    fragment_origin.x += size.width;
4198                }
4199            }
4200        }
4201
4202        self.draw_invisibles(
4203            &selection_ranges,
4204            layout,
4205            content_origin,
4206            line_y,
4207            row,
4208            line_height,
4209            whitespace_setting,
4210            cx,
4211        );
4212    }
4213
4214    #[allow(clippy::too_many_arguments)]
4215    fn draw_invisibles(
4216        &self,
4217        selection_ranges: &[Range<DisplayPoint>],
4218        layout: &EditorLayout,
4219        content_origin: gpui::Point<Pixels>,
4220        line_y: Pixels,
4221        row: DisplayRow,
4222        line_height: Pixels,
4223        whitespace_setting: ShowWhitespaceSetting,
4224        cx: &mut WindowContext,
4225    ) {
4226        let extract_whitespace_info = |invisible: &Invisible| {
4227            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
4228                Invisible::Tab {
4229                    line_start_offset,
4230                    line_end_offset,
4231                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
4232                Invisible::Whitespace { line_offset } => {
4233                    (*line_offset, line_offset + 1, &layout.space_invisible)
4234                }
4235            };
4236
4237            let x_offset = self.x_for_index(token_offset);
4238            let invisible_offset =
4239                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
4240            let origin = content_origin
4241                + gpui::point(
4242                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
4243                    line_y,
4244                );
4245
4246            (
4247                [token_offset, token_end_offset],
4248                Box::new(move |cx: &mut WindowContext| {
4249                    invisible_symbol.paint(origin, line_height, cx).log_err();
4250                }),
4251            )
4252        };
4253
4254        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
4255        match whitespace_setting {
4256            ShowWhitespaceSetting::None => return,
4257            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(cx)),
4258            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
4259                let invisible_point = DisplayPoint::new(row, start as u32);
4260                if !selection_ranges
4261                    .iter()
4262                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
4263                {
4264                    return;
4265                }
4266
4267                paint(cx);
4268            }),
4269
4270            // For a whitespace to be on a boundary, any of the following conditions need to be met:
4271            // - It is a tab
4272            // - It is adjacent to an edge (start or end)
4273            // - It is adjacent to a whitespace (left or right)
4274            ShowWhitespaceSetting::Boundary => {
4275                // 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
4276                // the above cases.
4277                // Note: We zip in the original `invisibles` to check for tab equality
4278                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut WindowContext)>)> = None;
4279                for (([start, end], paint), invisible) in
4280                    invisible_iter.zip_eq(self.invisibles.iter())
4281                {
4282                    let should_render = match (&last_seen, invisible) {
4283                        (_, Invisible::Tab { .. }) => true,
4284                        (Some((_, last_end, _)), _) => *last_end == start,
4285                        _ => false,
4286                    };
4287
4288                    if should_render || start == 0 || end == self.len {
4289                        paint(cx);
4290
4291                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
4292                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
4293                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
4294                            // Note that we need to make sure that the last one is actually adjacent
4295                            if !should_render_last && last_end == start {
4296                                paint_last(cx);
4297                            }
4298                        }
4299                    }
4300
4301                    // Manually render anything within a selection
4302                    let invisible_point = DisplayPoint::new(row, start as u32);
4303                    if selection_ranges.iter().any(|region| {
4304                        region.start <= invisible_point && invisible_point < region.end
4305                    }) {
4306                        paint(cx);
4307                    }
4308
4309                    last_seen = Some((should_render, end, paint));
4310                }
4311            }
4312        };
4313    }
4314
4315    pub fn x_for_index(&self, index: usize) -> Pixels {
4316        let mut fragment_start_x = Pixels::ZERO;
4317        let mut fragment_start_index = 0;
4318
4319        for fragment in &self.fragments {
4320            match fragment {
4321                LineFragment::Text(shaped_line) => {
4322                    let fragment_end_index = fragment_start_index + shaped_line.len;
4323                    if index < fragment_end_index {
4324                        return fragment_start_x
4325                            + shaped_line.x_for_index(index - fragment_start_index);
4326                    }
4327                    fragment_start_x += shaped_line.width;
4328                    fragment_start_index = fragment_end_index;
4329                }
4330                LineFragment::Element { len, size, .. } => {
4331                    let fragment_end_index = fragment_start_index + len;
4332                    if index < fragment_end_index {
4333                        return fragment_start_x;
4334                    }
4335                    fragment_start_x += size.width;
4336                    fragment_start_index = fragment_end_index;
4337                }
4338            }
4339        }
4340
4341        fragment_start_x
4342    }
4343
4344    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
4345        let mut fragment_start_x = Pixels::ZERO;
4346        let mut fragment_start_index = 0;
4347
4348        for fragment in &self.fragments {
4349            match fragment {
4350                LineFragment::Text(shaped_line) => {
4351                    let fragment_end_x = fragment_start_x + shaped_line.width;
4352                    if x < fragment_end_x {
4353                        return Some(
4354                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
4355                        );
4356                    }
4357                    fragment_start_x = fragment_end_x;
4358                    fragment_start_index += shaped_line.len;
4359                }
4360                LineFragment::Element { len, size, .. } => {
4361                    let fragment_end_x = fragment_start_x + size.width;
4362                    if x < fragment_end_x {
4363                        return Some(fragment_start_index);
4364                    }
4365                    fragment_start_index += len;
4366                    fragment_start_x = fragment_end_x;
4367                }
4368            }
4369        }
4370
4371        None
4372    }
4373
4374    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
4375        let mut fragment_start_index = 0;
4376
4377        for fragment in &self.fragments {
4378            match fragment {
4379                LineFragment::Text(shaped_line) => {
4380                    let fragment_end_index = fragment_start_index + shaped_line.len;
4381                    if index < fragment_end_index {
4382                        return shaped_line.font_id_for_index(index - fragment_start_index);
4383                    }
4384                    fragment_start_index = fragment_end_index;
4385                }
4386                LineFragment::Element { len, .. } => {
4387                    let fragment_end_index = fragment_start_index + len;
4388                    if index < fragment_end_index {
4389                        return None;
4390                    }
4391                    fragment_start_index = fragment_end_index;
4392                }
4393            }
4394        }
4395
4396        None
4397    }
4398}
4399
4400#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4401enum Invisible {
4402    /// A tab character
4403    ///
4404    /// A tab character is internally represented by spaces (configured by the user's tab width)
4405    /// aligned to the nearest column, so it's necessary to store the start and end offset for
4406    /// adjacency checks.
4407    Tab {
4408        line_start_offset: usize,
4409        line_end_offset: usize,
4410    },
4411    Whitespace {
4412        line_offset: usize,
4413    },
4414}
4415
4416impl EditorElement {
4417    /// Returns the rem size to use when rendering the [`EditorElement`].
4418    ///
4419    /// This allows UI elements to scale based on the `buffer_font_size`.
4420    fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
4421        match self.editor.read(cx).mode {
4422            EditorMode::Full => {
4423                let buffer_font_size = self.style.text.font_size;
4424                match buffer_font_size {
4425                    AbsoluteLength::Pixels(pixels) => {
4426                        let rem_size_scale = {
4427                            // Our default UI font size is 14px on a 16px base scale.
4428                            // This means the default UI font size is 0.875rems.
4429                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
4430
4431                            // We then determine the delta between a single rem and the default font
4432                            // size scale.
4433                            let default_font_size_delta = 1. - default_font_size_scale;
4434
4435                            // Finally, we add this delta to 1rem to get the scale factor that
4436                            // should be used to scale up the UI.
4437                            1. + default_font_size_delta
4438                        };
4439
4440                        Some(pixels * rem_size_scale)
4441                    }
4442                    AbsoluteLength::Rems(rems) => {
4443                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
4444                    }
4445                }
4446            }
4447            // We currently use single-line and auto-height editors in UI contexts,
4448            // so we don't want to scale everything with the buffer font size, as it
4449            // ends up looking off.
4450            EditorMode::SingleLine | EditorMode::AutoHeight { .. } => None,
4451        }
4452    }
4453}
4454
4455impl Element for EditorElement {
4456    type RequestLayoutState = ();
4457    type PrepaintState = EditorLayout;
4458
4459    fn id(&self) -> Option<ElementId> {
4460        None
4461    }
4462
4463    fn request_layout(
4464        &mut self,
4465        _: Option<&GlobalElementId>,
4466        cx: &mut WindowContext,
4467    ) -> (gpui::LayoutId, ()) {
4468        let rem_size = self.rem_size(cx);
4469        cx.with_rem_size(rem_size, |cx| {
4470            self.editor.update(cx, |editor, cx| {
4471                editor.set_style(self.style.clone(), cx);
4472
4473                let layout_id = match editor.mode {
4474                    EditorMode::SingleLine => {
4475                        let rem_size = cx.rem_size();
4476                        let mut style = Style::default();
4477                        style.size.width = relative(1.).into();
4478                        style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
4479                        cx.request_layout(style, None)
4480                    }
4481                    EditorMode::AutoHeight { max_lines } => {
4482                        let editor_handle = cx.view().clone();
4483                        let max_line_number_width =
4484                            self.max_line_number_width(&editor.snapshot(cx), cx);
4485                        cx.request_measured_layout(
4486                            Style::default(),
4487                            move |known_dimensions, available_space, cx| {
4488                                editor_handle
4489                                    .update(cx, |editor, cx| {
4490                                        compute_auto_height_layout(
4491                                            editor,
4492                                            max_lines,
4493                                            max_line_number_width,
4494                                            known_dimensions,
4495                                            available_space.width,
4496                                            cx,
4497                                        )
4498                                    })
4499                                    .unwrap_or_default()
4500                            },
4501                        )
4502                    }
4503                    EditorMode::Full => {
4504                        let mut style = Style::default();
4505                        style.size.width = relative(1.).into();
4506                        style.size.height = relative(1.).into();
4507                        cx.request_layout(style, None)
4508                    }
4509                };
4510
4511                (layout_id, ())
4512            })
4513        })
4514    }
4515
4516    fn prepaint(
4517        &mut self,
4518        _: Option<&GlobalElementId>,
4519        bounds: Bounds<Pixels>,
4520        _: &mut Self::RequestLayoutState,
4521        cx: &mut WindowContext,
4522    ) -> Self::PrepaintState {
4523        let text_style = TextStyleRefinement {
4524            font_size: Some(self.style.text.font_size),
4525            line_height: Some(self.style.text.line_height),
4526            ..Default::default()
4527        };
4528        cx.set_view_id(self.editor.entity_id());
4529
4530        let rem_size = self.rem_size(cx);
4531        cx.with_rem_size(rem_size, |cx| {
4532            cx.with_text_style(Some(text_style), |cx| {
4533                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
4534                    let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
4535                    let style = self.style.clone();
4536
4537                    let font_id = cx.text_system().resolve_font(&style.text.font());
4538                    let font_size = style.text.font_size.to_pixels(cx.rem_size());
4539                    let line_height = style.text.line_height_in_pixels(cx.rem_size());
4540                    let em_width = cx
4541                        .text_system()
4542                        .typographic_bounds(font_id, font_size, 'm')
4543                        .unwrap()
4544                        .size
4545                        .width;
4546                    let em_advance = cx
4547                        .text_system()
4548                        .advance(font_id, font_size, 'm')
4549                        .unwrap()
4550                        .width;
4551
4552                    let gutter_dimensions = snapshot.gutter_dimensions(
4553                        font_id,
4554                        font_size,
4555                        em_width,
4556                        self.max_line_number_width(&snapshot, cx),
4557                        cx,
4558                    );
4559                    let text_width = bounds.size.width - gutter_dimensions.width;
4560
4561                    let right_margin = if snapshot.mode == EditorMode::Full {
4562                        EditorElement::SCROLLBAR_WIDTH
4563                    } else {
4564                        px(0.)
4565                    };
4566                    let overscroll = size(em_width + right_margin, px(0.));
4567
4568                    snapshot = self.editor.update(cx, |editor, cx| {
4569                        editor.last_bounds = Some(bounds);
4570                        editor.gutter_dimensions = gutter_dimensions;
4571                        editor.set_visible_line_count(bounds.size.height / line_height, cx);
4572
4573                        let editor_width =
4574                            text_width - gutter_dimensions.margin - overscroll.width - em_width;
4575                        let wrap_width = match editor.soft_wrap_mode(cx) {
4576                            SoftWrap::None => None,
4577                            SoftWrap::PreferLine => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
4578                            SoftWrap::EditorWidth => Some(editor_width),
4579                            SoftWrap::Column(column) => {
4580                                Some(editor_width.min(column as f32 * em_advance))
4581                            }
4582                        };
4583
4584                        if editor.set_wrap_width(wrap_width, cx) {
4585                            editor.snapshot(cx)
4586                        } else {
4587                            snapshot
4588                        }
4589                    });
4590
4591                    let wrap_guides = self
4592                        .editor
4593                        .read(cx)
4594                        .wrap_guides(cx)
4595                        .iter()
4596                        .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
4597                        .collect::<SmallVec<[_; 2]>>();
4598
4599                    let hitbox = cx.insert_hitbox(bounds, false);
4600                    let gutter_hitbox = cx.insert_hitbox(
4601                        Bounds {
4602                            origin: bounds.origin,
4603                            size: size(gutter_dimensions.width, bounds.size.height),
4604                        },
4605                        false,
4606                    );
4607                    let text_hitbox = cx.insert_hitbox(
4608                        Bounds {
4609                            origin: gutter_hitbox.upper_right(),
4610                            size: size(text_width, bounds.size.height),
4611                        },
4612                        false,
4613                    );
4614                    // Offset the content_bounds from the text_bounds by the gutter margin (which
4615                    // is roughly half a character wide) to make hit testing work more like how we want.
4616                    let content_origin =
4617                        text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
4618
4619                    let mut autoscroll_containing_element = false;
4620                    let mut autoscroll_horizontally = false;
4621                    self.editor.update(cx, |editor, cx| {
4622                        autoscroll_containing_element =
4623                            editor.autoscroll_requested() || editor.has_pending_selection();
4624                        autoscroll_horizontally =
4625                            editor.autoscroll_vertically(bounds, line_height, cx);
4626                        snapshot = editor.snapshot(cx);
4627                    });
4628
4629                    let mut scroll_position = snapshot.scroll_position();
4630                    // The scroll position is a fractional point, the whole number of which represents
4631                    // the top of the window in terms of display rows.
4632                    let start_row = DisplayRow(scroll_position.y as u32);
4633                    let height_in_lines = bounds.size.height / line_height;
4634                    let max_row = snapshot.max_point().row();
4635                    let end_row = cmp::min(
4636                        (scroll_position.y + height_in_lines).ceil() as u32,
4637                        max_row.next_row().0,
4638                    );
4639                    let end_row = DisplayRow(end_row);
4640
4641                    let buffer_rows = snapshot
4642                        .buffer_rows(start_row)
4643                        .take((start_row..end_row).len())
4644                        .collect::<Vec<_>>();
4645
4646                    let start_anchor = if start_row == Default::default() {
4647                        Anchor::min()
4648                    } else {
4649                        snapshot.buffer_snapshot.anchor_before(
4650                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
4651                        )
4652                    };
4653                    let end_anchor = if end_row > max_row {
4654                        Anchor::max()
4655                    } else {
4656                        snapshot.buffer_snapshot.anchor_before(
4657                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
4658                        )
4659                    };
4660
4661                    let highlighted_rows = self
4662                        .editor
4663                        .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
4664                    let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
4665                        start_anchor..end_anchor,
4666                        &snapshot.display_snapshot,
4667                        cx.theme().colors(),
4668                    );
4669                    let highlighted_gutter_ranges =
4670                        self.editor.read(cx).gutter_highlights_in_range(
4671                            start_anchor..end_anchor,
4672                            &snapshot.display_snapshot,
4673                            cx,
4674                        );
4675
4676                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
4677                        start_anchor..end_anchor,
4678                        &snapshot.display_snapshot,
4679                        cx,
4680                    );
4681
4682                    let (selections, active_rows, newest_selection_head) = self.layout_selections(
4683                        start_anchor,
4684                        end_anchor,
4685                        &snapshot,
4686                        start_row,
4687                        end_row,
4688                        cx,
4689                    );
4690
4691                    let line_numbers = self.layout_line_numbers(
4692                        start_row..end_row,
4693                        buffer_rows.iter().copied(),
4694                        &active_rows,
4695                        newest_selection_head,
4696                        &snapshot,
4697                        cx,
4698                    );
4699
4700                    let mut gutter_fold_toggles =
4701                        cx.with_element_namespace("gutter_fold_toggles", |cx| {
4702                            self.layout_gutter_fold_toggles(
4703                                start_row..end_row,
4704                                buffer_rows.iter().copied(),
4705                                &active_rows,
4706                                &snapshot,
4707                                cx,
4708                            )
4709                        });
4710                    let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
4711                        self.layout_crease_trailers(buffer_rows.iter().copied(), &snapshot, cx)
4712                    });
4713
4714                    let display_hunks = self.layout_git_gutters(
4715                        line_height,
4716                        &gutter_hitbox,
4717                        start_row..end_row,
4718                        &snapshot,
4719                        cx,
4720                    );
4721
4722                    let mut max_visible_line_width = Pixels::ZERO;
4723                    let mut line_layouts =
4724                        self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
4725                    for line_with_invisibles in &line_layouts {
4726                        if line_with_invisibles.width > max_visible_line_width {
4727                            max_visible_line_width = line_with_invisibles.width;
4728                        }
4729                    }
4730
4731                    let longest_line_width =
4732                        layout_line(snapshot.longest_row(), &snapshot, &style, cx).width;
4733                    let mut scroll_width =
4734                        longest_line_width.max(max_visible_line_width) + overscroll.width;
4735
4736                    let mut blocks = cx.with_element_namespace("blocks", |cx| {
4737                        self.build_blocks(
4738                            start_row..end_row,
4739                            &snapshot,
4740                            &hitbox,
4741                            &text_hitbox,
4742                            &mut scroll_width,
4743                            &gutter_dimensions,
4744                            em_width,
4745                            gutter_dimensions.full_width(),
4746                            line_height,
4747                            &line_layouts,
4748                            cx,
4749                        )
4750                    });
4751
4752                    let scroll_pixel_position = point(
4753                        scroll_position.x * em_width,
4754                        scroll_position.y * line_height,
4755                    );
4756
4757                    let start_buffer_row =
4758                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
4759                    let end_buffer_row =
4760                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
4761
4762                    let indent_guides = self.layout_indent_guides(
4763                        content_origin,
4764                        text_hitbox.origin,
4765                        start_buffer_row..end_buffer_row,
4766                        scroll_pixel_position,
4767                        line_height,
4768                        &snapshot,
4769                        cx,
4770                    );
4771
4772                    let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
4773                        self.prepaint_crease_trailers(
4774                            crease_trailers,
4775                            &line_layouts,
4776                            line_height,
4777                            content_origin,
4778                            scroll_pixel_position,
4779                            em_width,
4780                            cx,
4781                        )
4782                    });
4783
4784                    let mut inline_blame = None;
4785                    if let Some(newest_selection_head) = newest_selection_head {
4786                        let display_row = newest_selection_head.row();
4787                        if (start_row..end_row).contains(&display_row) {
4788                            let line_ix = display_row.minus(start_row) as usize;
4789                            let line_layout = &line_layouts[line_ix];
4790                            let crease_trailer_layout = crease_trailers[line_ix].as_ref();
4791                            inline_blame = self.layout_inline_blame(
4792                                display_row,
4793                                &snapshot.display_snapshot,
4794                                line_layout,
4795                                crease_trailer_layout,
4796                                em_width,
4797                                content_origin,
4798                                scroll_pixel_position,
4799                                line_height,
4800                                cx,
4801                            );
4802                        }
4803                    }
4804
4805                    let blamed_display_rows = self.layout_blame_entries(
4806                        buffer_rows.into_iter(),
4807                        em_width,
4808                        scroll_position,
4809                        line_height,
4810                        &gutter_hitbox,
4811                        gutter_dimensions.git_blame_entries_width,
4812                        cx,
4813                    );
4814
4815                    let settings = EditorSettings::get_global(cx);
4816                    let scroll_max_row = max_row.as_f32();
4817                    let scroll_max_row = match settings.scroll_beyond_last_line {
4818                        ScrollBeyondLastLine::OnePage => scroll_max_row,
4819                        ScrollBeyondLastLine::Off => {
4820                            (scroll_max_row - height_in_lines + 1.0).max(0.0)
4821                        }
4822                        ScrollBeyondLastLine::VerticalScrollMargin => (scroll_max_row
4823                            - height_in_lines
4824                            + 1.0
4825                            + settings.vertical_scroll_margin)
4826                            .max(0.0),
4827                    };
4828                    let scroll_max = point(
4829                        ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
4830                        scroll_max_row,
4831                    );
4832
4833                    self.editor.update(cx, |editor, cx| {
4834                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
4835
4836                        let autoscrolled = if autoscroll_horizontally {
4837                            editor.autoscroll_horizontally(
4838                                start_row,
4839                                text_hitbox.size.width,
4840                                scroll_width,
4841                                em_width,
4842                                &line_layouts,
4843                                cx,
4844                            )
4845                        } else {
4846                            false
4847                        };
4848
4849                        if clamped || autoscrolled {
4850                            snapshot = editor.snapshot(cx);
4851                            scroll_position = snapshot.scroll_position();
4852                        }
4853                    });
4854
4855                    let line_elements = self.prepaint_lines(
4856                        start_row,
4857                        &mut line_layouts,
4858                        line_height,
4859                        scroll_pixel_position,
4860                        content_origin,
4861                        cx,
4862                    );
4863
4864                    cx.with_element_namespace("blocks", |cx| {
4865                        self.layout_blocks(
4866                            &mut blocks,
4867                            &hitbox,
4868                            line_height,
4869                            scroll_pixel_position,
4870                            cx,
4871                        );
4872                    });
4873
4874                    let cursors = self.collect_cursors(&snapshot, cx);
4875                    let visible_row_range = start_row..end_row;
4876                    let non_visible_cursors = cursors
4877                        .iter()
4878                        .any(move |c| !visible_row_range.contains(&c.0.row()));
4879
4880                    let visible_cursors = self.layout_visible_cursors(
4881                        &snapshot,
4882                        &selections,
4883                        start_row..end_row,
4884                        &line_layouts,
4885                        &text_hitbox,
4886                        content_origin,
4887                        scroll_position,
4888                        scroll_pixel_position,
4889                        line_height,
4890                        em_width,
4891                        autoscroll_containing_element,
4892                        cx,
4893                    );
4894
4895                    let scrollbar_layout = self.layout_scrollbar(
4896                        &snapshot,
4897                        bounds,
4898                        scroll_position,
4899                        height_in_lines,
4900                        non_visible_cursors,
4901                        cx,
4902                    );
4903
4904                    let gutter_settings = EditorSettings::get_global(cx).gutter;
4905
4906                    let mut _context_menu_visible = false;
4907                    let mut code_actions_indicator = None;
4908                    if let Some(newest_selection_head) = newest_selection_head {
4909                        if (start_row..end_row).contains(&newest_selection_head.row()) {
4910                            _context_menu_visible = self.layout_context_menu(
4911                                line_height,
4912                                &hitbox,
4913                                &text_hitbox,
4914                                content_origin,
4915                                start_row,
4916                                scroll_pixel_position,
4917                                &line_layouts,
4918                                newest_selection_head,
4919                                gutter_dimensions.width - gutter_dimensions.left_padding,
4920                                cx,
4921                            );
4922
4923                            let show_code_actions = snapshot
4924                                .show_code_actions
4925                                .unwrap_or_else(|| gutter_settings.code_actions);
4926                            if show_code_actions {
4927                                let newest_selection_point =
4928                                    newest_selection_head.to_point(&snapshot.display_snapshot);
4929                                let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
4930                                    MultiBufferRow(newest_selection_point.row),
4931                                );
4932                                if let Some((buffer, range)) = buffer {
4933                                    let buffer_id = buffer.remote_id();
4934                                    let row = range.start.row;
4935                                    let has_test_indicator =
4936                                        self.editor.read(cx).tasks.contains_key(&(buffer_id, row));
4937
4938                                    if !has_test_indicator {
4939                                        code_actions_indicator = self
4940                                            .layout_code_actions_indicator(
4941                                                line_height,
4942                                                newest_selection_head,
4943                                                scroll_pixel_position,
4944                                                &gutter_dimensions,
4945                                                &gutter_hitbox,
4946                                                cx,
4947                                            );
4948                                    }
4949                                }
4950                            }
4951                        }
4952                    }
4953
4954                    let test_indicators = if gutter_settings.runnables {
4955                        self.layout_run_indicators(
4956                            line_height,
4957                            scroll_pixel_position,
4958                            &gutter_dimensions,
4959                            &gutter_hitbox,
4960                            &snapshot,
4961                            cx,
4962                        )
4963                    } else {
4964                        vec![]
4965                    };
4966
4967                    if !cx.has_active_drag() {
4968                        self.layout_hover_popovers(
4969                            &snapshot,
4970                            &hitbox,
4971                            &text_hitbox,
4972                            start_row..end_row,
4973                            content_origin,
4974                            scroll_pixel_position,
4975                            &line_layouts,
4976                            line_height,
4977                            em_width,
4978                            cx,
4979                        );
4980                    }
4981
4982                    let mouse_context_menu = self.layout_mouse_context_menu(cx);
4983
4984                    cx.with_element_namespace("gutter_fold_toggles", |cx| {
4985                        self.prepaint_gutter_fold_toggles(
4986                            &mut gutter_fold_toggles,
4987                            line_height,
4988                            &gutter_dimensions,
4989                            gutter_settings,
4990                            scroll_pixel_position,
4991                            &gutter_hitbox,
4992                            cx,
4993                        )
4994                    });
4995
4996                    let invisible_symbol_font_size = font_size / 2.;
4997                    let tab_invisible = cx
4998                        .text_system()
4999                        .shape_line(
5000                            "".into(),
5001                            invisible_symbol_font_size,
5002                            &[TextRun {
5003                                len: "".len(),
5004                                font: self.style.text.font(),
5005                                color: cx.theme().colors().editor_invisible,
5006                                background_color: None,
5007                                underline: None,
5008                                strikethrough: None,
5009                            }],
5010                        )
5011                        .unwrap();
5012                    let space_invisible = cx
5013                        .text_system()
5014                        .shape_line(
5015                            "".into(),
5016                            invisible_symbol_font_size,
5017                            &[TextRun {
5018                                len: "".len(),
5019                                font: self.style.text.font(),
5020                                color: cx.theme().colors().editor_invisible,
5021                                background_color: None,
5022                                underline: None,
5023                                strikethrough: None,
5024                            }],
5025                        )
5026                        .unwrap();
5027
5028                    EditorLayout {
5029                        mode: snapshot.mode,
5030                        position_map: Arc::new(PositionMap {
5031                            size: bounds.size,
5032                            scroll_pixel_position,
5033                            scroll_max,
5034                            line_layouts,
5035                            line_height,
5036                            em_width,
5037                            em_advance,
5038                            snapshot,
5039                        }),
5040                        visible_display_row_range: start_row..end_row,
5041                        wrap_guides,
5042                        indent_guides,
5043                        hitbox,
5044                        text_hitbox,
5045                        gutter_hitbox,
5046                        gutter_dimensions,
5047                        content_origin,
5048                        scrollbar_layout,
5049                        active_rows,
5050                        highlighted_rows,
5051                        highlighted_ranges,
5052                        highlighted_gutter_ranges,
5053                        redacted_ranges,
5054                        line_elements,
5055                        line_numbers,
5056                        display_hunks,
5057                        blamed_display_rows,
5058                        inline_blame,
5059                        blocks,
5060                        cursors,
5061                        visible_cursors,
5062                        selections,
5063                        mouse_context_menu,
5064                        test_indicators,
5065                        code_actions_indicator,
5066                        gutter_fold_toggles,
5067                        crease_trailers,
5068                        tab_invisible,
5069                        space_invisible,
5070                    }
5071                })
5072            })
5073        })
5074    }
5075
5076    fn paint(
5077        &mut self,
5078        _: Option<&GlobalElementId>,
5079        bounds: Bounds<gpui::Pixels>,
5080        _: &mut Self::RequestLayoutState,
5081        layout: &mut Self::PrepaintState,
5082        cx: &mut WindowContext,
5083    ) {
5084        let focus_handle = self.editor.focus_handle(cx);
5085        let key_context = self.editor.read(cx).key_context(cx);
5086        cx.set_focus_handle(&focus_handle);
5087        cx.set_key_context(key_context);
5088        cx.handle_input(
5089            &focus_handle,
5090            ElementInputHandler::new(bounds, self.editor.clone()),
5091        );
5092        self.register_actions(cx);
5093        self.register_key_listeners(cx, layout);
5094
5095        let text_style = TextStyleRefinement {
5096            font_size: Some(self.style.text.font_size),
5097            line_height: Some(self.style.text.line_height),
5098            ..Default::default()
5099        };
5100        let mouse_position = cx.mouse_position();
5101        let hovered_hunk = layout
5102            .display_hunks
5103            .iter()
5104            .find_map(|(hunk, hunk_hitbox)| match hunk {
5105                DisplayDiffHunk::Folded { .. } => None,
5106                DisplayDiffHunk::Unfolded {
5107                    diff_base_byte_range,
5108                    multi_buffer_range,
5109                    status,
5110                    ..
5111                } => {
5112                    if hunk_hitbox
5113                        .as_ref()
5114                        .map(|hitbox| hitbox.contains(&mouse_position))
5115                        .unwrap_or(false)
5116                    {
5117                        Some(HunkToExpand {
5118                            status: *status,
5119                            multi_buffer_range: multi_buffer_range.clone(),
5120                            diff_base_byte_range: diff_base_byte_range.clone(),
5121                        })
5122                    } else {
5123                        None
5124                    }
5125                }
5126            });
5127        let rem_size = self.rem_size(cx);
5128        cx.with_rem_size(rem_size, |cx| {
5129            cx.with_text_style(Some(text_style), |cx| {
5130                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5131                    self.paint_mouse_listeners(layout, hovered_hunk, cx);
5132                    self.paint_background(layout, cx);
5133                    self.paint_indent_guides(layout, cx);
5134
5135                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
5136                        self.paint_blamed_display_rows(layout, cx);
5137                        self.paint_line_numbers(layout, cx);
5138                    }
5139
5140                    self.paint_text(layout, cx);
5141
5142                    if !layout.blocks.is_empty() {
5143                        cx.with_element_namespace("blocks", |cx| {
5144                            self.paint_blocks(layout, cx);
5145                        });
5146                    }
5147
5148                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
5149                        self.paint_gutter_highlights(layout, cx);
5150                        self.paint_gutter_indicators(layout, cx);
5151                    }
5152
5153                    self.paint_scrollbar(layout, cx);
5154                    self.paint_mouse_context_menu(layout, cx);
5155                });
5156            })
5157        })
5158    }
5159}
5160
5161impl IntoElement for EditorElement {
5162    type Element = Self;
5163
5164    fn into_element(self) -> Self::Element {
5165        self
5166    }
5167}
5168
5169pub struct EditorLayout {
5170    position_map: Arc<PositionMap>,
5171    hitbox: Hitbox,
5172    text_hitbox: Hitbox,
5173    gutter_hitbox: Hitbox,
5174    gutter_dimensions: GutterDimensions,
5175    content_origin: gpui::Point<Pixels>,
5176    scrollbar_layout: Option<ScrollbarLayout>,
5177    mode: EditorMode,
5178    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
5179    indent_guides: Option<Vec<IndentGuideLayout>>,
5180    visible_display_row_range: Range<DisplayRow>,
5181    active_rows: BTreeMap<DisplayRow, bool>,
5182    highlighted_rows: BTreeMap<DisplayRow, Hsla>,
5183    line_elements: SmallVec<[AnyElement; 1]>,
5184    line_numbers: Vec<Option<ShapedLine>>,
5185    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
5186    blamed_display_rows: Option<Vec<AnyElement>>,
5187    inline_blame: Option<AnyElement>,
5188    blocks: Vec<BlockLayout>,
5189    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5190    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5191    redacted_ranges: Vec<Range<DisplayPoint>>,
5192    cursors: Vec<(DisplayPoint, Hsla)>,
5193    visible_cursors: Vec<CursorLayout>,
5194    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
5195    code_actions_indicator: Option<AnyElement>,
5196    test_indicators: Vec<AnyElement>,
5197    gutter_fold_toggles: Vec<Option<AnyElement>>,
5198    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
5199    mouse_context_menu: Option<AnyElement>,
5200    tab_invisible: ShapedLine,
5201    space_invisible: ShapedLine,
5202}
5203
5204impl EditorLayout {
5205    fn line_end_overshoot(&self) -> Pixels {
5206        0.15 * self.position_map.line_height
5207    }
5208}
5209
5210struct ColoredRange<T> {
5211    start: T,
5212    end: T,
5213    color: Hsla,
5214}
5215
5216#[derive(Clone)]
5217struct ScrollbarLayout {
5218    hitbox: Hitbox,
5219    visible_row_range: Range<f32>,
5220    visible: bool,
5221    row_height: Pixels,
5222    thumb_height: Pixels,
5223}
5224
5225impl ScrollbarLayout {
5226    const BORDER_WIDTH: Pixels = px(1.0);
5227    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
5228    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
5229    const MIN_THUMB_HEIGHT: Pixels = px(20.0);
5230
5231    fn thumb_bounds(&self) -> Bounds<Pixels> {
5232        let thumb_top = self.y_for_row(self.visible_row_range.start);
5233        let thumb_bottom = thumb_top + self.thumb_height;
5234        Bounds::from_corners(
5235            point(self.hitbox.left(), thumb_top),
5236            point(self.hitbox.right(), thumb_bottom),
5237        )
5238    }
5239
5240    fn y_for_row(&self, row: f32) -> Pixels {
5241        self.hitbox.top() + row * self.row_height
5242    }
5243
5244    fn marker_quads_for_ranges(
5245        &self,
5246        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
5247        column: Option<usize>,
5248    ) -> Vec<PaintQuad> {
5249        struct MinMax {
5250            min: Pixels,
5251            max: Pixels,
5252        }
5253        let (x_range, height_limit) = if let Some(column) = column {
5254            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
5255            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
5256            let end = start + column_width;
5257            (
5258                Range { start, end },
5259                MinMax {
5260                    min: Self::MIN_MARKER_HEIGHT,
5261                    max: px(f32::MAX),
5262                },
5263            )
5264        } else {
5265            (
5266                Range {
5267                    start: Self::BORDER_WIDTH,
5268                    end: self.hitbox.size.width,
5269                },
5270                MinMax {
5271                    min: Self::LINE_MARKER_HEIGHT,
5272                    max: Self::LINE_MARKER_HEIGHT,
5273                },
5274            )
5275        };
5276
5277        let row_to_y = |row: DisplayRow| row.as_f32() * self.row_height;
5278        let mut pixel_ranges = row_ranges
5279            .into_iter()
5280            .map(|range| {
5281                let start_y = row_to_y(range.start);
5282                let end_y = row_to_y(range.end)
5283                    + self.row_height.max(height_limit.min).min(height_limit.max);
5284                ColoredRange {
5285                    start: start_y,
5286                    end: end_y,
5287                    color: range.color,
5288                }
5289            })
5290            .peekable();
5291
5292        let mut quads = Vec::new();
5293        while let Some(mut pixel_range) = pixel_ranges.next() {
5294            while let Some(next_pixel_range) = pixel_ranges.peek() {
5295                if pixel_range.end >= next_pixel_range.start - px(1.0)
5296                    && pixel_range.color == next_pixel_range.color
5297                {
5298                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
5299                    pixel_ranges.next();
5300                } else {
5301                    break;
5302                }
5303            }
5304
5305            let bounds = Bounds::from_corners(
5306                point(x_range.start, pixel_range.start),
5307                point(x_range.end, pixel_range.end),
5308            );
5309            quads.push(quad(
5310                bounds,
5311                Corners::default(),
5312                pixel_range.color,
5313                Edges::default(),
5314                Hsla::transparent_black(),
5315            ));
5316        }
5317
5318        quads
5319    }
5320}
5321
5322struct CreaseTrailerLayout {
5323    element: AnyElement,
5324    bounds: Bounds<Pixels>,
5325}
5326
5327struct PositionMap {
5328    size: Size<Pixels>,
5329    line_height: Pixels,
5330    scroll_pixel_position: gpui::Point<Pixels>,
5331    scroll_max: gpui::Point<f32>,
5332    em_width: Pixels,
5333    em_advance: Pixels,
5334    line_layouts: Vec<LineWithInvisibles>,
5335    snapshot: EditorSnapshot,
5336}
5337
5338#[derive(Debug, Copy, Clone)]
5339pub struct PointForPosition {
5340    pub previous_valid: DisplayPoint,
5341    pub next_valid: DisplayPoint,
5342    pub exact_unclipped: DisplayPoint,
5343    pub column_overshoot_after_line_end: u32,
5344}
5345
5346impl PointForPosition {
5347    pub fn as_valid(&self) -> Option<DisplayPoint> {
5348        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
5349            Some(self.previous_valid)
5350        } else {
5351            None
5352        }
5353    }
5354}
5355
5356impl PositionMap {
5357    fn point_for_position(
5358        &self,
5359        text_bounds: Bounds<Pixels>,
5360        position: gpui::Point<Pixels>,
5361    ) -> PointForPosition {
5362        let scroll_position = self.snapshot.scroll_position();
5363        let position = position - text_bounds.origin;
5364        let y = position.y.max(px(0.)).min(self.size.height);
5365        let x = position.x + (scroll_position.x * self.em_width);
5366        let row = ((y / self.line_height) + scroll_position.y) as u32;
5367
5368        let (column, x_overshoot_after_line_end) = if let Some(line) = self
5369            .line_layouts
5370            .get(row as usize - scroll_position.y as usize)
5371        {
5372            if let Some(ix) = line.index_for_x(x) {
5373                (ix as u32, px(0.))
5374            } else {
5375                (line.len as u32, px(0.).max(x - line.width))
5376            }
5377        } else {
5378            (0, x)
5379        };
5380
5381        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
5382        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
5383        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
5384
5385        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
5386        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
5387        PointForPosition {
5388            previous_valid,
5389            next_valid,
5390            exact_unclipped,
5391            column_overshoot_after_line_end,
5392        }
5393    }
5394}
5395
5396struct BlockLayout {
5397    row: DisplayRow,
5398    element: AnyElement,
5399    available_space: Size<AvailableSpace>,
5400    style: BlockStyle,
5401}
5402
5403fn layout_line(
5404    row: DisplayRow,
5405    snapshot: &EditorSnapshot,
5406    style: &EditorStyle,
5407    cx: &mut WindowContext,
5408) -> LineWithInvisibles {
5409    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
5410    LineWithInvisibles::from_chunks(chunks, &style.text, MAX_LINE_LEN, 1, &[], snapshot.mode, cx)
5411        .pop()
5412        .unwrap()
5413}
5414
5415#[derive(Debug)]
5416pub struct IndentGuideLayout {
5417    origin: gpui::Point<Pixels>,
5418    length: Pixels,
5419    single_indent_width: Pixels,
5420    depth: u32,
5421    active: bool,
5422    settings: IndentGuideSettings,
5423}
5424
5425pub struct CursorLayout {
5426    origin: gpui::Point<Pixels>,
5427    block_width: Pixels,
5428    line_height: Pixels,
5429    color: Hsla,
5430    shape: CursorShape,
5431    block_text: Option<ShapedLine>,
5432    cursor_name: Option<AnyElement>,
5433}
5434
5435#[derive(Debug)]
5436pub struct CursorName {
5437    string: SharedString,
5438    color: Hsla,
5439    is_top_row: bool,
5440}
5441
5442impl CursorLayout {
5443    pub fn new(
5444        origin: gpui::Point<Pixels>,
5445        block_width: Pixels,
5446        line_height: Pixels,
5447        color: Hsla,
5448        shape: CursorShape,
5449        block_text: Option<ShapedLine>,
5450    ) -> CursorLayout {
5451        CursorLayout {
5452            origin,
5453            block_width,
5454            line_height,
5455            color,
5456            shape,
5457            block_text,
5458            cursor_name: None,
5459        }
5460    }
5461
5462    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5463        Bounds {
5464            origin: self.origin + origin,
5465            size: size(self.block_width, self.line_height),
5466        }
5467    }
5468
5469    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5470        match self.shape {
5471            CursorShape::Bar => Bounds {
5472                origin: self.origin + origin,
5473                size: size(px(2.0), self.line_height),
5474            },
5475            CursorShape::Block | CursorShape::Hollow => Bounds {
5476                origin: self.origin + origin,
5477                size: size(self.block_width, self.line_height),
5478            },
5479            CursorShape::Underscore => Bounds {
5480                origin: self.origin
5481                    + origin
5482                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
5483                size: size(self.block_width, px(2.0)),
5484            },
5485        }
5486    }
5487
5488    pub fn layout(
5489        &mut self,
5490        origin: gpui::Point<Pixels>,
5491        cursor_name: Option<CursorName>,
5492        cx: &mut WindowContext,
5493    ) {
5494        if let Some(cursor_name) = cursor_name {
5495            let bounds = self.bounds(origin);
5496            let text_size = self.line_height / 1.5;
5497
5498            let name_origin = if cursor_name.is_top_row {
5499                point(bounds.right() - px(1.), bounds.top())
5500            } else {
5501                point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
5502            };
5503            let mut name_element = div()
5504                .bg(self.color)
5505                .text_size(text_size)
5506                .px_0p5()
5507                .line_height(text_size + px(2.))
5508                .text_color(cursor_name.color)
5509                .child(cursor_name.string.clone())
5510                .into_any_element();
5511
5512            name_element.prepaint_as_root(
5513                name_origin,
5514                size(AvailableSpace::MinContent, AvailableSpace::MinContent),
5515                cx,
5516            );
5517
5518            self.cursor_name = Some(name_element);
5519        }
5520    }
5521
5522    pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
5523        let bounds = self.bounds(origin);
5524
5525        //Draw background or border quad
5526        let cursor = if matches!(self.shape, CursorShape::Hollow) {
5527            outline(bounds, self.color)
5528        } else {
5529            fill(bounds, self.color)
5530        };
5531
5532        if let Some(name) = &mut self.cursor_name {
5533            name.paint(cx);
5534        }
5535
5536        cx.paint_quad(cursor);
5537
5538        if let Some(block_text) = &self.block_text {
5539            block_text
5540                .paint(self.origin + origin, self.line_height, cx)
5541                .log_err();
5542        }
5543    }
5544
5545    pub fn shape(&self) -> CursorShape {
5546        self.shape
5547    }
5548}
5549
5550#[derive(Debug)]
5551pub struct HighlightedRange {
5552    pub start_y: Pixels,
5553    pub line_height: Pixels,
5554    pub lines: Vec<HighlightedRangeLine>,
5555    pub color: Hsla,
5556    pub corner_radius: Pixels,
5557}
5558
5559#[derive(Debug)]
5560pub struct HighlightedRangeLine {
5561    pub start_x: Pixels,
5562    pub end_x: Pixels,
5563}
5564
5565impl HighlightedRange {
5566    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
5567        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
5568            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
5569            self.paint_lines(
5570                self.start_y + self.line_height,
5571                &self.lines[1..],
5572                bounds,
5573                cx,
5574            );
5575        } else {
5576            self.paint_lines(self.start_y, &self.lines, bounds, cx);
5577        }
5578    }
5579
5580    fn paint_lines(
5581        &self,
5582        start_y: Pixels,
5583        lines: &[HighlightedRangeLine],
5584        _bounds: Bounds<Pixels>,
5585        cx: &mut WindowContext,
5586    ) {
5587        if lines.is_empty() {
5588            return;
5589        }
5590
5591        let first_line = lines.first().unwrap();
5592        let last_line = lines.last().unwrap();
5593
5594        let first_top_left = point(first_line.start_x, start_y);
5595        let first_top_right = point(first_line.end_x, start_y);
5596
5597        let curve_height = point(Pixels::ZERO, self.corner_radius);
5598        let curve_width = |start_x: Pixels, end_x: Pixels| {
5599            let max = (end_x - start_x) / 2.;
5600            let width = if max < self.corner_radius {
5601                max
5602            } else {
5603                self.corner_radius
5604            };
5605
5606            point(width, Pixels::ZERO)
5607        };
5608
5609        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
5610        let mut path = gpui::Path::new(first_top_right - top_curve_width);
5611        path.curve_to(first_top_right + curve_height, first_top_right);
5612
5613        let mut iter = lines.iter().enumerate().peekable();
5614        while let Some((ix, line)) = iter.next() {
5615            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
5616
5617            if let Some((_, next_line)) = iter.peek() {
5618                let next_top_right = point(next_line.end_x, bottom_right.y);
5619
5620                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
5621                    Ordering::Equal => {
5622                        path.line_to(bottom_right);
5623                    }
5624                    Ordering::Less => {
5625                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
5626                        path.line_to(bottom_right - curve_height);
5627                        if self.corner_radius > Pixels::ZERO {
5628                            path.curve_to(bottom_right - curve_width, bottom_right);
5629                        }
5630                        path.line_to(next_top_right + curve_width);
5631                        if self.corner_radius > Pixels::ZERO {
5632                            path.curve_to(next_top_right + curve_height, next_top_right);
5633                        }
5634                    }
5635                    Ordering::Greater => {
5636                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
5637                        path.line_to(bottom_right - curve_height);
5638                        if self.corner_radius > Pixels::ZERO {
5639                            path.curve_to(bottom_right + curve_width, bottom_right);
5640                        }
5641                        path.line_to(next_top_right - curve_width);
5642                        if self.corner_radius > Pixels::ZERO {
5643                            path.curve_to(next_top_right + curve_height, next_top_right);
5644                        }
5645                    }
5646                }
5647            } else {
5648                let curve_width = curve_width(line.start_x, line.end_x);
5649                path.line_to(bottom_right - curve_height);
5650                if self.corner_radius > Pixels::ZERO {
5651                    path.curve_to(bottom_right - curve_width, bottom_right);
5652                }
5653
5654                let bottom_left = point(line.start_x, bottom_right.y);
5655                path.line_to(bottom_left + curve_width);
5656                if self.corner_radius > Pixels::ZERO {
5657                    path.curve_to(bottom_left - curve_height, bottom_left);
5658                }
5659            }
5660        }
5661
5662        if first_line.start_x > last_line.start_x {
5663            let curve_width = curve_width(last_line.start_x, first_line.start_x);
5664            let second_top_left = point(last_line.start_x, start_y + self.line_height);
5665            path.line_to(second_top_left + curve_height);
5666            if self.corner_radius > Pixels::ZERO {
5667                path.curve_to(second_top_left + curve_width, second_top_left);
5668            }
5669            let first_bottom_left = point(first_line.start_x, second_top_left.y);
5670            path.line_to(first_bottom_left - curve_width);
5671            if self.corner_radius > Pixels::ZERO {
5672                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
5673            }
5674        }
5675
5676        path.line_to(first_top_left + curve_height);
5677        if self.corner_radius > Pixels::ZERO {
5678            path.curve_to(first_top_left + top_curve_width, first_top_left);
5679        }
5680        path.line_to(first_top_right - top_curve_width);
5681
5682        cx.paint_path(path, self.color);
5683    }
5684}
5685
5686pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5687    (delta.pow(1.5) / 100.0).into()
5688}
5689
5690fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5691    (delta.pow(1.2) / 300.0).into()
5692}
5693
5694#[cfg(test)]
5695mod tests {
5696    use super::*;
5697    use crate::{
5698        display_map::{BlockDisposition, BlockProperties},
5699        editor_tests::{init_test, update_test_language_settings},
5700        Editor, MultiBuffer,
5701    };
5702    use gpui::{TestAppContext, VisualTestContext};
5703    use language::language_settings;
5704    use log::info;
5705    use std::num::NonZeroU32;
5706    use ui::Context;
5707    use util::test::sample_text;
5708
5709    #[gpui::test]
5710    fn test_shape_line_numbers(cx: &mut TestAppContext) {
5711        init_test(cx, |_| {});
5712        let window = cx.add_window(|cx| {
5713            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
5714            Editor::new(EditorMode::Full, buffer, None, true, cx)
5715        });
5716
5717        let editor = window.root(cx).unwrap();
5718        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5719        let element = EditorElement::new(&editor, style);
5720        let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
5721
5722        let layouts = cx
5723            .update_window(*window, |_, cx| {
5724                element.layout_line_numbers(
5725                    DisplayRow(0)..DisplayRow(6),
5726                    (0..6).map(MultiBufferRow).map(Some),
5727                    &Default::default(),
5728                    Some(DisplayPoint::new(DisplayRow(0), 0)),
5729                    &snapshot,
5730                    cx,
5731                )
5732            })
5733            .unwrap();
5734        assert_eq!(layouts.len(), 6);
5735
5736        let relative_rows = window
5737            .update(cx, |editor, cx| {
5738                let snapshot = editor.snapshot(cx);
5739                element.calculate_relative_line_numbers(
5740                    &snapshot,
5741                    &(DisplayRow(0)..DisplayRow(6)),
5742                    Some(DisplayRow(3)),
5743                )
5744            })
5745            .unwrap();
5746        assert_eq!(relative_rows[&DisplayRow(0)], 3);
5747        assert_eq!(relative_rows[&DisplayRow(1)], 2);
5748        assert_eq!(relative_rows[&DisplayRow(2)], 1);
5749        // current line has no relative number
5750        assert_eq!(relative_rows[&DisplayRow(4)], 1);
5751        assert_eq!(relative_rows[&DisplayRow(5)], 2);
5752
5753        // works if cursor is before screen
5754        let relative_rows = window
5755            .update(cx, |editor, cx| {
5756                let snapshot = editor.snapshot(cx);
5757                element.calculate_relative_line_numbers(
5758                    &snapshot,
5759                    &(DisplayRow(3)..DisplayRow(6)),
5760                    Some(DisplayRow(1)),
5761                )
5762            })
5763            .unwrap();
5764        assert_eq!(relative_rows.len(), 3);
5765        assert_eq!(relative_rows[&DisplayRow(3)], 2);
5766        assert_eq!(relative_rows[&DisplayRow(4)], 3);
5767        assert_eq!(relative_rows[&DisplayRow(5)], 4);
5768
5769        // works if cursor is after screen
5770        let relative_rows = window
5771            .update(cx, |editor, cx| {
5772                let snapshot = editor.snapshot(cx);
5773                element.calculate_relative_line_numbers(
5774                    &snapshot,
5775                    &(DisplayRow(0)..DisplayRow(3)),
5776                    Some(DisplayRow(6)),
5777                )
5778            })
5779            .unwrap();
5780        assert_eq!(relative_rows.len(), 3);
5781        assert_eq!(relative_rows[&DisplayRow(0)], 5);
5782        assert_eq!(relative_rows[&DisplayRow(1)], 4);
5783        assert_eq!(relative_rows[&DisplayRow(2)], 3);
5784    }
5785
5786    #[gpui::test]
5787    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
5788        init_test(cx, |_| {});
5789
5790        let window = cx.add_window(|cx| {
5791            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
5792            Editor::new(EditorMode::Full, buffer, None, true, cx)
5793        });
5794        let cx = &mut VisualTestContext::from_window(*window, cx);
5795        let editor = window.root(cx).unwrap();
5796        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5797
5798        window
5799            .update(cx, |editor, cx| {
5800                editor.cursor_shape = CursorShape::Block;
5801                editor.change_selections(None, cx, |s| {
5802                    s.select_ranges([
5803                        Point::new(0, 0)..Point::new(1, 0),
5804                        Point::new(3, 2)..Point::new(3, 3),
5805                        Point::new(5, 6)..Point::new(6, 0),
5806                    ]);
5807                });
5808            })
5809            .unwrap();
5810
5811        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5812            EditorElement::new(&editor, style)
5813        });
5814
5815        assert_eq!(state.selections.len(), 1);
5816        let local_selections = &state.selections[0].1;
5817        assert_eq!(local_selections.len(), 3);
5818        // moves cursor back one line
5819        assert_eq!(
5820            local_selections[0].head,
5821            DisplayPoint::new(DisplayRow(0), 6)
5822        );
5823        assert_eq!(
5824            local_selections[0].range,
5825            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
5826        );
5827
5828        // moves cursor back one column
5829        assert_eq!(
5830            local_selections[1].range,
5831            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
5832        );
5833        assert_eq!(
5834            local_selections[1].head,
5835            DisplayPoint::new(DisplayRow(3), 2)
5836        );
5837
5838        // leaves cursor on the max point
5839        assert_eq!(
5840            local_selections[2].range,
5841            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
5842        );
5843        assert_eq!(
5844            local_selections[2].head,
5845            DisplayPoint::new(DisplayRow(6), 0)
5846        );
5847
5848        // active lines does not include 1 (even though the range of the selection does)
5849        assert_eq!(
5850            state.active_rows.keys().cloned().collect::<Vec<_>>(),
5851            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
5852        );
5853
5854        // multi-buffer support
5855        // in DisplayPoint coordinates, this is what we're dealing with:
5856        //  0: [[file
5857        //  1:   header
5858        //  2:   section]]
5859        //  3: aaaaaa
5860        //  4: bbbbbb
5861        //  5: cccccc
5862        //  6:
5863        //  7: [[footer]]
5864        //  8: [[header]]
5865        //  9: ffffff
5866        // 10: gggggg
5867        // 11: hhhhhh
5868        // 12:
5869        // 13: [[footer]]
5870        // 14: [[file
5871        // 15:   header
5872        // 16:   section]]
5873        // 17: bbbbbb
5874        // 18: cccccc
5875        // 19: dddddd
5876        // 20: [[footer]]
5877        let window = cx.add_window(|cx| {
5878            let buffer = MultiBuffer::build_multi(
5879                [
5880                    (
5881                        &(sample_text(8, 6, 'a') + "\n"),
5882                        vec![
5883                            Point::new(0, 0)..Point::new(3, 0),
5884                            Point::new(4, 0)..Point::new(7, 0),
5885                        ],
5886                    ),
5887                    (
5888                        &(sample_text(8, 6, 'a') + "\n"),
5889                        vec![Point::new(1, 0)..Point::new(3, 0)],
5890                    ),
5891                ],
5892                cx,
5893            );
5894            Editor::new(EditorMode::Full, buffer, None, true, cx)
5895        });
5896        let editor = window.root(cx).unwrap();
5897        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5898        let _state = window.update(cx, |editor, cx| {
5899            editor.cursor_shape = CursorShape::Block;
5900            editor.change_selections(None, cx, |s| {
5901                s.select_display_ranges([
5902                    DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
5903                    DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
5904                ]);
5905            });
5906        });
5907
5908        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5909            EditorElement::new(&editor, style)
5910        });
5911        assert_eq!(state.selections.len(), 1);
5912        let local_selections = &state.selections[0].1;
5913        assert_eq!(local_selections.len(), 2);
5914
5915        // moves cursor on excerpt boundary back a line
5916        // and doesn't allow selection to bleed through
5917        assert_eq!(
5918            local_selections[0].range,
5919            DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
5920        );
5921        assert_eq!(
5922            local_selections[0].head,
5923            DisplayPoint::new(DisplayRow(6), 0)
5924        );
5925        // moves cursor on buffer boundary back two lines
5926        // and doesn't allow selection to bleed through
5927        assert_eq!(
5928            local_selections[1].range,
5929            DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
5930        );
5931        assert_eq!(
5932            local_selections[1].head,
5933            DisplayPoint::new(DisplayRow(12), 0)
5934        );
5935    }
5936
5937    #[gpui::test]
5938    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
5939        init_test(cx, |_| {});
5940
5941        let window = cx.add_window(|cx| {
5942            let buffer = MultiBuffer::build_simple("", cx);
5943            Editor::new(EditorMode::Full, buffer, None, true, cx)
5944        });
5945        let cx = &mut VisualTestContext::from_window(*window, cx);
5946        let editor = window.root(cx).unwrap();
5947        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5948        window
5949            .update(cx, |editor, cx| {
5950                editor.set_placeholder_text("hello", cx);
5951                editor.insert_blocks(
5952                    [BlockProperties {
5953                        style: BlockStyle::Fixed,
5954                        disposition: BlockDisposition::Above,
5955                        height: 3,
5956                        position: Anchor::min(),
5957                        render: Box::new(|_| div().into_any()),
5958                    }],
5959                    None,
5960                    cx,
5961                );
5962
5963                // Blur the editor so that it displays placeholder text.
5964                cx.blur();
5965            })
5966            .unwrap();
5967
5968        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5969            EditorElement::new(&editor, style)
5970        });
5971        assert_eq!(state.position_map.line_layouts.len(), 4);
5972        assert_eq!(
5973            state
5974                .line_numbers
5975                .iter()
5976                .map(Option::is_some)
5977                .collect::<Vec<_>>(),
5978            &[false, false, false, true]
5979        );
5980    }
5981
5982    #[gpui::test]
5983    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
5984        const TAB_SIZE: u32 = 4;
5985
5986        let input_text = "\t \t|\t| a b";
5987        let expected_invisibles = vec![
5988            Invisible::Tab {
5989                line_start_offset: 0,
5990                line_end_offset: TAB_SIZE as usize,
5991            },
5992            Invisible::Whitespace {
5993                line_offset: TAB_SIZE as usize,
5994            },
5995            Invisible::Tab {
5996                line_start_offset: TAB_SIZE as usize + 1,
5997                line_end_offset: TAB_SIZE as usize * 2,
5998            },
5999            Invisible::Tab {
6000                line_start_offset: TAB_SIZE as usize * 2 + 1,
6001                line_end_offset: TAB_SIZE as usize * 3,
6002            },
6003            Invisible::Whitespace {
6004                line_offset: TAB_SIZE as usize * 3 + 1,
6005            },
6006            Invisible::Whitespace {
6007                line_offset: TAB_SIZE as usize * 3 + 3,
6008            },
6009        ];
6010        assert_eq!(
6011            expected_invisibles.len(),
6012            input_text
6013                .chars()
6014                .filter(|initial_char| initial_char.is_whitespace())
6015                .count(),
6016            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6017        );
6018
6019        init_test(cx, |s| {
6020            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6021            s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
6022        });
6023
6024        let actual_invisibles =
6025            collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
6026
6027        assert_eq!(expected_invisibles, actual_invisibles);
6028    }
6029
6030    #[gpui::test]
6031    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
6032        init_test(cx, |s| {
6033            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6034            s.defaults.tab_size = NonZeroU32::new(4);
6035        });
6036
6037        for editor_mode_without_invisibles in [
6038            EditorMode::SingleLine,
6039            EditorMode::AutoHeight { max_lines: 100 },
6040        ] {
6041            let invisibles = collect_invisibles_from_new_editor(
6042                cx,
6043                editor_mode_without_invisibles,
6044                "\t\t\t| | a b",
6045                px(500.0),
6046            );
6047            assert!(invisibles.is_empty(),
6048                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
6049        }
6050    }
6051
6052    #[gpui::test]
6053    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
6054        let tab_size = 4;
6055        let input_text = "a\tbcd     ".repeat(9);
6056        let repeated_invisibles = [
6057            Invisible::Tab {
6058                line_start_offset: 1,
6059                line_end_offset: tab_size as usize,
6060            },
6061            Invisible::Whitespace {
6062                line_offset: tab_size as usize + 3,
6063            },
6064            Invisible::Whitespace {
6065                line_offset: tab_size as usize + 4,
6066            },
6067            Invisible::Whitespace {
6068                line_offset: tab_size as usize + 5,
6069            },
6070            Invisible::Whitespace {
6071                line_offset: tab_size as usize + 6,
6072            },
6073            Invisible::Whitespace {
6074                line_offset: tab_size as usize + 7,
6075            },
6076        ];
6077        let expected_invisibles = std::iter::once(repeated_invisibles)
6078            .cycle()
6079            .take(9)
6080            .flatten()
6081            .collect::<Vec<_>>();
6082        assert_eq!(
6083            expected_invisibles.len(),
6084            input_text
6085                .chars()
6086                .filter(|initial_char| initial_char.is_whitespace())
6087                .count(),
6088            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6089        );
6090        info!("Expected invisibles: {expected_invisibles:?}");
6091
6092        init_test(cx, |_| {});
6093
6094        // Put the same string with repeating whitespace pattern into editors of various size,
6095        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
6096        let resize_step = 10.0;
6097        let mut editor_width = 200.0;
6098        while editor_width <= 1000.0 {
6099            update_test_language_settings(cx, |s| {
6100                s.defaults.tab_size = NonZeroU32::new(tab_size);
6101                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6102                s.defaults.preferred_line_length = Some(editor_width as u32);
6103                s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
6104            });
6105
6106            let actual_invisibles = collect_invisibles_from_new_editor(
6107                cx,
6108                EditorMode::Full,
6109                &input_text,
6110                px(editor_width),
6111            );
6112
6113            // Whatever the editor size is, ensure it has the same invisible kinds in the same order
6114            // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
6115            let mut i = 0;
6116            for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
6117                i = actual_index;
6118                match expected_invisibles.get(i) {
6119                    Some(expected_invisible) => match (expected_invisible, actual_invisible) {
6120                        (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
6121                        | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
6122                        _ => {
6123                            panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
6124                        }
6125                    },
6126                    None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
6127                }
6128            }
6129            let missing_expected_invisibles = &expected_invisibles[i + 1..];
6130            assert!(
6131                missing_expected_invisibles.is_empty(),
6132                "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
6133            );
6134
6135            editor_width += resize_step;
6136        }
6137    }
6138
6139    fn collect_invisibles_from_new_editor(
6140        cx: &mut TestAppContext,
6141        editor_mode: EditorMode,
6142        input_text: &str,
6143        editor_width: Pixels,
6144    ) -> Vec<Invisible> {
6145        info!(
6146            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
6147            editor_width.0
6148        );
6149        let window = cx.add_window(|cx| {
6150            let buffer = MultiBuffer::build_simple(&input_text, cx);
6151            Editor::new(editor_mode, buffer, None, true, cx)
6152        });
6153        let cx = &mut VisualTestContext::from_window(*window, cx);
6154        let editor = window.root(cx).unwrap();
6155        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6156        window
6157            .update(cx, |editor, cx| {
6158                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
6159                editor.set_wrap_width(Some(editor_width), cx);
6160            })
6161            .unwrap();
6162        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6163            EditorElement::new(&editor, style)
6164        });
6165        state
6166            .position_map
6167            .line_layouts
6168            .iter()
6169            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
6170            .cloned()
6171            .collect()
6172    }
6173}
6174
6175pub fn register_action<T: Action>(
6176    view: &View<Editor>,
6177    cx: &mut WindowContext,
6178    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
6179) {
6180    let view = view.clone();
6181    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
6182        let action = action.downcast_ref().unwrap();
6183        if phase == DispatchPhase::Bubble {
6184            view.update(cx, |editor, cx| {
6185                listener(editor, action, cx);
6186            })
6187        }
6188    })
6189}
6190
6191fn compute_auto_height_layout(
6192    editor: &mut Editor,
6193    max_lines: usize,
6194    max_line_number_width: Pixels,
6195    known_dimensions: Size<Option<Pixels>>,
6196    available_width: AvailableSpace,
6197    cx: &mut ViewContext<Editor>,
6198) -> Option<Size<Pixels>> {
6199    let width = known_dimensions.width.or_else(|| {
6200        if let AvailableSpace::Definite(available_width) = available_width {
6201            Some(available_width)
6202        } else {
6203            None
6204        }
6205    })?;
6206    if let Some(height) = known_dimensions.height {
6207        return Some(size(width, height));
6208    }
6209
6210    let style = editor.style.as_ref().unwrap();
6211    let font_id = cx.text_system().resolve_font(&style.text.font());
6212    let font_size = style.text.font_size.to_pixels(cx.rem_size());
6213    let line_height = style.text.line_height_in_pixels(cx.rem_size());
6214    let em_width = cx
6215        .text_system()
6216        .typographic_bounds(font_id, font_size, 'm')
6217        .unwrap()
6218        .size
6219        .width;
6220
6221    let mut snapshot = editor.snapshot(cx);
6222    let gutter_dimensions =
6223        snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
6224
6225    editor.gutter_dimensions = gutter_dimensions;
6226    let text_width = width - gutter_dimensions.width;
6227    let overscroll = size(em_width, px(0.));
6228
6229    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
6230    if editor.set_wrap_width(Some(editor_width), cx) {
6231        snapshot = editor.snapshot(cx);
6232    }
6233
6234    let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
6235    let height = scroll_height
6236        .max(line_height)
6237        .min(line_height * max_lines as f32);
6238
6239    Some(size(width, height))
6240}