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