element.rs

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