element.rs

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