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