element.rs

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