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