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        // Offset the content_bounds from the text_bounds by the gutter margin (which is roughly half a character wide) to make hit testing work more like how we want.
 898        let content_origin =
 899            text_bounds.origin + point(layout.gutter_dimensions.margin, Pixels::ZERO);
 900        let line_end_overshoot = 0.15 * layout.position_map.line_height;
 901        let whitespace_setting = self
 902            .editor
 903            .read(cx)
 904            .buffer
 905            .read(cx)
 906            .settings_at(0, cx)
 907            .show_whitespaces;
 908
 909        cx.with_content_mask(
 910            Some(ContentMask {
 911                bounds: text_bounds,
 912            }),
 913            |cx| {
 914                let interactive_text_bounds = InteractiveBounds {
 915                    bounds: text_bounds,
 916                    stacking_order: cx.stacking_order().clone(),
 917                };
 918                if interactive_text_bounds.visibly_contains(&cx.mouse_position(), cx) {
 919                    if self
 920                        .editor
 921                        .read(cx)
 922                        .hovered_link_state
 923                        .as_ref()
 924                        .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
 925                    {
 926                        cx.set_cursor_style(CursorStyle::PointingHand);
 927                    } else {
 928                        cx.set_cursor_style(CursorStyle::IBeam);
 929                    }
 930                }
 931
 932                let fold_corner_radius = 0.15 * layout.position_map.line_height;
 933                cx.with_element_id(Some("folds"), |cx| {
 934                    let snapshot = &layout.position_map.snapshot;
 935
 936                    for fold in snapshot.folds_in_range(layout.visible_anchor_range.clone()) {
 937                        let fold_range = fold.range.clone();
 938                        let display_range = fold.range.start.to_display_point(&snapshot)
 939                            ..fold.range.end.to_display_point(&snapshot);
 940                        debug_assert_eq!(display_range.start.row(), display_range.end.row());
 941                        let row = display_range.start.row();
 942                        debug_assert!(row < layout.visible_display_row_range.end);
 943                        let Some(line_layout) = &layout
 944                            .position_map
 945                            .line_layouts
 946                            .get((row - layout.visible_display_row_range.start) as usize)
 947                            .map(|l| &l.line)
 948                        else {
 949                            continue;
 950                        };
 951
 952                        let start_x = content_origin.x
 953                            + line_layout.x_for_index(display_range.start.column() as usize)
 954                            - layout.position_map.scroll_position.x;
 955                        let start_y = content_origin.y
 956                            + row as f32 * layout.position_map.line_height
 957                            - layout.position_map.scroll_position.y;
 958                        let end_x = content_origin.x
 959                            + line_layout.x_for_index(display_range.end.column() as usize)
 960                            - layout.position_map.scroll_position.x;
 961
 962                        let fold_bounds = Bounds {
 963                            origin: point(start_x, start_y),
 964                            size: size(end_x - start_x, layout.position_map.line_height),
 965                        };
 966
 967                        let fold_background = cx.with_z_index(1, |cx| {
 968                            div()
 969                                .id(fold.id)
 970                                .size_full()
 971                                .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 972                                .on_click(cx.listener_for(
 973                                    &self.editor,
 974                                    move |editor: &mut Editor, _, cx| {
 975                                        editor.unfold_ranges(
 976                                            [fold_range.start..fold_range.end],
 977                                            true,
 978                                            false,
 979                                            cx,
 980                                        );
 981                                        cx.stop_propagation();
 982                                    },
 983                                ))
 984                                .draw_and_update_state(
 985                                    fold_bounds.origin,
 986                                    fold_bounds.size,
 987                                    cx,
 988                                    |fold_element_state, cx| {
 989                                        if fold_element_state.is_active() {
 990                                            cx.theme().colors().ghost_element_active
 991                                        } else if fold_bounds.contains(&cx.mouse_position()) {
 992                                            cx.theme().colors().ghost_element_hover
 993                                        } else {
 994                                            cx.theme().colors().ghost_element_background
 995                                        }
 996                                    },
 997                                )
 998                        });
 999
1000                        self.paint_highlighted_range(
1001                            display_range.clone(),
1002                            fold_background,
1003                            fold_corner_radius,
1004                            fold_corner_radius * 2.,
1005                            layout,
1006                            content_origin,
1007                            text_bounds,
1008                            cx,
1009                        );
1010                    }
1011                });
1012
1013                for (range, color) in &layout.highlighted_ranges {
1014                    self.paint_highlighted_range(
1015                        range.clone(),
1016                        *color,
1017                        Pixels::ZERO,
1018                        line_end_overshoot,
1019                        layout,
1020                        content_origin,
1021                        text_bounds,
1022                        cx,
1023                    );
1024                }
1025
1026                let mut cursors = SmallVec::<[Cursor; 32]>::new();
1027                let corner_radius = 0.15 * layout.position_map.line_height;
1028                let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
1029
1030                for (participant_ix, (player_color, selections)) in
1031                    layout.selections.iter().enumerate()
1032                {
1033                    for selection in selections.into_iter() {
1034                        self.paint_highlighted_range(
1035                            selection.range.clone(),
1036                            player_color.selection,
1037                            corner_radius,
1038                            corner_radius * 2.,
1039                            layout,
1040                            content_origin,
1041                            text_bounds,
1042                            cx,
1043                        );
1044
1045                        if selection.is_local && !selection.range.is_empty() {
1046                            invisible_display_ranges.push(selection.range.clone());
1047                        }
1048
1049                        if !selection.is_local || self.editor.read(cx).show_local_cursors(cx) {
1050                            let cursor_position = selection.head;
1051                            if layout
1052                                .visible_display_row_range
1053                                .contains(&cursor_position.row())
1054                            {
1055                                let cursor_row_layout = &layout.position_map.line_layouts
1056                                    [(cursor_position.row() - start_row) as usize]
1057                                    .line;
1058                                let cursor_column = cursor_position.column() as usize;
1059
1060                                let cursor_character_x =
1061                                    cursor_row_layout.x_for_index(cursor_column);
1062                                let mut block_width = cursor_row_layout
1063                                    .x_for_index(cursor_column + 1)
1064                                    - cursor_character_x;
1065                                if block_width == Pixels::ZERO {
1066                                    block_width = layout.position_map.em_width;
1067                                }
1068                                let block_text = if let CursorShape::Block = selection.cursor_shape
1069                                {
1070                                    layout
1071                                        .position_map
1072                                        .snapshot
1073                                        .chars_at(cursor_position)
1074                                        .next()
1075                                        .and_then(|(character, _)| {
1076                                            let text = if character == '\n' {
1077                                                SharedString::from(" ")
1078                                            } else {
1079                                                SharedString::from(character.to_string())
1080                                            };
1081                                            let len = text.len();
1082                                            cx.text_system()
1083                                                .shape_line(
1084                                                    text,
1085                                                    cursor_row_layout.font_size,
1086                                                    &[TextRun {
1087                                                        len,
1088                                                        font: self.style.text.font(),
1089                                                        color: self.style.background,
1090                                                        background_color: None,
1091                                                        strikethrough: None,
1092                                                        underline: None,
1093                                                    }],
1094                                                )
1095                                                .log_err()
1096                                        })
1097                                } else {
1098                                    None
1099                                };
1100
1101                                let x = cursor_character_x - layout.position_map.scroll_position.x;
1102                                let y = cursor_position.row() as f32
1103                                    * layout.position_map.line_height
1104                                    - layout.position_map.scroll_position.y;
1105                                if selection.is_newest {
1106                                    self.editor.update(cx, |editor, _| {
1107                                        editor.pixel_position_of_newest_cursor = Some(point(
1108                                            text_bounds.origin.x + x + block_width / 2.,
1109                                            text_bounds.origin.y
1110                                                + y
1111                                                + layout.position_map.line_height / 2.,
1112                                        ))
1113                                    });
1114                                }
1115
1116                                cursors.push(Cursor {
1117                                    color: player_color.cursor,
1118                                    block_width,
1119                                    origin: point(x, y),
1120                                    line_height: layout.position_map.line_height,
1121                                    shape: selection.cursor_shape,
1122                                    block_text,
1123                                    cursor_name: selection.user_name.clone().map(|name| {
1124                                        CursorName {
1125                                            string: name,
1126                                            color: self.style.background,
1127                                            is_top_row: cursor_position.row() == 0,
1128                                            z_index: (participant_ix % 256).try_into().unwrap(),
1129                                        }
1130                                    }),
1131                                });
1132                            }
1133                        }
1134                    }
1135                }
1136
1137                for (ix, line_with_invisibles) in
1138                    layout.position_map.line_layouts.iter().enumerate()
1139                {
1140                    let row = start_row + ix as u32;
1141                    line_with_invisibles.draw(
1142                        layout,
1143                        row,
1144                        content_origin,
1145                        whitespace_setting,
1146                        &invisible_display_ranges,
1147                        cx,
1148                    )
1149                }
1150
1151                cx.with_z_index(0, |cx| self.paint_redactions(text_bounds, &layout, cx));
1152
1153                cx.with_z_index(1, |cx| {
1154                    for cursor in cursors {
1155                        cursor.paint(content_origin, cx);
1156                    }
1157                });
1158            },
1159        )
1160    }
1161
1162    fn paint_redactions(
1163        &mut self,
1164        text_bounds: Bounds<Pixels>,
1165        layout: &LayoutState,
1166        cx: &mut ElementContext,
1167    ) {
1168        let content_origin =
1169            text_bounds.origin + point(layout.gutter_dimensions.margin, Pixels::ZERO);
1170        let line_end_overshoot = layout.line_end_overshoot();
1171
1172        // A softer than perfect black
1173        let redaction_color = gpui::rgb(0x0e1111);
1174
1175        for range in layout.redacted_ranges.iter() {
1176            self.paint_highlighted_range(
1177                range.clone(),
1178                redaction_color.into(),
1179                Pixels::ZERO,
1180                line_end_overshoot,
1181                layout,
1182                content_origin,
1183                text_bounds,
1184                cx,
1185            );
1186        }
1187    }
1188
1189    fn paint_overlays(
1190        &mut self,
1191        text_bounds: Bounds<Pixels>,
1192        layout: &mut LayoutState,
1193        cx: &mut ElementContext,
1194    ) {
1195        let content_origin =
1196            text_bounds.origin + point(layout.gutter_dimensions.margin, Pixels::ZERO);
1197        let start_row = layout.visible_display_row_range.start;
1198        if let Some((position, mut context_menu)) = layout.context_menu.take() {
1199            let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1200            let context_menu_size = context_menu.measure(available_space, cx);
1201
1202            let cursor_row_layout =
1203                &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
1204            let x = cursor_row_layout.x_for_index(position.column() as usize)
1205                - layout.position_map.scroll_position.x;
1206            let y = (position.row() + 1) as f32 * layout.position_map.line_height
1207                - layout.position_map.scroll_position.y;
1208            let mut list_origin = content_origin + point(x, y);
1209            let list_width = context_menu_size.width;
1210            let list_height = context_menu_size.height;
1211
1212            // Snap the right edge of the list to the right edge of the window if
1213            // its horizontal bounds overflow.
1214            if list_origin.x + list_width > cx.viewport_size().width {
1215                list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
1216            }
1217
1218            if list_origin.y + list_height > text_bounds.lower_right().y {
1219                list_origin.y -= layout.position_map.line_height + list_height;
1220            }
1221
1222            cx.break_content_mask(|cx| context_menu.draw(list_origin, available_space, cx));
1223        }
1224
1225        if let Some((position, mut hover_popovers)) = layout.hover_popovers.take() {
1226            let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1227
1228            // This is safe because we check on layout whether the required row is available
1229            let hovered_row_layout =
1230                &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
1231
1232            // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
1233            // height. This is the size we will use to decide whether to render popovers above or below
1234            // the hovered line.
1235            let first_size = hover_popovers[0].measure(available_space, cx);
1236            let height_to_reserve =
1237                first_size.height + 1.5 * MIN_POPOVER_LINE_HEIGHT * layout.position_map.line_height;
1238
1239            // Compute Hovered Point
1240            let x = hovered_row_layout.x_for_index(position.column() as usize)
1241                - layout.position_map.scroll_position.x;
1242            let y = position.row() as f32 * layout.position_map.line_height
1243                - layout.position_map.scroll_position.y;
1244            let hovered_point = content_origin + point(x, y);
1245
1246            if hovered_point.y - height_to_reserve > Pixels::ZERO {
1247                // There is enough space above. Render popovers above the hovered point
1248                let mut current_y = hovered_point.y;
1249                for mut hover_popover in hover_popovers {
1250                    let size = hover_popover.measure(available_space, cx);
1251                    let mut popover_origin = point(hovered_point.x, current_y - size.height);
1252
1253                    let x_out_of_bounds =
1254                        text_bounds.upper_right().x - (popover_origin.x + size.width);
1255                    if x_out_of_bounds < Pixels::ZERO {
1256                        popover_origin.x = popover_origin.x + x_out_of_bounds;
1257                    }
1258
1259                    if cx.was_top_layer(&popover_origin, cx.stacking_order()) {
1260                        cx.break_content_mask(|cx| {
1261                            hover_popover.draw(popover_origin, available_space, cx)
1262                        });
1263                    }
1264
1265                    current_y = popover_origin.y - HOVER_POPOVER_GAP;
1266                }
1267            } else {
1268                // There is not enough space above. Render popovers below the hovered point
1269                let mut current_y = hovered_point.y + layout.position_map.line_height;
1270                for mut hover_popover in hover_popovers {
1271                    let size = hover_popover.measure(available_space, cx);
1272                    let mut popover_origin = point(hovered_point.x, current_y);
1273
1274                    let x_out_of_bounds =
1275                        text_bounds.upper_right().x - (popover_origin.x + size.width);
1276                    if x_out_of_bounds < Pixels::ZERO {
1277                        popover_origin.x = popover_origin.x + x_out_of_bounds;
1278                    }
1279
1280                    hover_popover.draw(popover_origin, available_space, cx);
1281
1282                    current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
1283                }
1284            }
1285        }
1286
1287        if let Some(mouse_context_menu) = self.editor.read(cx).mouse_context_menu.as_ref() {
1288            let element = overlay()
1289                .position(mouse_context_menu.position)
1290                .child(mouse_context_menu.context_menu.clone())
1291                .anchor(AnchorCorner::TopLeft)
1292                .snap_to_window();
1293            element.into_any().draw(
1294                gpui::Point::default(),
1295                size(AvailableSpace::MinContent, AvailableSpace::MinContent),
1296                cx,
1297            );
1298        }
1299    }
1300
1301    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
1302        bounds.upper_right().x - self.style.scrollbar_width
1303    }
1304
1305    fn paint_scrollbar(
1306        &mut self,
1307        bounds: Bounds<Pixels>,
1308        layout: &mut LayoutState,
1309        cx: &mut ElementContext,
1310    ) {
1311        if layout.mode != EditorMode::Full {
1312            return;
1313        }
1314
1315        // If a drag took place after we started dragging the scrollbar,
1316        // cancel the scrollbar drag.
1317        if cx.has_active_drag() {
1318            self.editor.update(cx, |editor, cx| {
1319                editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
1320            });
1321        }
1322
1323        let top = bounds.origin.y;
1324        let bottom = bounds.lower_left().y;
1325        let right = bounds.lower_right().x;
1326        let left = self.scrollbar_left(&bounds);
1327        let row_range = layout.scrollbar_row_range.clone();
1328        let max_row = layout.max_row as f32 + (row_range.end - row_range.start);
1329
1330        let mut height = bounds.size.height;
1331        let mut first_row_y_offset = px(0.0);
1332
1333        // Impose a minimum height on the scrollbar thumb
1334        let row_height = height / max_row;
1335        let min_thumb_height = layout.position_map.line_height;
1336        let thumb_height = (row_range.end - row_range.start) * row_height;
1337        if thumb_height < min_thumb_height {
1338            first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
1339            height -= min_thumb_height - thumb_height;
1340        }
1341
1342        let y_for_row = |row: f32| -> Pixels { top + first_row_y_offset + row * row_height };
1343
1344        let thumb_top = y_for_row(row_range.start) - first_row_y_offset;
1345        let thumb_bottom = y_for_row(row_range.end) + first_row_y_offset;
1346        let track_bounds = Bounds::from_corners(point(left, top), point(right, bottom));
1347        let thumb_bounds = Bounds::from_corners(point(left, thumb_top), point(right, thumb_bottom));
1348
1349        if layout.show_scrollbars {
1350            cx.paint_quad(quad(
1351                track_bounds,
1352                Corners::default(),
1353                cx.theme().colors().scrollbar_track_background,
1354                Edges {
1355                    top: Pixels::ZERO,
1356                    right: Pixels::ZERO,
1357                    bottom: Pixels::ZERO,
1358                    left: px(1.),
1359                },
1360                cx.theme().colors().scrollbar_track_border,
1361            ));
1362            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
1363            if layout.is_singleton && scrollbar_settings.selections {
1364                let start_anchor = Anchor::min();
1365                let end_anchor = Anchor::max();
1366                let background_ranges = self
1367                    .editor
1368                    .read(cx)
1369                    .background_highlight_row_ranges::<BufferSearchHighlights>(
1370                        start_anchor..end_anchor,
1371                        &layout.position_map.snapshot,
1372                        50000,
1373                    );
1374                for range in background_ranges {
1375                    let start_y = y_for_row(range.start().row() as f32);
1376                    let mut end_y = y_for_row(range.end().row() as f32);
1377                    if end_y - start_y < px(1.) {
1378                        end_y = start_y + px(1.);
1379                    }
1380                    let bounds = Bounds::from_corners(point(left, start_y), point(right, end_y));
1381                    cx.paint_quad(quad(
1382                        bounds,
1383                        Corners::default(),
1384                        cx.theme().status().info,
1385                        Edges {
1386                            top: Pixels::ZERO,
1387                            right: px(1.),
1388                            bottom: Pixels::ZERO,
1389                            left: px(1.),
1390                        },
1391                        cx.theme().colors().scrollbar_thumb_border,
1392                    ));
1393                }
1394            }
1395
1396            if layout.is_singleton && scrollbar_settings.symbols_selections {
1397                let selection_ranges = self.editor.read(cx).background_highlights_in_range(
1398                    Anchor::min()..Anchor::max(),
1399                    &layout.position_map.snapshot,
1400                    cx.theme().colors(),
1401                );
1402                for hunk in selection_ranges {
1403                    let start_display = Point::new(hunk.0.start.row(), 0)
1404                        .to_display_point(&layout.position_map.snapshot.display_snapshot);
1405                    let end_display = Point::new(hunk.0.end.row(), 0)
1406                        .to_display_point(&layout.position_map.snapshot.display_snapshot);
1407                    let start_y = y_for_row(start_display.row() as f32);
1408                    let mut end_y = if hunk.0.start == hunk.0.end {
1409                        y_for_row((end_display.row() + 1) as f32)
1410                    } else {
1411                        y_for_row((end_display.row()) as f32)
1412                    };
1413
1414                    if end_y - start_y < px(1.) {
1415                        end_y = start_y + px(1.);
1416                    }
1417                    let bounds = Bounds::from_corners(point(left, start_y), point(right, end_y));
1418
1419                    cx.paint_quad(quad(
1420                        bounds,
1421                        Corners::default(),
1422                        cx.theme().status().info,
1423                        Edges {
1424                            top: Pixels::ZERO,
1425                            right: px(1.),
1426                            bottom: Pixels::ZERO,
1427                            left: px(1.),
1428                        },
1429                        cx.theme().colors().scrollbar_thumb_border,
1430                    ));
1431                }
1432            }
1433
1434            if layout.is_singleton && scrollbar_settings.git_diff {
1435                for hunk in layout
1436                    .position_map
1437                    .snapshot
1438                    .buffer_snapshot
1439                    .git_diff_hunks_in_range(0..(max_row.floor() as u32))
1440                {
1441                    let start_display = Point::new(hunk.buffer_range.start, 0)
1442                        .to_display_point(&layout.position_map.snapshot.display_snapshot);
1443                    let end_display = Point::new(hunk.buffer_range.end, 0)
1444                        .to_display_point(&layout.position_map.snapshot.display_snapshot);
1445                    let start_y = y_for_row(start_display.row() as f32);
1446                    let mut end_y = if hunk.buffer_range.start == hunk.buffer_range.end {
1447                        y_for_row((end_display.row() + 1) as f32)
1448                    } else {
1449                        y_for_row((end_display.row()) as f32)
1450                    };
1451
1452                    if end_y - start_y < px(1.) {
1453                        end_y = start_y + px(1.);
1454                    }
1455                    let bounds = Bounds::from_corners(point(left, start_y), point(right, end_y));
1456
1457                    let color = match hunk.status() {
1458                        DiffHunkStatus::Added => cx.theme().status().created,
1459                        DiffHunkStatus::Modified => cx.theme().status().modified,
1460                        DiffHunkStatus::Removed => cx.theme().status().deleted,
1461                    };
1462                    cx.paint_quad(quad(
1463                        bounds,
1464                        Corners::default(),
1465                        color,
1466                        Edges {
1467                            top: Pixels::ZERO,
1468                            right: px(1.),
1469                            bottom: Pixels::ZERO,
1470                            left: px(1.),
1471                        },
1472                        cx.theme().colors().scrollbar_thumb_border,
1473                    ));
1474                }
1475            }
1476
1477            if layout.is_singleton && scrollbar_settings.diagnostics {
1478                let max_point = layout
1479                    .position_map
1480                    .snapshot
1481                    .display_snapshot
1482                    .buffer_snapshot
1483                    .max_point();
1484
1485                let diagnostics = layout
1486                    .position_map
1487                    .snapshot
1488                    .buffer_snapshot
1489                    .diagnostics_in_range::<_, Point>(Point::zero()..max_point, false)
1490                    // We want to sort by severity, in order to paint the most severe diagnostics last.
1491                    .sorted_by_key(|diagnostic| std::cmp::Reverse(diagnostic.diagnostic.severity));
1492
1493                for diagnostic in diagnostics {
1494                    let start_display = diagnostic
1495                        .range
1496                        .start
1497                        .to_display_point(&layout.position_map.snapshot.display_snapshot);
1498                    let end_display = diagnostic
1499                        .range
1500                        .end
1501                        .to_display_point(&layout.position_map.snapshot.display_snapshot);
1502                    let start_y = y_for_row(start_display.row() as f32);
1503                    let mut end_y = if diagnostic.range.start == diagnostic.range.end {
1504                        y_for_row((end_display.row() + 1) as f32)
1505                    } else {
1506                        y_for_row((end_display.row()) as f32)
1507                    };
1508
1509                    if end_y - start_y < px(1.) {
1510                        end_y = start_y + px(1.);
1511                    }
1512                    let bounds = Bounds::from_corners(point(left, start_y), point(right, end_y));
1513
1514                    let color = match diagnostic.diagnostic.severity {
1515                        DiagnosticSeverity::ERROR => cx.theme().status().error,
1516                        DiagnosticSeverity::WARNING => cx.theme().status().warning,
1517                        DiagnosticSeverity::INFORMATION => cx.theme().status().info,
1518                        _ => cx.theme().status().hint,
1519                    };
1520                    cx.paint_quad(quad(
1521                        bounds,
1522                        Corners::default(),
1523                        color,
1524                        Edges {
1525                            top: Pixels::ZERO,
1526                            right: px(1.),
1527                            bottom: Pixels::ZERO,
1528                            left: px(1.),
1529                        },
1530                        cx.theme().colors().scrollbar_thumb_border,
1531                    ));
1532                }
1533            }
1534
1535            cx.paint_quad(quad(
1536                thumb_bounds,
1537                Corners::default(),
1538                cx.theme().colors().scrollbar_thumb_background,
1539                Edges {
1540                    top: Pixels::ZERO,
1541                    right: px(1.),
1542                    bottom: Pixels::ZERO,
1543                    left: px(1.),
1544                },
1545                cx.theme().colors().scrollbar_thumb_border,
1546            ));
1547        }
1548
1549        let interactive_track_bounds = InteractiveBounds {
1550            bounds: track_bounds,
1551            stacking_order: cx.stacking_order().clone(),
1552        };
1553        let mut mouse_position = cx.mouse_position();
1554        if interactive_track_bounds.visibly_contains(&mouse_position, cx) {
1555            cx.set_cursor_style(CursorStyle::Arrow);
1556        }
1557
1558        cx.on_mouse_event({
1559            let editor = self.editor.clone();
1560            move |event: &MouseMoveEvent, phase, cx| {
1561                if phase == DispatchPhase::Capture {
1562                    return;
1563                }
1564
1565                editor.update(cx, |editor, cx| {
1566                    if event.pressed_button == Some(MouseButton::Left)
1567                        && editor.scroll_manager.is_dragging_scrollbar()
1568                    {
1569                        let y = mouse_position.y;
1570                        let new_y = event.position.y;
1571                        if (track_bounds.top()..track_bounds.bottom()).contains(&y) {
1572                            let mut position = editor.scroll_position(cx);
1573                            position.y += (new_y - y) * (max_row as f32) / height;
1574                            if position.y < 0.0 {
1575                                position.y = 0.0;
1576                            }
1577                            editor.set_scroll_position(position, cx);
1578                        }
1579
1580                        mouse_position = event.position;
1581                        cx.stop_propagation();
1582                    } else {
1583                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
1584                        if interactive_track_bounds.visibly_contains(&event.position, cx) {
1585                            editor.scroll_manager.show_scrollbar(cx);
1586                        }
1587                    }
1588                })
1589            }
1590        });
1591
1592        if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
1593            cx.on_mouse_event({
1594                let editor = self.editor.clone();
1595                move |_: &MouseUpEvent, phase, cx| {
1596                    if phase == DispatchPhase::Capture {
1597                        return;
1598                    }
1599
1600                    editor.update(cx, |editor, cx| {
1601                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
1602                        cx.stop_propagation();
1603                    });
1604                }
1605            });
1606        } else {
1607            cx.on_mouse_event({
1608                let editor = self.editor.clone();
1609                move |event: &MouseDownEvent, phase, cx| {
1610                    if phase == DispatchPhase::Capture {
1611                        return;
1612                    }
1613
1614                    editor.update(cx, |editor, cx| {
1615                        if track_bounds.contains(&event.position) {
1616                            editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
1617
1618                            let y = event.position.y;
1619                            if y < thumb_top || thumb_bottom < y {
1620                                let center_row =
1621                                    ((y - top) * max_row as f32 / height).round() as u32;
1622                                let top_row = center_row
1623                                    .saturating_sub((row_range.end - row_range.start) as u32 / 2);
1624                                let mut position = editor.scroll_position(cx);
1625                                position.y = top_row as f32;
1626                                editor.set_scroll_position(position, cx);
1627                            } else {
1628                                editor.scroll_manager.show_scrollbar(cx);
1629                            }
1630
1631                            cx.stop_propagation();
1632                        }
1633                    });
1634                }
1635            });
1636        }
1637    }
1638
1639    #[allow(clippy::too_many_arguments)]
1640    fn paint_highlighted_range(
1641        &self,
1642        range: Range<DisplayPoint>,
1643        color: Hsla,
1644        corner_radius: Pixels,
1645        line_end_overshoot: Pixels,
1646        layout: &LayoutState,
1647        content_origin: gpui::Point<Pixels>,
1648        bounds: Bounds<Pixels>,
1649        cx: &mut ElementContext,
1650    ) {
1651        let start_row = layout.visible_display_row_range.start;
1652        let end_row = layout.visible_display_row_range.end;
1653        if range.start != range.end {
1654            let row_range = if range.end.column() == 0 {
1655                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
1656            } else {
1657                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
1658            };
1659
1660            let highlighted_range = HighlightedRange {
1661                color,
1662                line_height: layout.position_map.line_height,
1663                corner_radius,
1664                start_y: content_origin.y
1665                    + row_range.start as f32 * layout.position_map.line_height
1666                    - layout.position_map.scroll_position.y,
1667                lines: row_range
1668                    .into_iter()
1669                    .map(|row| {
1670                        let line_layout =
1671                            &layout.position_map.line_layouts[(row - start_row) as usize].line;
1672                        HighlightedRangeLine {
1673                            start_x: if row == range.start.row() {
1674                                content_origin.x
1675                                    + line_layout.x_for_index(range.start.column() as usize)
1676                                    - layout.position_map.scroll_position.x
1677                            } else {
1678                                content_origin.x - layout.position_map.scroll_position.x
1679                            },
1680                            end_x: if row == range.end.row() {
1681                                content_origin.x
1682                                    + line_layout.x_for_index(range.end.column() as usize)
1683                                    - layout.position_map.scroll_position.x
1684                            } else {
1685                                content_origin.x + line_layout.width + line_end_overshoot
1686                                    - layout.position_map.scroll_position.x
1687                            },
1688                        }
1689                    })
1690                    .collect(),
1691            };
1692
1693            highlighted_range.paint(bounds, cx);
1694        }
1695    }
1696
1697    fn paint_blocks(
1698        &mut self,
1699        bounds: Bounds<Pixels>,
1700        layout: &mut LayoutState,
1701        cx: &mut ElementContext,
1702    ) {
1703        let scroll_position = layout.position_map.snapshot.scroll_position();
1704        let scroll_left = scroll_position.x * layout.position_map.em_width;
1705        let scroll_top = scroll_position.y * layout.position_map.line_height;
1706
1707        for mut block in layout.blocks.drain(..) {
1708            let mut origin = bounds.origin
1709                + point(
1710                    Pixels::ZERO,
1711                    block.row as f32 * layout.position_map.line_height - scroll_top,
1712                );
1713            if !matches!(block.style, BlockStyle::Sticky) {
1714                origin += point(-scroll_left, Pixels::ZERO);
1715            }
1716            block.element.draw(origin, block.available_space, cx);
1717        }
1718    }
1719
1720    fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
1721        let style = &self.style;
1722        let font_size = style.text.font_size.to_pixels(cx.rem_size());
1723        let layout = cx
1724            .text_system()
1725            .shape_line(
1726                SharedString::from(" ".repeat(column)),
1727                font_size,
1728                &[TextRun {
1729                    len: column,
1730                    font: style.text.font(),
1731                    color: Hsla::default(),
1732                    background_color: None,
1733                    underline: None,
1734                    strikethrough: None,
1735                }],
1736            )
1737            .unwrap();
1738
1739        layout.width
1740    }
1741
1742    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
1743        let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
1744        self.column_pixels(digit_count, cx)
1745    }
1746
1747    //Folds contained in a hunk are ignored apart from shrinking visual size
1748    //If a fold contains any hunks then that fold line is marked as modified
1749    fn layout_git_gutters(
1750        &self,
1751        display_rows: Range<u32>,
1752        snapshot: &EditorSnapshot,
1753    ) -> Vec<DisplayDiffHunk> {
1754        let buffer_snapshot = &snapshot.buffer_snapshot;
1755
1756        let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1757            .to_point(snapshot)
1758            .row;
1759        let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1760            .to_point(snapshot)
1761            .row;
1762
1763        buffer_snapshot
1764            .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1765            .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1766            .dedup()
1767            .collect()
1768    }
1769
1770    fn calculate_relative_line_numbers(
1771        &self,
1772        snapshot: &EditorSnapshot,
1773        rows: &Range<u32>,
1774        relative_to: Option<u32>,
1775    ) -> HashMap<u32, u32> {
1776        let mut relative_rows: HashMap<u32, u32> = Default::default();
1777        let Some(relative_to) = relative_to else {
1778            return relative_rows;
1779        };
1780
1781        let start = rows.start.min(relative_to);
1782        let end = rows.end.max(relative_to);
1783
1784        let buffer_rows = snapshot
1785            .buffer_rows(start)
1786            .take(1 + (end - start) as usize)
1787            .collect::<Vec<_>>();
1788
1789        let head_idx = relative_to - start;
1790        let mut delta = 1;
1791        let mut i = head_idx + 1;
1792        while i < buffer_rows.len() as u32 {
1793            if buffer_rows[i as usize].is_some() {
1794                if rows.contains(&(i + start)) {
1795                    relative_rows.insert(i + start, delta);
1796                }
1797                delta += 1;
1798            }
1799            i += 1;
1800        }
1801        delta = 1;
1802        i = head_idx.min(buffer_rows.len() as u32 - 1);
1803        while i > 0 && buffer_rows[i as usize].is_none() {
1804            i -= 1;
1805        }
1806
1807        while i > 0 {
1808            i -= 1;
1809            if buffer_rows[i as usize].is_some() {
1810                if rows.contains(&(i + start)) {
1811                    relative_rows.insert(i + start, delta);
1812                }
1813                delta += 1;
1814            }
1815        }
1816
1817        relative_rows
1818    }
1819
1820    fn shape_line_numbers(
1821        &self,
1822        rows: Range<u32>,
1823        active_rows: &BTreeMap<u32, bool>,
1824        newest_selection_head: DisplayPoint,
1825        is_singleton: bool,
1826        snapshot: &EditorSnapshot,
1827        cx: &ViewContext<Editor>,
1828    ) -> (
1829        Vec<Option<ShapedLine>>,
1830        Vec<Option<(FoldStatus, BufferRow, bool)>>,
1831    ) {
1832        let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1833        let include_line_numbers =
1834            EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full;
1835        let include_fold_statuses =
1836            EditorSettings::get_global(cx).gutter.folds && snapshot.mode == EditorMode::Full;
1837        let mut shaped_line_numbers = Vec::with_capacity(rows.len());
1838        let mut fold_statuses = Vec::with_capacity(rows.len());
1839        let mut line_number = String::new();
1840        let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1841        let relative_to = if is_relative {
1842            Some(newest_selection_head.row())
1843        } else {
1844            None
1845        };
1846
1847        let relative_rows = self.calculate_relative_line_numbers(&snapshot, &rows, relative_to);
1848
1849        for (ix, row) in snapshot
1850            .buffer_rows(rows.start)
1851            .take((rows.end - rows.start) as usize)
1852            .enumerate()
1853        {
1854            let display_row = rows.start + ix as u32;
1855            let (active, color) = if active_rows.contains_key(&display_row) {
1856                (true, cx.theme().colors().editor_active_line_number)
1857            } else {
1858                (false, cx.theme().colors().editor_line_number)
1859            };
1860            if let Some(buffer_row) = row {
1861                if include_line_numbers {
1862                    line_number.clear();
1863                    let default_number = buffer_row + 1;
1864                    let number = relative_rows
1865                        .get(&(ix as u32 + rows.start))
1866                        .unwrap_or(&default_number);
1867                    write!(&mut line_number, "{}", number).unwrap();
1868                    let run = TextRun {
1869                        len: line_number.len(),
1870                        font: self.style.text.font(),
1871                        color,
1872                        background_color: None,
1873                        underline: None,
1874                        strikethrough: None,
1875                    };
1876                    let shaped_line = cx
1877                        .text_system()
1878                        .shape_line(line_number.clone().into(), font_size, &[run])
1879                        .unwrap();
1880                    shaped_line_numbers.push(Some(shaped_line));
1881                }
1882                if include_fold_statuses {
1883                    fold_statuses.push(
1884                        is_singleton
1885                            .then(|| {
1886                                snapshot
1887                                    .fold_for_line(buffer_row)
1888                                    .map(|fold_status| (fold_status, buffer_row, active))
1889                            })
1890                            .flatten(),
1891                    )
1892                }
1893            } else {
1894                fold_statuses.push(None);
1895                shaped_line_numbers.push(None);
1896            }
1897        }
1898
1899        (shaped_line_numbers, fold_statuses)
1900    }
1901
1902    fn layout_lines(
1903        &self,
1904        rows: Range<u32>,
1905        line_number_layouts: &[Option<ShapedLine>],
1906        snapshot: &EditorSnapshot,
1907        cx: &mut ViewContext<Editor>,
1908    ) -> Vec<LineWithInvisibles> {
1909        if rows.start >= rows.end {
1910            return Vec::new();
1911        }
1912
1913        // Show the placeholder when the editor is empty
1914        if snapshot.is_empty() {
1915            let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1916            let placeholder_color = cx.theme().colors().text_placeholder;
1917            let placeholder_text = snapshot.placeholder_text(cx);
1918
1919            let placeholder_lines = placeholder_text
1920                .as_ref()
1921                .map_or("", AsRef::as_ref)
1922                .split('\n')
1923                .skip(rows.start as usize)
1924                .chain(iter::repeat(""))
1925                .take(rows.len());
1926            placeholder_lines
1927                .filter_map(move |line| {
1928                    let run = TextRun {
1929                        len: line.len(),
1930                        font: self.style.text.font(),
1931                        color: placeholder_color,
1932                        background_color: None,
1933                        underline: Default::default(),
1934                        strikethrough: None,
1935                    };
1936                    cx.text_system()
1937                        .shape_line(line.to_string().into(), font_size, &[run])
1938                        .log_err()
1939                })
1940                .map(|line| LineWithInvisibles {
1941                    line,
1942                    invisibles: Vec::new(),
1943                })
1944                .collect()
1945        } else {
1946            let chunks = snapshot.highlighted_chunks(rows.clone(), true, &self.style);
1947            LineWithInvisibles::from_chunks(
1948                chunks,
1949                &self.style.text,
1950                MAX_LINE_LEN,
1951                rows.len() as usize,
1952                line_number_layouts,
1953                snapshot.mode,
1954                cx,
1955            )
1956        }
1957    }
1958
1959    fn compute_layout(&mut self, bounds: Bounds<Pixels>, cx: &mut ElementContext) -> LayoutState {
1960        self.editor.update(cx, |editor, cx| {
1961            let snapshot = editor.snapshot(cx);
1962            let style = self.style.clone();
1963
1964            let font_id = cx.text_system().resolve_font(&style.text.font());
1965            let font_size = style.text.font_size.to_pixels(cx.rem_size());
1966            let line_height = style.text.line_height_in_pixels(cx.rem_size());
1967            let em_width = cx
1968                .text_system()
1969                .typographic_bounds(font_id, font_size, 'm')
1970                .unwrap()
1971                .size
1972                .width;
1973            let em_advance = cx
1974                .text_system()
1975                .advance(font_id, font_size, 'm')
1976                .unwrap()
1977                .width;
1978
1979            let gutter_dimensions = snapshot.gutter_dimensions(
1980                font_id,
1981                font_size,
1982                em_width,
1983                self.max_line_number_width(&snapshot, cx),
1984                cx,
1985            );
1986
1987            editor.gutter_width = gutter_dimensions.width;
1988
1989            let text_width = bounds.size.width - gutter_dimensions.width;
1990            let overscroll = size(em_width, px(0.));
1991            let _snapshot = {
1992                editor.set_visible_line_count((bounds.size.height / line_height).into(), cx);
1993
1994                let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
1995                let wrap_width = match editor.soft_wrap_mode(cx) {
1996                    SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
1997                    SoftWrap::EditorWidth => editor_width,
1998                    SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
1999                };
2000
2001                if editor.set_wrap_width(Some(wrap_width), cx) {
2002                    editor.snapshot(cx)
2003                } else {
2004                    snapshot
2005                }
2006            };
2007
2008            let wrap_guides = editor
2009                .wrap_guides(cx)
2010                .iter()
2011                .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
2012                .collect::<SmallVec<[_; 2]>>();
2013
2014            let gutter_size = size(gutter_dimensions.width, bounds.size.height);
2015            let text_size = size(text_width, bounds.size.height);
2016
2017            let autoscroll_horizontally =
2018                editor.autoscroll_vertically(bounds.size.height, line_height, cx);
2019            let mut snapshot = editor.snapshot(cx);
2020
2021            let scroll_position = snapshot.scroll_position();
2022            // The scroll position is a fractional point, the whole number of which represents
2023            // the top of the window in terms of display rows.
2024            let start_row = scroll_position.y as u32;
2025            let height_in_lines = f32::from(bounds.size.height / line_height);
2026            let max_row = snapshot.max_point().row();
2027
2028            // Add 1 to ensure selections bleed off screen
2029            let end_row = 1 + cmp::min((scroll_position.y + height_in_lines).ceil() as u32, max_row);
2030
2031            let start_anchor = if start_row == 0 {
2032                Anchor::min()
2033            } else {
2034                snapshot
2035                    .buffer_snapshot
2036                    .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
2037            };
2038            let end_anchor = if end_row > max_row {
2039                Anchor::max()
2040            } else {
2041                snapshot
2042                    .buffer_snapshot
2043                    .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
2044            };
2045
2046            let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
2047            let mut active_rows = BTreeMap::new();
2048            let is_singleton = editor.is_singleton(cx);
2049
2050            let highlighted_rows = editor.highlighted_rows();
2051            let highlighted_ranges = editor.background_highlights_in_range(
2052                start_anchor..end_anchor,
2053                &snapshot.display_snapshot,
2054                cx.theme().colors(),
2055            );
2056
2057            let redacted_ranges = editor.redacted_ranges(start_anchor..end_anchor, &snapshot.display_snapshot, cx);
2058
2059            let mut newest_selection_head = None;
2060
2061            if editor.show_local_selections {
2062                let mut local_selections: Vec<Selection<Point>> = editor
2063                    .selections
2064                    .disjoint_in_range(start_anchor..end_anchor, cx);
2065                local_selections.extend(editor.selections.pending(cx));
2066                let mut layouts = Vec::new();
2067                let newest = editor.selections.newest(cx);
2068                for selection in local_selections.drain(..) {
2069                    let is_empty = selection.start == selection.end;
2070                    let is_newest = selection == newest;
2071
2072                    let layout = SelectionLayout::new(
2073                        selection,
2074                        editor.selections.line_mode,
2075                        editor.cursor_shape,
2076                        &snapshot.display_snapshot,
2077                        is_newest,
2078                        true,
2079                        None,
2080                    );
2081                    if is_newest {
2082                        newest_selection_head = Some(layout.head);
2083                    }
2084
2085                    for row in cmp::max(layout.active_rows.start, start_row)
2086                        ..=cmp::min(layout.active_rows.end, end_row)
2087                    {
2088                        let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
2089                        *contains_non_empty_selection |= !is_empty;
2090                    }
2091                    layouts.push(layout);
2092                }
2093
2094                let player = if editor.read_only(cx) {
2095                    cx.theme().players().read_only()
2096                } else {
2097                    style.local_player
2098                };
2099
2100                selections.push((player, layouts));
2101            }
2102
2103            if let Some(collaboration_hub) = &editor.collaboration_hub {
2104                // When following someone, render the local selections in their color.
2105                if let Some(leader_id) = editor.leader_peer_id {
2106                    if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
2107                        if let Some(participant_index) = collaboration_hub
2108                            .user_participant_indices(cx)
2109                            .get(&collaborator.user_id)
2110                        {
2111                            if let Some((local_selection_style, _)) = selections.first_mut() {
2112                                *local_selection_style = cx
2113                                    .theme()
2114                                    .players()
2115                                    .color_for_participant(participant_index.0);
2116                            }
2117                        }
2118                    }
2119                }
2120
2121                let mut remote_selections = HashMap::default();
2122                for selection in snapshot.remote_selections_in_range(
2123                    &(start_anchor..end_anchor),
2124                    collaboration_hub.as_ref(),
2125                    cx,
2126                ) {
2127                    let selection_style = if let Some(participant_index) = selection.participant_index {
2128                        cx.theme()
2129                            .players()
2130                            .color_for_participant(participant_index.0)
2131                    } else {
2132                        cx.theme().players().absent()
2133                    };
2134
2135                    // Don't re-render the leader's selections, since the local selections
2136                    // match theirs.
2137                    if Some(selection.peer_id) == editor.leader_peer_id {
2138                        continue;
2139                    }
2140                    let key = HoveredCursor{replica_id: selection.replica_id, selection_id: selection.selection.id};
2141
2142                    let is_shown = editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
2143
2144                    remote_selections
2145                        .entry(selection.replica_id)
2146                        .or_insert((selection_style, Vec::new()))
2147                        .1
2148                        .push(SelectionLayout::new(
2149                            selection.selection,
2150                            selection.line_mode,
2151                            selection.cursor_shape,
2152                            &snapshot.display_snapshot,
2153                            false,
2154                            false,
2155                            if is_shown {
2156                                selection.user_name
2157                            } else {
2158                                None
2159                            },
2160                        ));
2161                }
2162
2163                selections.extend(remote_selections.into_values());
2164            }
2165
2166            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
2167            let show_scrollbars = match scrollbar_settings.show {
2168                ShowScrollbar::Auto => {
2169                    // Git
2170                    (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
2171                    ||
2172                    // Selections
2173                    (is_singleton && scrollbar_settings.selections && editor.has_background_highlights::<BufferSearchHighlights>())
2174                    ||
2175                    // Symbols Selections
2176                    (is_singleton && scrollbar_settings.symbols_selections && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
2177                    ||
2178                    // Diagnostics
2179                    (is_singleton && scrollbar_settings.diagnostics && snapshot.buffer_snapshot.has_diagnostics())
2180                    ||
2181                    // Scrollmanager
2182                    editor.scroll_manager.scrollbars_visible()
2183                }
2184                ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
2185                ShowScrollbar::Always => true,
2186                ShowScrollbar::Never => false,
2187            };
2188
2189            let head_for_relative = newest_selection_head.unwrap_or_else(|| {
2190                let newest = editor.selections.newest::<Point>(cx);
2191                SelectionLayout::new(
2192                    newest,
2193                    editor.selections.line_mode,
2194                    editor.cursor_shape,
2195                    &snapshot.display_snapshot,
2196                    true,
2197                    true,
2198                    None,
2199                )
2200                .head
2201            });
2202
2203            let (line_numbers, fold_statuses) = self.shape_line_numbers(
2204                start_row..end_row,
2205                &active_rows,
2206                head_for_relative,
2207                is_singleton,
2208                &snapshot,
2209                cx,
2210            );
2211
2212            let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2213
2214            let scrollbar_row_range = scroll_position.y..(scroll_position.y + height_in_lines);
2215
2216            let mut max_visible_line_width = Pixels::ZERO;
2217            let line_layouts = self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
2218            for line_with_invisibles in &line_layouts {
2219                if line_with_invisibles.line.width > max_visible_line_width {
2220                    max_visible_line_width = line_with_invisibles.line.width;
2221                }
2222            }
2223
2224            let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
2225                .unwrap()
2226                .width;
2227            let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.width;
2228
2229            let (scroll_width, blocks) = cx.with_element_context(|cx| {
2230             cx.with_element_id(Some("editor_blocks"), |cx| {
2231                self.layout_blocks(
2232                    start_row..end_row,
2233                    &snapshot,
2234                    bounds.size.width,
2235                    scroll_width,
2236                    text_width,
2237                    &gutter_dimensions,
2238                    em_width,
2239                    gutter_dimensions.width + gutter_dimensions.margin,
2240                    line_height,
2241                    &style,
2242                    &line_layouts,
2243                    editor,
2244                    cx,
2245                )
2246            })
2247            });
2248
2249            let scroll_max = point(
2250                f32::from((scroll_width - text_size.width) / em_width).max(0.0),
2251                max_row as f32,
2252            );
2253
2254            let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
2255
2256            let autoscrolled = if autoscroll_horizontally {
2257                editor.autoscroll_horizontally(
2258                    start_row,
2259                    text_size.width,
2260                    scroll_width,
2261                    em_width,
2262                    &line_layouts,
2263                    cx,
2264                )
2265            } else {
2266                false
2267            };
2268
2269            if clamped || autoscrolled {
2270                snapshot = editor.snapshot(cx);
2271            }
2272
2273            let gutter_settings = EditorSettings::get_global(cx).gutter;
2274
2275            let mut context_menu = None;
2276            let mut code_actions_indicator = None;
2277            if let Some(newest_selection_head) = newest_selection_head {
2278                if (start_row..end_row).contains(&newest_selection_head.row()) {
2279                    if editor.context_menu_visible() {
2280                        let max_height = cmp::min(
2281                            12. * line_height,
2282                            cmp::max(
2283                                3. * line_height,
2284                                (bounds.size.height - line_height) / 2.,
2285                            )
2286                        );
2287                        context_menu =
2288                            editor.render_context_menu(newest_selection_head, &self.style, max_height, cx);
2289                    }
2290
2291                    let active = matches!(
2292                        editor.context_menu.read().as_ref(),
2293                        Some(crate::ContextMenu::CodeActions(_))
2294                    );
2295
2296                    if gutter_settings.code_actions {
2297                        code_actions_indicator = editor
2298                            .render_code_actions_indicator(&style, active, cx)
2299                            .map(|element| CodeActionsIndicator {
2300                                row: newest_selection_head.row(),
2301                                button: element,
2302                            });
2303                    }
2304                }
2305            }
2306
2307            let visible_rows = start_row..start_row + line_layouts.len() as u32;
2308            let max_size = size(
2309                (120. * em_width) // Default size
2310                    .min(bounds.size.width / 2.) // Shrink to half of the editor width
2311                    .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2312                (16. * line_height) // Default size
2313                    .min(bounds.size.height / 2.) // Shrink to half of the editor height
2314                    .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2315            );
2316
2317            let hover = if context_menu.is_some() {
2318                None
2319            } else {
2320                editor.hover_state.render(
2321                    &snapshot,
2322                    &style,
2323                    visible_rows,
2324                    max_size,
2325                    editor.workspace.as_ref().map(|(w, _)| w.clone()),
2326                    cx,
2327                )
2328            };
2329
2330            let editor_view = cx.view().clone();
2331            let fold_indicators = if gutter_settings.folds {
2332                cx.with_element_context(|cx| {
2333                    cx.with_element_id(Some("gutter_fold_indicators"), |_cx| {
2334                        editor.render_fold_indicators(
2335                            fold_statuses,
2336                            &style,
2337                            editor.gutter_hovered,
2338                            line_height,
2339                            gutter_dimensions.margin,
2340                            editor_view,
2341                        )
2342                    })
2343                })
2344            } else {
2345                Vec::new()
2346            };
2347
2348            let invisible_symbol_font_size = font_size / 2.;
2349            let tab_invisible = cx
2350                .text_system()
2351                .shape_line(
2352                    "".into(),
2353                    invisible_symbol_font_size,
2354                    &[TextRun {
2355                        len: "".len(),
2356                        font: self.style.text.font(),
2357                        color: cx.theme().colors().editor_invisible,
2358                        background_color: None,
2359                        underline: None,
2360                        strikethrough: None,
2361                    }],
2362                )
2363                .unwrap();
2364            let space_invisible = cx
2365                .text_system()
2366                .shape_line(
2367                    "".into(),
2368                    invisible_symbol_font_size,
2369                    &[TextRun {
2370                        len: "".len(),
2371                        font: self.style.text.font(),
2372                        color: cx.theme().colors().editor_invisible,
2373                        background_color: None,
2374                        underline: None,
2375                        strikethrough: None,
2376                    }],
2377                )
2378                .unwrap();
2379
2380            LayoutState {
2381                mode: snapshot.mode,
2382                position_map: Arc::new(PositionMap {
2383                    size: bounds.size,
2384                    scroll_position: point(
2385                        scroll_position.x * em_width,
2386                        scroll_position.y * line_height,
2387                    ),
2388                    scroll_max,
2389                    line_layouts,
2390                    line_height,
2391                    em_width,
2392                    em_advance,
2393                    snapshot,
2394                }),
2395                visible_anchor_range: start_anchor..end_anchor,
2396                visible_display_row_range: start_row..end_row,
2397                wrap_guides,
2398                gutter_size,
2399                gutter_dimensions,
2400                text_size,
2401                scrollbar_row_range,
2402                show_scrollbars,
2403                is_singleton,
2404                max_row,
2405                active_rows,
2406                highlighted_rows,
2407                highlighted_ranges,
2408                redacted_ranges,
2409                line_numbers,
2410                display_hunks,
2411                blocks,
2412                selections,
2413                context_menu,
2414                code_actions_indicator,
2415                fold_indicators,
2416                tab_invisible,
2417                space_invisible,
2418                hover_popovers: hover,
2419            }
2420        })
2421    }
2422
2423    #[allow(clippy::too_many_arguments)]
2424    fn layout_blocks(
2425        &self,
2426        rows: Range<u32>,
2427        snapshot: &EditorSnapshot,
2428        editor_width: Pixels,
2429        scroll_width: Pixels,
2430        text_width: Pixels,
2431        gutter_dimensions: &GutterDimensions,
2432        em_width: Pixels,
2433        text_x: Pixels,
2434        line_height: Pixels,
2435        style: &EditorStyle,
2436        line_layouts: &[LineWithInvisibles],
2437        editor: &mut Editor,
2438        cx: &mut ElementContext,
2439    ) -> (Pixels, Vec<BlockLayout>) {
2440        let mut block_id = 0;
2441        let (fixed_blocks, non_fixed_blocks) = snapshot
2442            .blocks_in_range(rows.clone())
2443            .partition::<Vec<_>, _>(|(_, block)| match block {
2444                TransformBlock::ExcerptHeader { .. } => false,
2445                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
2446            });
2447
2448        let render_block = |block: &TransformBlock,
2449                            available_space: Size<AvailableSpace>,
2450                            block_id: usize,
2451                            editor: &mut Editor,
2452                            cx: &mut ElementContext| {
2453            let mut element = match block {
2454                TransformBlock::Custom(block) => {
2455                    let align_to = block
2456                        .position()
2457                        .to_point(&snapshot.buffer_snapshot)
2458                        .to_display_point(snapshot);
2459                    let anchor_x = text_x
2460                        + if rows.contains(&align_to.row()) {
2461                            line_layouts[(align_to.row() - rows.start) as usize]
2462                                .line
2463                                .x_for_index(align_to.column() as usize)
2464                        } else {
2465                            layout_line(align_to.row(), snapshot, style, cx)
2466                                .unwrap()
2467                                .x_for_index(align_to.column() as usize)
2468                        };
2469
2470                    block.render(&mut BlockContext {
2471                        context: cx,
2472                        anchor_x,
2473                        gutter_dimensions,
2474                        line_height,
2475                        em_width,
2476                        block_id,
2477                        max_width: scroll_width.max(text_width),
2478                        editor_style: &self.style,
2479                    })
2480                }
2481
2482                TransformBlock::ExcerptHeader {
2483                    buffer,
2484                    range,
2485                    starts_new_buffer,
2486                    ..
2487                } => {
2488                    let include_root = editor
2489                        .project
2490                        .as_ref()
2491                        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2492                        .unwrap_or_default();
2493
2494                    let jump_handler = project::File::from_dyn(buffer.file()).map(|file| {
2495                        let jump_path = ProjectPath {
2496                            worktree_id: file.worktree_id(cx),
2497                            path: file.path.clone(),
2498                        };
2499                        let jump_anchor = range
2500                            .primary
2501                            .as_ref()
2502                            .map_or(range.context.start, |primary| primary.start);
2503                        let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
2504
2505                        cx.listener_for(&self.editor, move |editor, _, cx| {
2506                            editor.jump(jump_path.clone(), jump_position, jump_anchor, cx);
2507                        })
2508                    });
2509
2510                    let element = if *starts_new_buffer {
2511                        let path = buffer.resolve_file_path(cx, include_root);
2512                        let mut filename = None;
2513                        let mut parent_path = None;
2514                        // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
2515                        if let Some(path) = path {
2516                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
2517                            parent_path = path
2518                                .parent()
2519                                .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
2520                        }
2521
2522                        v_flex()
2523                            .id(("path header container", block_id))
2524                            .size_full()
2525                            .justify_center()
2526                            .p(gpui::px(6.))
2527                            .child(
2528                                h_flex()
2529                                    .id("path header block")
2530                                    .size_full()
2531                                    .pl(gpui::px(12.))
2532                                    .pr(gpui::px(8.))
2533                                    .rounded_md()
2534                                    .shadow_md()
2535                                    .border()
2536                                    .border_color(cx.theme().colors().border)
2537                                    .bg(cx.theme().colors().editor_subheader_background)
2538                                    .justify_between()
2539                                    .hover(|style| style.bg(cx.theme().colors().element_hover))
2540                                    .child(
2541                                        h_flex().gap_3().child(
2542                                            h_flex()
2543                                                .gap_2()
2544                                                .child(
2545                                                    filename
2546                                                        .map(SharedString::from)
2547                                                        .unwrap_or_else(|| "untitled".into()),
2548                                                )
2549                                                .when_some(parent_path, |then, path| {
2550                                                    then.child(
2551                                                        div().child(path).text_color(
2552                                                            cx.theme().colors().text_muted,
2553                                                        ),
2554                                                    )
2555                                                }),
2556                                        ),
2557                                    )
2558                                    .when_some(jump_handler, |this, jump_handler| {
2559                                        this.cursor_pointer()
2560                                            .tooltip(|cx| {
2561                                                Tooltip::for_action(
2562                                                    "Jump to Buffer",
2563                                                    &OpenExcerpts,
2564                                                    cx,
2565                                                )
2566                                            })
2567                                            .on_mouse_down(MouseButton::Left, |_, cx| {
2568                                                cx.stop_propagation()
2569                                            })
2570                                            .on_click(jump_handler)
2571                                    }),
2572                            )
2573                    } else {
2574                        h_flex()
2575                            .id(("collapsed context", block_id))
2576                            .size_full()
2577                            .gap(gutter_dimensions.left_padding + gutter_dimensions.right_padding)
2578                            .child(
2579                                h_flex()
2580                                    .justify_end()
2581                                    .flex_none()
2582                                    .w(gutter_dimensions.width
2583                                        - (gutter_dimensions.left_padding
2584                                            + gutter_dimensions.right_padding))
2585                                    .h_full()
2586                                    .text_buffer(cx)
2587                                    .text_color(cx.theme().colors().editor_line_number)
2588                                    .child("..."),
2589                            )
2590                            .child(
2591                                ButtonLike::new("jump to collapsed context")
2592                                    .style(ButtonStyle::Transparent)
2593                                    .full_width()
2594                                    .child(
2595                                        div()
2596                                            .h_px()
2597                                            .w_full()
2598                                            .bg(cx.theme().colors().border_variant)
2599                                            .group_hover("", |style| {
2600                                                style.bg(cx.theme().colors().border)
2601                                            }),
2602                                    )
2603                                    .when_some(jump_handler, |this, jump_handler| {
2604                                        this.on_click(jump_handler).tooltip(|cx| {
2605                                            Tooltip::for_action("Jump to Buffer", &OpenExcerpts, cx)
2606                                        })
2607                                    }),
2608                            )
2609                    };
2610                    element.into_any()
2611                }
2612            };
2613
2614            let size = element.measure(available_space, cx);
2615            (element, size)
2616        };
2617
2618        let mut fixed_block_max_width = Pixels::ZERO;
2619        let mut blocks = Vec::new();
2620        for (row, block) in fixed_blocks {
2621            let available_space = size(
2622                AvailableSpace::MinContent,
2623                AvailableSpace::Definite(block.height() as f32 * line_height),
2624            );
2625            let (element, element_size) =
2626                render_block(block, available_space, block_id, editor, cx);
2627            block_id += 1;
2628            fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2629            blocks.push(BlockLayout {
2630                row,
2631                element,
2632                available_space,
2633                style: BlockStyle::Fixed,
2634            });
2635        }
2636        for (row, block) in non_fixed_blocks {
2637            let style = match block {
2638                TransformBlock::Custom(block) => block.style(),
2639                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
2640            };
2641            let width = match style {
2642                BlockStyle::Sticky => editor_width,
2643                BlockStyle::Flex => editor_width
2644                    .max(fixed_block_max_width)
2645                    .max(gutter_dimensions.width + scroll_width),
2646                BlockStyle::Fixed => unreachable!(),
2647            };
2648            let available_space = size(
2649                AvailableSpace::Definite(width),
2650                AvailableSpace::Definite(block.height() as f32 * line_height),
2651            );
2652            let (element, _) = render_block(block, available_space, block_id, editor, cx);
2653            block_id += 1;
2654            blocks.push(BlockLayout {
2655                row,
2656                element,
2657                available_space,
2658                style,
2659            });
2660        }
2661        (
2662            scroll_width.max(fixed_block_max_width - gutter_dimensions.width),
2663            blocks,
2664        )
2665    }
2666
2667    fn paint_scroll_wheel_listener(
2668        &mut self,
2669        interactive_bounds: &InteractiveBounds,
2670        layout: &LayoutState,
2671        cx: &mut ElementContext,
2672    ) {
2673        cx.on_mouse_event({
2674            let position_map = layout.position_map.clone();
2675            let editor = self.editor.clone();
2676            let interactive_bounds = interactive_bounds.clone();
2677            let mut delta = ScrollDelta::default();
2678
2679            move |event: &ScrollWheelEvent, phase, cx| {
2680                if phase == DispatchPhase::Bubble
2681                    && interactive_bounds.visibly_contains(&event.position, cx)
2682                {
2683                    delta = delta.coalesce(event.delta);
2684                    editor.update(cx, |editor, cx| {
2685                        let position = event.position;
2686                        let position_map: &PositionMap = &position_map;
2687                        let bounds = &interactive_bounds;
2688                        if !bounds.visibly_contains(&position, cx) {
2689                            return;
2690                        }
2691
2692                        let line_height = position_map.line_height;
2693                        let max_glyph_width = position_map.em_width;
2694                        let (delta, axis) = match delta {
2695                            gpui::ScrollDelta::Pixels(mut pixels) => {
2696                                //Trackpad
2697                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
2698                                (pixels, axis)
2699                            }
2700
2701                            gpui::ScrollDelta::Lines(lines) => {
2702                                //Not trackpad
2703                                let pixels =
2704                                    point(lines.x * max_glyph_width, lines.y * line_height);
2705                                (pixels, None)
2706                            }
2707                        };
2708
2709                        let scroll_position = position_map.snapshot.scroll_position();
2710                        let x = f32::from(
2711                            (scroll_position.x * max_glyph_width - delta.x) / max_glyph_width,
2712                        );
2713                        let y =
2714                            f32::from((scroll_position.y * line_height - delta.y) / line_height);
2715                        let scroll_position =
2716                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
2717                        editor.scroll(scroll_position, axis, cx);
2718                        cx.stop_propagation();
2719                    });
2720                }
2721            }
2722        });
2723    }
2724
2725    fn paint_mouse_listeners(
2726        &mut self,
2727        bounds: Bounds<Pixels>,
2728        gutter_bounds: Bounds<Pixels>,
2729        text_bounds: Bounds<Pixels>,
2730        layout: &LayoutState,
2731        cx: &mut ElementContext,
2732    ) {
2733        let interactive_bounds = InteractiveBounds {
2734            bounds: bounds.intersect(&cx.content_mask().bounds),
2735            stacking_order: cx.stacking_order().clone(),
2736        };
2737
2738        self.paint_scroll_wheel_listener(&interactive_bounds, layout, cx);
2739
2740        cx.on_mouse_event({
2741            let position_map = layout.position_map.clone();
2742            let editor = self.editor.clone();
2743            let stacking_order = cx.stacking_order().clone();
2744            let interactive_bounds = interactive_bounds.clone();
2745
2746            move |event: &MouseDownEvent, phase, cx| {
2747                if phase == DispatchPhase::Bubble
2748                    && interactive_bounds.visibly_contains(&event.position, cx)
2749                {
2750                    match event.button {
2751                        MouseButton::Left => editor.update(cx, |editor, cx| {
2752                            Self::mouse_left_down(
2753                                editor,
2754                                event,
2755                                &position_map,
2756                                text_bounds,
2757                                gutter_bounds,
2758                                &stacking_order,
2759                                cx,
2760                            );
2761                        }),
2762                        MouseButton::Right => editor.update(cx, |editor, cx| {
2763                            Self::mouse_right_down(editor, event, &position_map, text_bounds, cx);
2764                        }),
2765                        _ => {}
2766                    };
2767                }
2768            }
2769        });
2770
2771        cx.on_mouse_event({
2772            let position_map = layout.position_map.clone();
2773            let editor = self.editor.clone();
2774            let stacking_order = cx.stacking_order().clone();
2775            let interactive_bounds = interactive_bounds.clone();
2776
2777            move |event: &MouseUpEvent, phase, cx| {
2778                if phase == DispatchPhase::Bubble {
2779                    editor.update(cx, |editor, cx| {
2780                        Self::mouse_up(
2781                            editor,
2782                            event,
2783                            &position_map,
2784                            text_bounds,
2785                            &interactive_bounds,
2786                            &stacking_order,
2787                            cx,
2788                        )
2789                    });
2790                }
2791            }
2792        });
2793        cx.on_mouse_event({
2794            let position_map = layout.position_map.clone();
2795            let editor = self.editor.clone();
2796            let stacking_order = cx.stacking_order().clone();
2797
2798            move |event: &MouseMoveEvent, phase, cx| {
2799                // if editor.has_pending_selection() && event.pressed_button == Some(MouseButton::Left) {
2800
2801                if phase == DispatchPhase::Bubble {
2802                    editor.update(cx, |editor, cx| {
2803                        if event.pressed_button == Some(MouseButton::Left) {
2804                            Self::mouse_dragged(
2805                                editor,
2806                                event,
2807                                &position_map,
2808                                text_bounds,
2809                                gutter_bounds,
2810                                &stacking_order,
2811                                cx,
2812                            )
2813                        }
2814
2815                        if interactive_bounds.visibly_contains(&event.position, cx) {
2816                            Self::mouse_moved(
2817                                editor,
2818                                event,
2819                                &position_map,
2820                                text_bounds,
2821                                gutter_bounds,
2822                                &stacking_order,
2823                                cx,
2824                            )
2825                        }
2826                    });
2827                }
2828            }
2829        });
2830    }
2831}
2832
2833#[derive(Debug)]
2834pub(crate) struct LineWithInvisibles {
2835    pub line: ShapedLine,
2836    invisibles: Vec<Invisible>,
2837}
2838
2839impl LineWithInvisibles {
2840    fn from_chunks<'a>(
2841        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
2842        text_style: &TextStyle,
2843        max_line_len: usize,
2844        max_line_count: usize,
2845        line_number_layouts: &[Option<ShapedLine>],
2846        editor_mode: EditorMode,
2847        cx: &WindowContext,
2848    ) -> Vec<Self> {
2849        let mut layouts = Vec::with_capacity(max_line_count);
2850        let mut line = String::new();
2851        let mut invisibles = Vec::new();
2852        let mut styles = Vec::new();
2853        let mut non_whitespace_added = false;
2854        let mut row = 0;
2855        let mut line_exceeded_max_len = false;
2856        let font_size = text_style.font_size.to_pixels(cx.rem_size());
2857
2858        for highlighted_chunk in chunks.chain([HighlightedChunk {
2859            chunk: "\n",
2860            style: None,
2861            is_tab: false,
2862        }]) {
2863            for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
2864                if ix > 0 {
2865                    let shaped_line = cx
2866                        .text_system()
2867                        .shape_line(line.clone().into(), font_size, &styles)
2868                        .unwrap();
2869                    layouts.push(Self {
2870                        line: shaped_line,
2871                        invisibles: invisibles.drain(..).collect(),
2872                    });
2873
2874                    line.clear();
2875                    styles.clear();
2876                    row += 1;
2877                    line_exceeded_max_len = false;
2878                    non_whitespace_added = false;
2879                    if row == max_line_count {
2880                        return layouts;
2881                    }
2882                }
2883
2884                if !line_chunk.is_empty() && !line_exceeded_max_len {
2885                    let text_style = if let Some(style) = highlighted_chunk.style {
2886                        Cow::Owned(text_style.clone().highlight(style))
2887                    } else {
2888                        Cow::Borrowed(text_style)
2889                    };
2890
2891                    if line.len() + line_chunk.len() > max_line_len {
2892                        let mut chunk_len = max_line_len - line.len();
2893                        while !line_chunk.is_char_boundary(chunk_len) {
2894                            chunk_len -= 1;
2895                        }
2896                        line_chunk = &line_chunk[..chunk_len];
2897                        line_exceeded_max_len = true;
2898                    }
2899
2900                    styles.push(TextRun {
2901                        len: line_chunk.len(),
2902                        font: text_style.font(),
2903                        color: text_style.color,
2904                        background_color: text_style.background_color,
2905                        underline: text_style.underline,
2906                        strikethrough: text_style.strikethrough,
2907                    });
2908
2909                    if editor_mode == EditorMode::Full {
2910                        // Line wrap pads its contents with fake whitespaces,
2911                        // avoid printing them
2912                        let inside_wrapped_string = line_number_layouts
2913                            .get(row)
2914                            .and_then(|layout| layout.as_ref())
2915                            .is_none();
2916                        if highlighted_chunk.is_tab {
2917                            if non_whitespace_added || !inside_wrapped_string {
2918                                invisibles.push(Invisible::Tab {
2919                                    line_start_offset: line.len(),
2920                                });
2921                            }
2922                        } else {
2923                            invisibles.extend(
2924                                line_chunk
2925                                    .chars()
2926                                    .enumerate()
2927                                    .filter(|(_, line_char)| {
2928                                        let is_whitespace = line_char.is_whitespace();
2929                                        non_whitespace_added |= !is_whitespace;
2930                                        is_whitespace
2931                                            && (non_whitespace_added || !inside_wrapped_string)
2932                                    })
2933                                    .map(|(whitespace_index, _)| Invisible::Whitespace {
2934                                        line_offset: line.len() + whitespace_index,
2935                                    }),
2936                            )
2937                        }
2938                    }
2939
2940                    line.push_str(line_chunk);
2941                }
2942            }
2943        }
2944
2945        layouts
2946    }
2947
2948    fn draw(
2949        &self,
2950        layout: &LayoutState,
2951        row: u32,
2952        content_origin: gpui::Point<Pixels>,
2953        whitespace_setting: ShowWhitespaceSetting,
2954        selection_ranges: &[Range<DisplayPoint>],
2955        cx: &mut ElementContext,
2956    ) {
2957        let line_height = layout.position_map.line_height;
2958        let line_y = line_height * row as f32 - layout.position_map.scroll_position.y;
2959
2960        self.line
2961            .paint(
2962                content_origin + gpui::point(-layout.position_map.scroll_position.x, line_y),
2963                line_height,
2964                cx,
2965            )
2966            .log_err();
2967
2968        self.draw_invisibles(
2969            &selection_ranges,
2970            layout,
2971            content_origin,
2972            line_y,
2973            row,
2974            line_height,
2975            whitespace_setting,
2976            cx,
2977        );
2978    }
2979
2980    fn draw_invisibles(
2981        &self,
2982        selection_ranges: &[Range<DisplayPoint>],
2983        layout: &LayoutState,
2984        content_origin: gpui::Point<Pixels>,
2985        line_y: Pixels,
2986        row: u32,
2987        line_height: Pixels,
2988        whitespace_setting: ShowWhitespaceSetting,
2989        cx: &mut ElementContext,
2990    ) {
2991        let allowed_invisibles_regions = match whitespace_setting {
2992            ShowWhitespaceSetting::None => return,
2993            ShowWhitespaceSetting::Selection => Some(selection_ranges),
2994            ShowWhitespaceSetting::All => None,
2995        };
2996
2997        for invisible in &self.invisibles {
2998            let (&token_offset, invisible_symbol) = match invisible {
2999                Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
3000                Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
3001            };
3002
3003            let x_offset = self.line.x_for_index(token_offset);
3004            let invisible_offset =
3005                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
3006            let origin = content_origin
3007                + gpui::point(
3008                    x_offset + invisible_offset - layout.position_map.scroll_position.x,
3009                    line_y,
3010                );
3011
3012            if let Some(allowed_regions) = allowed_invisibles_regions {
3013                let invisible_point = DisplayPoint::new(row, token_offset as u32);
3014                if !allowed_regions
3015                    .iter()
3016                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
3017                {
3018                    continue;
3019                }
3020            }
3021            invisible_symbol.paint(origin, line_height, cx).log_err();
3022        }
3023    }
3024}
3025
3026#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3027enum Invisible {
3028    Tab { line_start_offset: usize },
3029    Whitespace { line_offset: usize },
3030}
3031
3032impl Element for EditorElement {
3033    type State = ();
3034
3035    fn request_layout(
3036        &mut self,
3037        _element_state: Option<Self::State>,
3038        cx: &mut gpui::ElementContext,
3039    ) -> (gpui::LayoutId, Self::State) {
3040        cx.with_view_id(self.editor.entity_id(), |cx| {
3041            self.editor.update(cx, |editor, cx| {
3042                editor.set_style(self.style.clone(), cx);
3043
3044                let layout_id = match editor.mode {
3045                    EditorMode::SingleLine => {
3046                        let rem_size = cx.rem_size();
3047                        let mut style = Style::default();
3048                        style.size.width = relative(1.).into();
3049                        style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
3050                        cx.with_element_context(|cx| cx.request_layout(&style, None))
3051                    }
3052                    EditorMode::AutoHeight { max_lines } => {
3053                        let editor_handle = cx.view().clone();
3054                        let max_line_number_width =
3055                            self.max_line_number_width(&editor.snapshot(cx), cx);
3056                        cx.with_element_context(|cx| {
3057                            cx.request_measured_layout(
3058                                Style::default(),
3059                                move |known_dimensions, _, cx| {
3060                                    editor_handle
3061                                        .update(cx, |editor, cx| {
3062                                            compute_auto_height_layout(
3063                                                editor,
3064                                                max_lines,
3065                                                max_line_number_width,
3066                                                known_dimensions,
3067                                                cx,
3068                                            )
3069                                        })
3070                                        .unwrap_or_default()
3071                                },
3072                            )
3073                        })
3074                    }
3075                    EditorMode::Full => {
3076                        let mut style = Style::default();
3077                        style.size.width = relative(1.).into();
3078                        style.size.height = relative(1.).into();
3079                        cx.with_element_context(|cx| cx.request_layout(&style, None))
3080                    }
3081                };
3082
3083                (layout_id, ())
3084            })
3085        })
3086    }
3087
3088    fn paint(
3089        &mut self,
3090        bounds: Bounds<gpui::Pixels>,
3091        _element_state: &mut Self::State,
3092        cx: &mut gpui::ElementContext,
3093    ) {
3094        let editor = self.editor.clone();
3095
3096        cx.paint_view(self.editor.entity_id(), |cx| {
3097            cx.with_text_style(
3098                Some(gpui::TextStyleRefinement {
3099                    font_size: Some(self.style.text.font_size),
3100                    line_height: Some(self.style.text.line_height),
3101                    ..Default::default()
3102                }),
3103                |cx| {
3104                    let mut layout = self.compute_layout(bounds, cx);
3105                    let gutter_bounds = Bounds {
3106                        origin: bounds.origin,
3107                        size: layout.gutter_size,
3108                    };
3109                    let text_bounds = Bounds {
3110                        origin: gutter_bounds.upper_right(),
3111                        size: layout.text_size,
3112                    };
3113
3114                    let focus_handle = editor.focus_handle(cx);
3115                    let key_context = self.editor.read(cx).key_context(cx);
3116                    cx.with_key_dispatch(Some(key_context), Some(focus_handle.clone()), |_, cx| {
3117                        self.register_actions(cx);
3118
3119                        cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3120                            self.register_key_listeners(cx, text_bounds, &layout);
3121                            cx.handle_input(
3122                                &focus_handle,
3123                                ElementInputHandler::new(bounds, self.editor.clone()),
3124                            );
3125
3126                            self.paint_background(gutter_bounds, text_bounds, &layout, cx);
3127                            if layout.gutter_size.width > Pixels::ZERO {
3128                                self.paint_gutter(gutter_bounds, &mut layout, cx);
3129                            }
3130                            self.paint_text(text_bounds, &mut layout, cx);
3131
3132                            cx.with_z_index(0, |cx| {
3133                                self.paint_mouse_listeners(
3134                                    bounds,
3135                                    gutter_bounds,
3136                                    text_bounds,
3137                                    &layout,
3138                                    cx,
3139                                );
3140                            });
3141                            if !layout.blocks.is_empty() {
3142                                cx.with_z_index(0, |cx| {
3143                                    cx.with_element_id(Some("editor_blocks"), |cx| {
3144                                        self.paint_blocks(bounds, &mut layout, cx);
3145                                    });
3146                                })
3147                            }
3148
3149                            cx.with_z_index(1, |cx| {
3150                                self.paint_overlays(text_bounds, &mut layout, cx);
3151                            });
3152
3153                            cx.with_z_index(2, |cx| self.paint_scrollbar(bounds, &mut layout, cx));
3154                        });
3155                    })
3156                },
3157            )
3158        })
3159    }
3160}
3161
3162impl IntoElement for EditorElement {
3163    type Element = Self;
3164
3165    fn element_id(&self) -> Option<gpui::ElementId> {
3166        self.editor.element_id()
3167    }
3168
3169    fn into_element(self) -> Self::Element {
3170        self
3171    }
3172}
3173
3174type BufferRow = u32;
3175
3176pub struct LayoutState {
3177    position_map: Arc<PositionMap>,
3178    gutter_size: Size<Pixels>,
3179    gutter_dimensions: GutterDimensions,
3180    text_size: gpui::Size<Pixels>,
3181    mode: EditorMode,
3182    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
3183    visible_anchor_range: Range<Anchor>,
3184    visible_display_row_range: Range<u32>,
3185    active_rows: BTreeMap<u32, bool>,
3186    highlighted_rows: Option<Range<u32>>,
3187    line_numbers: Vec<Option<ShapedLine>>,
3188    display_hunks: Vec<DisplayDiffHunk>,
3189    blocks: Vec<BlockLayout>,
3190    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3191    redacted_ranges: Vec<Range<DisplayPoint>>,
3192    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
3193    scrollbar_row_range: Range<f32>,
3194    show_scrollbars: bool,
3195    is_singleton: bool,
3196    max_row: u32,
3197    context_menu: Option<(DisplayPoint, AnyElement)>,
3198    code_actions_indicator: Option<CodeActionsIndicator>,
3199    hover_popovers: Option<(DisplayPoint, Vec<AnyElement>)>,
3200    fold_indicators: Vec<Option<IconButton>>,
3201    tab_invisible: ShapedLine,
3202    space_invisible: ShapedLine,
3203}
3204
3205impl LayoutState {
3206    fn line_end_overshoot(&self) -> Pixels {
3207        0.15 * self.position_map.line_height
3208    }
3209}
3210
3211struct CodeActionsIndicator {
3212    row: u32,
3213    button: IconButton,
3214}
3215
3216struct PositionMap {
3217    size: Size<Pixels>,
3218    line_height: Pixels,
3219    scroll_position: gpui::Point<Pixels>,
3220    scroll_max: gpui::Point<f32>,
3221    em_width: Pixels,
3222    em_advance: Pixels,
3223    line_layouts: Vec<LineWithInvisibles>,
3224    snapshot: EditorSnapshot,
3225}
3226
3227#[derive(Debug, Copy, Clone)]
3228pub struct PointForPosition {
3229    pub previous_valid: DisplayPoint,
3230    pub next_valid: DisplayPoint,
3231    pub exact_unclipped: DisplayPoint,
3232    pub column_overshoot_after_line_end: u32,
3233}
3234
3235impl PointForPosition {
3236    pub fn as_valid(&self) -> Option<DisplayPoint> {
3237        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
3238            Some(self.previous_valid)
3239        } else {
3240            None
3241        }
3242    }
3243}
3244
3245impl PositionMap {
3246    fn point_for_position(
3247        &self,
3248        text_bounds: Bounds<Pixels>,
3249        position: gpui::Point<Pixels>,
3250    ) -> PointForPosition {
3251        let scroll_position = self.snapshot.scroll_position();
3252        let position = position - text_bounds.origin;
3253        let y = position.y.max(px(0.)).min(self.size.height);
3254        let x = position.x + (scroll_position.x * self.em_width);
3255        let row = (f32::from(y / self.line_height) + scroll_position.y) as u32;
3256
3257        let (column, x_overshoot_after_line_end) = if let Some(line) = self
3258            .line_layouts
3259            .get(row as usize - scroll_position.y as usize)
3260            .map(|&LineWithInvisibles { ref line, .. }| line)
3261        {
3262            if let Some(ix) = line.index_for_x(x) {
3263                (ix as u32, px(0.))
3264            } else {
3265                (line.len as u32, px(0.).max(x - line.width))
3266            }
3267        } else {
3268            (0, x)
3269        };
3270
3271        let mut exact_unclipped = DisplayPoint::new(row, column);
3272        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
3273        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
3274
3275        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
3276        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
3277        PointForPosition {
3278            previous_valid,
3279            next_valid,
3280            exact_unclipped,
3281            column_overshoot_after_line_end,
3282        }
3283    }
3284}
3285
3286struct BlockLayout {
3287    row: u32,
3288    element: AnyElement,
3289    available_space: Size<AvailableSpace>,
3290    style: BlockStyle,
3291}
3292
3293fn layout_line(
3294    row: u32,
3295    snapshot: &EditorSnapshot,
3296    style: &EditorStyle,
3297    cx: &WindowContext,
3298) -> Result<ShapedLine> {
3299    let mut line = snapshot.line(row);
3300
3301    if line.len() > MAX_LINE_LEN {
3302        let mut len = MAX_LINE_LEN;
3303        while !line.is_char_boundary(len) {
3304            len -= 1;
3305        }
3306
3307        line.truncate(len);
3308    }
3309
3310    cx.text_system().shape_line(
3311        line.into(),
3312        style.text.font_size.to_pixels(cx.rem_size()),
3313        &[TextRun {
3314            len: snapshot.line_len(row) as usize,
3315            font: style.text.font(),
3316            color: Hsla::default(),
3317            background_color: None,
3318            underline: None,
3319            strikethrough: None,
3320        }],
3321    )
3322}
3323
3324#[derive(Debug)]
3325pub struct Cursor {
3326    origin: gpui::Point<Pixels>,
3327    block_width: Pixels,
3328    line_height: Pixels,
3329    color: Hsla,
3330    shape: CursorShape,
3331    block_text: Option<ShapedLine>,
3332    cursor_name: Option<CursorName>,
3333}
3334
3335#[derive(Debug)]
3336pub struct CursorName {
3337    string: SharedString,
3338    color: Hsla,
3339    is_top_row: bool,
3340    z_index: u16,
3341}
3342
3343impl Cursor {
3344    pub fn new(
3345        origin: gpui::Point<Pixels>,
3346        block_width: Pixels,
3347        line_height: Pixels,
3348        color: Hsla,
3349        shape: CursorShape,
3350        block_text: Option<ShapedLine>,
3351        cursor_name: Option<CursorName>,
3352    ) -> Cursor {
3353        Cursor {
3354            origin,
3355            block_width,
3356            line_height,
3357            color,
3358            shape,
3359            block_text,
3360            cursor_name,
3361        }
3362    }
3363
3364    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3365        Bounds {
3366            origin: self.origin + origin,
3367            size: size(self.block_width, self.line_height),
3368        }
3369    }
3370
3371    pub fn paint(&self, origin: gpui::Point<Pixels>, cx: &mut ElementContext) {
3372        let bounds = match self.shape {
3373            CursorShape::Bar => Bounds {
3374                origin: self.origin + origin,
3375                size: size(px(2.0), self.line_height),
3376            },
3377            CursorShape::Block | CursorShape::Hollow => Bounds {
3378                origin: self.origin + origin,
3379                size: size(self.block_width, self.line_height),
3380            },
3381            CursorShape::Underscore => Bounds {
3382                origin: self.origin
3383                    + origin
3384                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
3385                size: size(self.block_width, px(2.0)),
3386            },
3387        };
3388
3389        //Draw background or border quad
3390        let cursor = if matches!(self.shape, CursorShape::Hollow) {
3391            outline(bounds, self.color)
3392        } else {
3393            fill(bounds, self.color)
3394        };
3395
3396        if let Some(name) = &self.cursor_name {
3397            let text_size = self.line_height / 1.5;
3398
3399            let name_origin = if name.is_top_row {
3400                point(bounds.right() - px(1.), bounds.top())
3401            } else {
3402                point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
3403            };
3404            cx.with_z_index(name.z_index, |cx| {
3405                div()
3406                    .bg(self.color)
3407                    .text_size(text_size)
3408                    .px_0p5()
3409                    .line_height(text_size + px(2.))
3410                    .text_color(name.color)
3411                    .child(name.string.clone())
3412                    .into_any_element()
3413                    .draw(
3414                        name_origin,
3415                        size(AvailableSpace::MinContent, AvailableSpace::MinContent),
3416                        cx,
3417                    )
3418            })
3419        }
3420
3421        cx.paint_quad(cursor);
3422
3423        if let Some(block_text) = &self.block_text {
3424            block_text
3425                .paint(self.origin + origin, self.line_height, cx)
3426                .log_err();
3427        }
3428    }
3429
3430    pub fn shape(&self) -> CursorShape {
3431        self.shape
3432    }
3433}
3434
3435#[derive(Debug)]
3436pub struct HighlightedRange {
3437    pub start_y: Pixels,
3438    pub line_height: Pixels,
3439    pub lines: Vec<HighlightedRangeLine>,
3440    pub color: Hsla,
3441    pub corner_radius: Pixels,
3442}
3443
3444#[derive(Debug)]
3445pub struct HighlightedRangeLine {
3446    pub start_x: Pixels,
3447    pub end_x: Pixels,
3448}
3449
3450impl HighlightedRange {
3451    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut ElementContext) {
3452        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
3453            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
3454            self.paint_lines(
3455                self.start_y + self.line_height,
3456                &self.lines[1..],
3457                bounds,
3458                cx,
3459            );
3460        } else {
3461            self.paint_lines(self.start_y, &self.lines, bounds, cx);
3462        }
3463    }
3464
3465    fn paint_lines(
3466        &self,
3467        start_y: Pixels,
3468        lines: &[HighlightedRangeLine],
3469        _bounds: Bounds<Pixels>,
3470        cx: &mut ElementContext,
3471    ) {
3472        if lines.is_empty() {
3473            return;
3474        }
3475
3476        let first_line = lines.first().unwrap();
3477        let last_line = lines.last().unwrap();
3478
3479        let first_top_left = point(first_line.start_x, start_y);
3480        let first_top_right = point(first_line.end_x, start_y);
3481
3482        let curve_height = point(Pixels::ZERO, self.corner_radius);
3483        let curve_width = |start_x: Pixels, end_x: Pixels| {
3484            let max = (end_x - start_x) / 2.;
3485            let width = if max < self.corner_radius {
3486                max
3487            } else {
3488                self.corner_radius
3489            };
3490
3491            point(width, Pixels::ZERO)
3492        };
3493
3494        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
3495        let mut path = gpui::Path::new(first_top_right - top_curve_width);
3496        path.curve_to(first_top_right + curve_height, first_top_right);
3497
3498        let mut iter = lines.iter().enumerate().peekable();
3499        while let Some((ix, line)) = iter.next() {
3500            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
3501
3502            if let Some((_, next_line)) = iter.peek() {
3503                let next_top_right = point(next_line.end_x, bottom_right.y);
3504
3505                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
3506                    Ordering::Equal => {
3507                        path.line_to(bottom_right);
3508                    }
3509                    Ordering::Less => {
3510                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
3511                        path.line_to(bottom_right - curve_height);
3512                        if self.corner_radius > Pixels::ZERO {
3513                            path.curve_to(bottom_right - curve_width, bottom_right);
3514                        }
3515                        path.line_to(next_top_right + curve_width);
3516                        if self.corner_radius > Pixels::ZERO {
3517                            path.curve_to(next_top_right + curve_height, next_top_right);
3518                        }
3519                    }
3520                    Ordering::Greater => {
3521                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
3522                        path.line_to(bottom_right - curve_height);
3523                        if self.corner_radius > Pixels::ZERO {
3524                            path.curve_to(bottom_right + curve_width, bottom_right);
3525                        }
3526                        path.line_to(next_top_right - curve_width);
3527                        if self.corner_radius > Pixels::ZERO {
3528                            path.curve_to(next_top_right + curve_height, next_top_right);
3529                        }
3530                    }
3531                }
3532            } else {
3533                let curve_width = curve_width(line.start_x, line.end_x);
3534                path.line_to(bottom_right - curve_height);
3535                if self.corner_radius > Pixels::ZERO {
3536                    path.curve_to(bottom_right - curve_width, bottom_right);
3537                }
3538
3539                let bottom_left = point(line.start_x, bottom_right.y);
3540                path.line_to(bottom_left + curve_width);
3541                if self.corner_radius > Pixels::ZERO {
3542                    path.curve_to(bottom_left - curve_height, bottom_left);
3543                }
3544            }
3545        }
3546
3547        if first_line.start_x > last_line.start_x {
3548            let curve_width = curve_width(last_line.start_x, first_line.start_x);
3549            let second_top_left = point(last_line.start_x, start_y + self.line_height);
3550            path.line_to(second_top_left + curve_height);
3551            if self.corner_radius > Pixels::ZERO {
3552                path.curve_to(second_top_left + curve_width, second_top_left);
3553            }
3554            let first_bottom_left = point(first_line.start_x, second_top_left.y);
3555            path.line_to(first_bottom_left - curve_width);
3556            if self.corner_radius > Pixels::ZERO {
3557                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
3558            }
3559        }
3560
3561        path.line_to(first_top_left + curve_height);
3562        if self.corner_radius > Pixels::ZERO {
3563            path.curve_to(first_top_left + top_curve_width, first_top_left);
3564        }
3565        path.line_to(first_top_right - top_curve_width);
3566
3567        cx.paint_path(path, self.color);
3568    }
3569}
3570
3571pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3572    (delta.pow(1.5) / 100.0).into()
3573}
3574
3575fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3576    (delta.pow(1.2) / 300.0).into()
3577}
3578
3579#[cfg(test)]
3580mod tests {
3581    use super::*;
3582    use crate::{
3583        display_map::{BlockDisposition, BlockProperties},
3584        editor_tests::{init_test, update_test_language_settings},
3585        Editor, MultiBuffer,
3586    };
3587    use gpui::TestAppContext;
3588    use language::language_settings;
3589    use log::info;
3590    use std::{num::NonZeroU32, sync::Arc};
3591    use util::test::sample_text;
3592
3593    #[gpui::test]
3594    fn test_shape_line_numbers(cx: &mut TestAppContext) {
3595        init_test(cx, |_| {});
3596        let window = cx.add_window(|cx| {
3597            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3598            Editor::new(EditorMode::Full, buffer, None, cx)
3599        });
3600
3601        let editor = window.root(cx).unwrap();
3602        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3603        let element = EditorElement::new(&editor, style);
3604
3605        let layouts = window
3606            .update(cx, |editor, cx| {
3607                let snapshot = editor.snapshot(cx);
3608                element
3609                    .shape_line_numbers(
3610                        0..6,
3611                        &Default::default(),
3612                        DisplayPoint::new(0, 0),
3613                        false,
3614                        &snapshot,
3615                        cx,
3616                    )
3617                    .0
3618            })
3619            .unwrap();
3620        assert_eq!(layouts.len(), 6);
3621
3622        let relative_rows = window
3623            .update(cx, |editor, cx| {
3624                let snapshot = editor.snapshot(cx);
3625                element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
3626            })
3627            .unwrap();
3628        assert_eq!(relative_rows[&0], 3);
3629        assert_eq!(relative_rows[&1], 2);
3630        assert_eq!(relative_rows[&2], 1);
3631        // current line has no relative number
3632        assert_eq!(relative_rows[&4], 1);
3633        assert_eq!(relative_rows[&5], 2);
3634
3635        // works if cursor is before screen
3636        let relative_rows = window
3637            .update(cx, |editor, cx| {
3638                let snapshot = editor.snapshot(cx);
3639
3640                element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
3641            })
3642            .unwrap();
3643        assert_eq!(relative_rows.len(), 3);
3644        assert_eq!(relative_rows[&3], 2);
3645        assert_eq!(relative_rows[&4], 3);
3646        assert_eq!(relative_rows[&5], 4);
3647
3648        // works if cursor is after screen
3649        let relative_rows = window
3650            .update(cx, |editor, cx| {
3651                let snapshot = editor.snapshot(cx);
3652
3653                element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
3654            })
3655            .unwrap();
3656        assert_eq!(relative_rows.len(), 3);
3657        assert_eq!(relative_rows[&0], 5);
3658        assert_eq!(relative_rows[&1], 4);
3659        assert_eq!(relative_rows[&2], 3);
3660    }
3661
3662    #[gpui::test]
3663    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
3664        init_test(cx, |_| {});
3665
3666        let window = cx.add_window(|cx| {
3667            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
3668            Editor::new(EditorMode::Full, buffer, None, cx)
3669        });
3670        let editor = window.root(cx).unwrap();
3671        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3672        let mut element = EditorElement::new(&editor, style);
3673
3674        window
3675            .update(cx, |editor, cx| {
3676                editor.cursor_shape = CursorShape::Block;
3677                editor.change_selections(None, cx, |s| {
3678                    s.select_ranges([
3679                        Point::new(0, 0)..Point::new(1, 0),
3680                        Point::new(3, 2)..Point::new(3, 3),
3681                        Point::new(5, 6)..Point::new(6, 0),
3682                    ]);
3683                });
3684            })
3685            .unwrap();
3686        let state = cx
3687            .update_window(window.into(), |view, cx| {
3688                cx.with_element_context(|cx| {
3689                    cx.with_view_id(view.entity_id(), |cx| {
3690                        element.compute_layout(
3691                            Bounds {
3692                                origin: point(px(500.), px(500.)),
3693                                size: size(px(500.), px(500.)),
3694                            },
3695                            cx,
3696                        )
3697                    })
3698                })
3699            })
3700            .unwrap();
3701
3702        assert_eq!(state.selections.len(), 1);
3703        let local_selections = &state.selections[0].1;
3704        assert_eq!(local_selections.len(), 3);
3705        // moves cursor back one line
3706        assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
3707        assert_eq!(
3708            local_selections[0].range,
3709            DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
3710        );
3711
3712        // moves cursor back one column
3713        assert_eq!(
3714            local_selections[1].range,
3715            DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
3716        );
3717        assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
3718
3719        // leaves cursor on the max point
3720        assert_eq!(
3721            local_selections[2].range,
3722            DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
3723        );
3724        assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
3725
3726        // active lines does not include 1 (even though the range of the selection does)
3727        assert_eq!(
3728            state.active_rows.keys().cloned().collect::<Vec<u32>>(),
3729            vec![0, 3, 5, 6]
3730        );
3731
3732        // multi-buffer support
3733        // in DisplayPoint coordinates, this is what we're dealing with:
3734        //  0: [[file
3735        //  1:   header]]
3736        //  2: aaaaaa
3737        //  3: bbbbbb
3738        //  4: cccccc
3739        //  5:
3740        //  6: ...
3741        //  7: ffffff
3742        //  8: gggggg
3743        //  9: hhhhhh
3744        // 10:
3745        // 11: [[file
3746        // 12:   header]]
3747        // 13: bbbbbb
3748        // 14: cccccc
3749        // 15: dddddd
3750        let window = cx.add_window(|cx| {
3751            let buffer = MultiBuffer::build_multi(
3752                [
3753                    (
3754                        &(sample_text(8, 6, 'a') + "\n"),
3755                        vec![
3756                            Point::new(0, 0)..Point::new(3, 0),
3757                            Point::new(4, 0)..Point::new(7, 0),
3758                        ],
3759                    ),
3760                    (
3761                        &(sample_text(8, 6, 'a') + "\n"),
3762                        vec![Point::new(1, 0)..Point::new(3, 0)],
3763                    ),
3764                ],
3765                cx,
3766            );
3767            Editor::new(EditorMode::Full, buffer, None, cx)
3768        });
3769        let editor = window.root(cx).unwrap();
3770        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3771        let mut element = EditorElement::new(&editor, style);
3772        let _state = window.update(cx, |editor, cx| {
3773            editor.cursor_shape = CursorShape::Block;
3774            editor.change_selections(None, cx, |s| {
3775                s.select_display_ranges([
3776                    DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
3777                    DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
3778                ]);
3779            });
3780        });
3781
3782        let state = cx
3783            .update_window(window.into(), |view, cx| {
3784                cx.with_element_context(|cx| {
3785                    cx.with_view_id(view.entity_id(), |cx| {
3786                        element.compute_layout(
3787                            Bounds {
3788                                origin: point(px(500.), px(500.)),
3789                                size: size(px(500.), px(500.)),
3790                            },
3791                            cx,
3792                        )
3793                    })
3794                })
3795            })
3796            .unwrap();
3797        assert_eq!(state.selections.len(), 1);
3798        let local_selections = &state.selections[0].1;
3799        assert_eq!(local_selections.len(), 2);
3800
3801        // moves cursor on excerpt boundary back a line
3802        // and doesn't allow selection to bleed through
3803        assert_eq!(
3804            local_selections[0].range,
3805            DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
3806        );
3807        assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
3808        // moves cursor on buffer boundary back two lines
3809        // and doesn't allow selection to bleed through
3810        assert_eq!(
3811            local_selections[1].range,
3812            DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
3813        );
3814        assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
3815    }
3816
3817    #[gpui::test]
3818    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
3819        init_test(cx, |_| {});
3820
3821        let window = cx.add_window(|cx| {
3822            let buffer = MultiBuffer::build_simple("", cx);
3823            Editor::new(EditorMode::Full, buffer, None, cx)
3824        });
3825        let editor = window.root(cx).unwrap();
3826        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3827        window
3828            .update(cx, |editor, cx| {
3829                editor.set_placeholder_text("hello", cx);
3830                editor.insert_blocks(
3831                    [BlockProperties {
3832                        style: BlockStyle::Fixed,
3833                        disposition: BlockDisposition::Above,
3834                        height: 3,
3835                        position: Anchor::min(),
3836                        render: Arc::new(|_| div().into_any()),
3837                    }],
3838                    None,
3839                    cx,
3840                );
3841
3842                // Blur the editor so that it displays placeholder text.
3843                cx.blur();
3844            })
3845            .unwrap();
3846
3847        let mut element = EditorElement::new(&editor, style);
3848        let state = cx
3849            .update_window(window.into(), |view, cx| {
3850                cx.with_element_context(|cx| {
3851                    cx.with_view_id(view.entity_id(), |cx| {
3852                        element.compute_layout(
3853                            Bounds {
3854                                origin: point(px(500.), px(500.)),
3855                                size: size(px(500.), px(500.)),
3856                            },
3857                            cx,
3858                        )
3859                    })
3860                })
3861            })
3862            .unwrap();
3863        let size = state.position_map.size;
3864
3865        assert_eq!(state.position_map.line_layouts.len(), 4);
3866        assert_eq!(
3867            state
3868                .line_numbers
3869                .iter()
3870                .map(Option::is_some)
3871                .collect::<Vec<_>>(),
3872            &[false, false, false, true]
3873        );
3874
3875        // Don't panic.
3876        let bounds = Bounds::<Pixels>::new(Default::default(), size);
3877        cx.update_window(window.into(), |_, cx| {
3878            cx.with_element_context(|cx| element.paint(bounds, &mut (), cx))
3879        })
3880        .unwrap()
3881    }
3882
3883    #[gpui::test]
3884    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
3885        const TAB_SIZE: u32 = 4;
3886
3887        let input_text = "\t \t|\t| a b";
3888        let expected_invisibles = vec![
3889            Invisible::Tab {
3890                line_start_offset: 0,
3891            },
3892            Invisible::Whitespace {
3893                line_offset: TAB_SIZE as usize,
3894            },
3895            Invisible::Tab {
3896                line_start_offset: TAB_SIZE as usize + 1,
3897            },
3898            Invisible::Tab {
3899                line_start_offset: TAB_SIZE as usize * 2 + 1,
3900            },
3901            Invisible::Whitespace {
3902                line_offset: TAB_SIZE as usize * 3 + 1,
3903            },
3904            Invisible::Whitespace {
3905                line_offset: TAB_SIZE as usize * 3 + 3,
3906            },
3907        ];
3908        assert_eq!(
3909            expected_invisibles.len(),
3910            input_text
3911                .chars()
3912                .filter(|initial_char| initial_char.is_whitespace())
3913                .count(),
3914            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3915        );
3916
3917        init_test(cx, |s| {
3918            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3919            s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
3920        });
3921
3922        let actual_invisibles =
3923            collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
3924
3925        assert_eq!(expected_invisibles, actual_invisibles);
3926    }
3927
3928    #[gpui::test]
3929    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
3930        init_test(cx, |s| {
3931            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3932            s.defaults.tab_size = NonZeroU32::new(4);
3933        });
3934
3935        for editor_mode_without_invisibles in [
3936            EditorMode::SingleLine,
3937            EditorMode::AutoHeight { max_lines: 100 },
3938        ] {
3939            let invisibles = collect_invisibles_from_new_editor(
3940                cx,
3941                editor_mode_without_invisibles,
3942                "\t\t\t| | a b",
3943                px(500.0),
3944            );
3945            assert!(invisibles.is_empty(),
3946                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
3947        }
3948    }
3949
3950    #[gpui::test]
3951    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
3952        let tab_size = 4;
3953        let input_text = "a\tbcd   ".repeat(9);
3954        let repeated_invisibles = [
3955            Invisible::Tab {
3956                line_start_offset: 1,
3957            },
3958            Invisible::Whitespace {
3959                line_offset: tab_size as usize + 3,
3960            },
3961            Invisible::Whitespace {
3962                line_offset: tab_size as usize + 4,
3963            },
3964            Invisible::Whitespace {
3965                line_offset: tab_size as usize + 5,
3966            },
3967        ];
3968        let expected_invisibles = std::iter::once(repeated_invisibles)
3969            .cycle()
3970            .take(9)
3971            .flatten()
3972            .collect::<Vec<_>>();
3973        assert_eq!(
3974            expected_invisibles.len(),
3975            input_text
3976                .chars()
3977                .filter(|initial_char| initial_char.is_whitespace())
3978                .count(),
3979            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3980        );
3981        info!("Expected invisibles: {expected_invisibles:?}");
3982
3983        init_test(cx, |_| {});
3984
3985        // Put the same string with repeating whitespace pattern into editors of various size,
3986        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
3987        let resize_step = 10.0;
3988        let mut editor_width = 200.0;
3989        while editor_width <= 1000.0 {
3990            update_test_language_settings(cx, |s| {
3991                s.defaults.tab_size = NonZeroU32::new(tab_size);
3992                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3993                s.defaults.preferred_line_length = Some(editor_width as u32);
3994                s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
3995            });
3996
3997            let actual_invisibles = collect_invisibles_from_new_editor(
3998                cx,
3999                EditorMode::Full,
4000                &input_text,
4001                px(editor_width),
4002            );
4003
4004            // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4005            // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4006            let mut i = 0;
4007            for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4008                i = actual_index;
4009                match expected_invisibles.get(i) {
4010                    Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4011                        (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4012                        | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4013                        _ => {
4014                            panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4015                        }
4016                    },
4017                    None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4018                }
4019            }
4020            let missing_expected_invisibles = &expected_invisibles[i + 1..];
4021            assert!(
4022                missing_expected_invisibles.is_empty(),
4023                "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4024            );
4025
4026            editor_width += resize_step;
4027        }
4028    }
4029
4030    fn collect_invisibles_from_new_editor(
4031        cx: &mut TestAppContext,
4032        editor_mode: EditorMode,
4033        input_text: &str,
4034        editor_width: Pixels,
4035    ) -> Vec<Invisible> {
4036        info!(
4037            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
4038            editor_width.0
4039        );
4040        let window = cx.add_window(|cx| {
4041            let buffer = MultiBuffer::build_simple(&input_text, cx);
4042            Editor::new(editor_mode, buffer, None, cx)
4043        });
4044        let editor = window.root(cx).unwrap();
4045        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4046        let mut element = EditorElement::new(&editor, style);
4047        window
4048            .update(cx, |editor, cx| {
4049                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4050                editor.set_wrap_width(Some(editor_width), cx);
4051            })
4052            .unwrap();
4053        let layout_state = cx
4054            .update_window(window.into(), |_, cx| {
4055                cx.with_element_context(|cx| {
4056                    element.compute_layout(
4057                        Bounds {
4058                            origin: point(px(500.), px(500.)),
4059                            size: size(px(500.), px(500.)),
4060                        },
4061                        cx,
4062                    )
4063                })
4064            })
4065            .unwrap();
4066
4067        layout_state
4068            .position_map
4069            .line_layouts
4070            .iter()
4071            .map(|line_with_invisibles| &line_with_invisibles.invisibles)
4072            .flatten()
4073            .cloned()
4074            .collect()
4075    }
4076}
4077
4078pub fn register_action<T: Action>(
4079    view: &View<Editor>,
4080    cx: &mut WindowContext,
4081    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
4082) {
4083    let view = view.clone();
4084    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
4085        let action = action.downcast_ref().unwrap();
4086        if phase == DispatchPhase::Bubble {
4087            view.update(cx, |editor, cx| {
4088                listener(editor, action, cx);
4089            })
4090        }
4091    })
4092}
4093
4094fn compute_auto_height_layout(
4095    editor: &mut Editor,
4096    max_lines: usize,
4097    max_line_number_width: Pixels,
4098    known_dimensions: Size<Option<Pixels>>,
4099    cx: &mut ViewContext<Editor>,
4100) -> Option<Size<Pixels>> {
4101    let width = known_dimensions.width?;
4102    if let Some(height) = known_dimensions.height {
4103        return Some(size(width, height));
4104    }
4105
4106    let style = editor.style.as_ref().unwrap();
4107    let font_id = cx.text_system().resolve_font(&style.text.font());
4108    let font_size = style.text.font_size.to_pixels(cx.rem_size());
4109    let line_height = style.text.line_height_in_pixels(cx.rem_size());
4110    let em_width = cx
4111        .text_system()
4112        .typographic_bounds(font_id, font_size, 'm')
4113        .unwrap()
4114        .size
4115        .width;
4116
4117    let mut snapshot = editor.snapshot(cx);
4118    let gutter_dimensions =
4119        snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
4120
4121    editor.gutter_width = gutter_dimensions.width;
4122    let text_width = width - gutter_dimensions.width;
4123    let overscroll = size(em_width, px(0.));
4124
4125    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
4126    if editor.set_wrap_width(Some(editor_width), cx) {
4127        snapshot = editor.snapshot(cx);
4128    }
4129
4130    let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
4131    let height = scroll_height
4132        .max(line_height)
4133        .min(line_height * max_lines as f32);
4134
4135    Some(size(width, height))
4136}