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