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