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