element.rs

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