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