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