element.rs

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