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