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