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