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